    public function open($savePath, $sessionName)
    {
        $return = (bool) $this->handler->open($savePath, $sessionName);

        if (true === $return) {
            $this->active = true;
        }

        return $return;
    }


	function show_vendor () {
		$vendor = new vendor();

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			$vendor_title = $vendor->title;
			$state = new geoRegion($vendor->state);
			$vendor->state = $state->name;
			//Removed unnecessary fields
			unset(
                $vendor->title,
                $vendor->table,
                $vendor->tablename,
                $vendor->classname,
                $vendor->identifier
            );

			assign_to_template(array(
                'vendor_title' => $vendor_title,
                'vendor'=>$vendor
            ));
		}
	}


    public function enable()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $swimlane_id = $this->request->getIntegerParam('swimlane_id');

        if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane updated successfully.'));
        } else {
            $this->flash->failure(t('Unable to update this swimlane.'));
        }

        $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
    }


	public static function doTablesUpdate($definition){
		$updateInformation = self::getTablesStatus($definition);
		$db = ezcDbInstance::get();

        $errorMessages = array();

		try {
            $db->query('SET GLOBAL innodb_strict_mode = 0;');
            $db->query('SET GLOBAL innodb_file_per_table=1;');
            $db->query('SET GLOBAL innodb_large_prefix=1;');
        } catch (Exception $e) {
            //$errorMessages[] = $e->getMessage();
        }

		foreach ($updateInformation as $table => $tableData) {
			if ($tableData['error'] == true) {
				foreach ($tableData['queries'] as $query) {
					try {
						$db->query($query);
					} catch (Exception $e) {
						$errorMessages[] = $e->getMessage();
					}
				}
			}
		}

		return $errorMessages;
	}


	 function manage_upcharge() {
		$this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
		$this->config = $config->config;

		$gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all',null,'rank asc,name asc');
        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions,
            'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
        ));
	 }


    protected function getSubtask()
    {
        $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));

        if (empty($subtask)) {
            throw new PageNotFoundException();
        }

        return $subtask;
    }


    public static function isPublic($s) {
        if ($s == null) {
            return false;
        }
        while ($s->public && $s->parent > 0) {
            $s = new section($s->parent);
        }
        $lineage = (($s->public) ? 1 : 0);
        return $lineage;
    }


            recyclebin::sendToRecycleBin($loc, $parent);
            //FIXME if we delete the module & sectionref the module completely disappears
//            if (class_exists($secref->module)) {
//                $modclass = $secref->module;
//                //FIXME: more module/controller glue code
//                if (expModules::controllerExists($modclass)) {
//                    $modclass = expModules::getControllerClassName($modclass);
//                    $mod = new $modclass($loc->src);
//                    $mod->delete_instance();
//                } else {
//                    $mod = new $modclass();
//                    $mod->deleteIn($loc);
//                }
//            }
        }
//        $db->delete('sectionref', 'section=' . $parent);
        $db->delete('section', 'parent=' . $parent);
    }


    public function confirm()
    {
        $project = $this->getProject();
        $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));

        $this->response->html($this->helper->layout->project('custom_filter/remove', array(
            'project' => $project,
            'filter' => $filter,
            'title' => t('Remove a custom filter')
        )));
    }


    public function update_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);
        // find required shipping method if needed
        if ($this->params['required_shipping_calculator_id'] > 0) {
            $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];
        } else {
            $this->params['required_shipping_calculator_id'] = 0;
        }

        $discount->update($this->params);
        expHistory::back();
    }


    function delete_selected() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item && $item->is_recurring == 1) {
            $event_remaining = false;
            $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);
            foreach ($eventdates as $ed) {
                if (array_key_exists($ed->id, $this->params['dates'])) {
                    $ed->delete();
                } else {
                    $event_remaining = true;
                }
            }
            if (!$event_remaining) {
                $item->delete(); // model will also ensure we delete all event dates
            }
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }


            $date->delete(); // event automatically deleted if all assoc eventdates are deleted
        }
        expHistory::back();
    }


   public function updateForgottenPassword(array $input) {
      $condition = [
         'glpi_users.is_active'  => 1,
         'glpi_users.is_deleted' => 0, [
            'OR' => [
               ['glpi_users.begin_date' => null],
               ['glpi_users.begin_date' => ['<', new QueryExpression('NOW()')]]
            ],
         ], [
            'OR'  => [
               ['glpi_users.end_date'   => null],
               ['glpi_users.end_date'   => ['>', new QueryExpression('NOW()')]]
            ]
         ]
      ];
      if ($this->getFromDBbyEmail($input['email'], $condition)) {
         if (($this->fields["authtype"] == Auth::DB_GLPI)
             || !Auth::useAuthExt()) {

            if (($input['password_forget_token'] == $this->fields['password_forget_token'])
                && (abs(strtotime($_SESSION["glpi_currenttime"])
                        -strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP)) {

               $input['id'] = $this->fields['id'];
               Config::validatePassword($input["password"], false); // Throws exception if password is invalid
               if (!$this->update($input)) {
                  return false;
               }
               $input2 = [
                  'password_forget_token'      => '',
                  'password_forget_token_date' => null,
                  'id'                         => $this->fields['id']
               ];
               $this->update($input2);
               return true;

            } else {
               throw new ForgetPasswordException(__('Your password reset request has expired or is invalid. Please renew it.'));
            }

         } else {
            throw new ForgetPasswordException(__("The authentication method configuration doesn't allow you to change your password."));
         }

      } else {
         throw new ForgetPasswordException(__('Email address not found.'));
      }

      return false;
   }


    function edit_freeform() {
        $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
        if ($section->parent == -1) {
            notfoundController::handle_not_found();
            exit;
        } // doesn't work for standalone pages
        if (empty($section->id)) {
            $section->public = 1;
            if (!isset($section->parent)) {
                // This is another precaution.  The parent attribute
                // should ALWAYS be set by the caller.
                //FJD - if that's the case, then we should die.
                notfoundController::handle_not_authorized();
                exit;
                //$section->parent = 0;
            }
        }
        assign_to_template(array(
            'section' => $section,
            'glyphs' => self::get_glyphs(),
        ));
    }


    function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
        if (empty($endtimestamp)) {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
        } else {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
        }
        if ($multiday)
            $date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
        $date_sql .= ")";
        return $date_sql;
    }


public function display_sdm_other_details_meta_box($post) { //Other details metabox
	$file_size = get_post_meta($post->ID, 'sdm_item_file_size', true);
	$file_size = isset($file_size) ? $file_size : '';

	$version = get_post_meta($post->ID, 'sdm_item_version', true);
	$version = isset($version) ? $version : '';

	echo '
';
	_e('File Size: ', 'simple-download-monitor');
	echo '
';
	echo ' <input type="text" name="sdm_item_file_size" value="' . $file_size . '" size="20" />';
	echo '
' . __('Enter the size of this file (example value: 2.15 MB). You can show this value in the fancy display by using a shortcode parameter.', 'simple-download-monitor') . '
';
	echo '
';

	echo '
';
	_e('Version: ', 'simple-download-monitor');
	echo '
';
	echo ' <input type="text" name="sdm_item_version" value="' . $version . '" size="20" />';
	echo '
' . __('Enter the version number for this item if any (example value: v2.5.10). You can show this value in the fancy display by using a shortcode parameter.', 'simple-download-monitor') . '
';
	echo '
';

	wp_nonce_field('sdm_other_details_nonce', 'sdm_other_details_nonce_check');
    }


    public function getQuerySelect()
    {
        return "c.submitted_by AS `" . $this->name . "`";
    }


    public function autocomplete() {
        return;
        global $db;

        $model = $this->params['model'];
        $mod = new $model();
        $srchcol = explode(",",$this->params['searchoncol']);
        /*for ($i=0; $i<count($srchcol); $i++) {
            if ($i>=1) $sql .= " OR ";
            $sql .= $srchcol[$i].' LIKE \'%'.$this->params['query'].'%\'';
        }*/
        //    $sql .= ' AND parent_id=0';
        //eDebug($sql);

        //$res = $mod->find('all',$sql,'id',25);
        $sql = "select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from ".$db->prefix."product as p INNER JOIN ".$db->prefix."content_expfiles as cef ON p.id=cef.content_id INNER JOIN ".$db->prefix."expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') desc LIMIT 25";
        //$res = $db->selectObjectsBySql($sql);
        //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');

        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    public function testNewInstanceWhenNewProtocol()
    {
        $r = new Response(200);
        $this->assertNotSame($r, $r->withProtocolVersion('1.0'));
    }


	protected function _rmdir($path) {
		$ret = @rmdir($path);
		$ret && clearstatcache();
		return $ret;
	}


    public function remove()
    {
        $project = $this->getProject();
        $this->checkCSRFParam();
        $column_id = $this->request->getIntegerParam('column_id');

        if ($this->columnModel->remove($column_id)) {
            $this->flash->success(t('Column removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this column.'));
        }

        $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));
    }


    function delete() {
        global $db;

        if (empty($this->params['id'])) return false;
        $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);
        $product = new $product_type($this->params['id'], true, false);
        //eDebug($product_type);
        //eDebug($product, true);
        //if (!empty($product->product_type_id)) {
        //$db->delete($product_type, 'id='.$product->product_id);
        //}

        $db->delete('option', 'product_id=' . $product->id . " AND optiongroup_id IN (SELECT id from " . $db->prefix . "optiongroup WHERE product_id=" . $product->id . ")");
        $db->delete('optiongroup', 'product_id=' . $product->id);
        //die();
        $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type="' . $product_type . '"');

        if ($product->product_type == "product") {
            if ($product->hasChildren()) {
                $this->deleteChildren();
            }
        }

        $product->delete();

        flash('message', gt('Product deleted successfully.'));
        expHistory::back();
    }


    public function testNewInstanceWhenNewBody()
    {
        $r = new Response(200, [], 'foo');
        $b2 = Psr7\stream_for('abc');
        $this->assertNotSame($r, $r->withBody($b2));
    }


    public function breadcrumb() {
        global $sectionObj;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // Show not only the location of a page in the hierarchy but also the location of a standalone page
        $current = new section($id);
        if ($current->parent == -1) {  // standalone page
            $navsections = section::levelTemplate(-1, 0);
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        } else {
            $navsections = section::levelTemplate(0, 0);
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
        ));
    }


public static function parseAndTrimImport($str, $isHTML = false) { //�Death from above�? �
        //echo "1
"; eDebug($str);
//        global $db;

        $str = str_replace("�", "’", $str);
        $str = str_replace("�", "‘", $str);
        $str = str_replace("�", "®", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "—", $str);
        $str = str_replace("�", "”", $str);
        $str = str_replace("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\,", ",", $str);
        $str = str_replace('""', '"', $str); //do this no matter what...in case someone added a quote in a non HTML field
        if (!$isHTML) {
            //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char
            $str = str_replace('"', """, $str);
        }
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "™", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "™", $str)));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


public function display_sdm_upload_meta_box($post) {  // File Upload metabox
	$old_upload = get_post_meta($post->ID, 'sdm_upload', true);
	$old_value = isset($old_upload) ? $old_upload : '';

	_e('Manually enter a valid URL of the file in the text box below, or click "Select File" button to upload (or choose) the downloadable file.', 'simple-download-monitor');
	echo '

';

	echo '
';
	echo '<input id="sdm_upload" type="text" size="100" name="sdm_upload" value="' . $old_value . '" placeholder="http://..." />';
	echo '
';

	echo '
';
	echo '<input id="upload_image_button" type="button" class="button-primary" value="' . __('Select File', 'simple-download-monitor') . '" />';

	echo '

';
	_e('Steps to upload a file or choose one from your media library:', 'simple-download-monitor');
	echo '
';
	echo '
Hit the "Select File" button.
';
	echo '
Upload a new file or choose an existing one from your media library.
';
	echo '
Click the "Insert" button, this will populate the uploaded file\'s URL in the above text field.
';
	echo '
';

	wp_nonce_field('sdm_upload_box_nonce', 'sdm_upload_box_nonce_check');
    }


    function __construct()
    {
        $this->render_menu_page();
    }


    public function routePostProvider()
    {
        return [
            ['/api/articles/',     1, 'articles', 'post', false],
            ['/api/v1/articles/',  1, 'articles', 'post', false],
            ['/api/v2/articles/',  2, 'articles', 'post', false],
            ['/api/articles/5',    1, 'articles', 'post', 5],
            ['/api/v1/articles/5', 1, 'articles', 'post', 5],
            ['/api/v2/articles/5', 2, 'articles', 'post', 5],
        ];
    }


    function edit_order_item() {
        $oi = new orderitem($this->params['id'], true, true);
        if (empty($oi->id)) {
            flash('error', gt('Order item doesn\'t exist.'));
            expHistory::back();
        }
        $oi->user_input_fields = expUnserialize($oi->user_input_fields);
        $params['options'] = $oi->opts;
        $params['user_input_fields'] = $oi->user_input_fields;
        $oi->product           = new product($oi->product->id, true, true);
        if ($oi->product->parent_id != 0) {
            $parProd = new product($oi->product->parent_id);
            //$oi->product->optiongroup = $parProd->optiongroup;
            $oi->product = $parProd;
        }
        //FIXME we don't use selectedOpts?
//        $oi->selectedOpts = array();
//        if (!empty($oi->opts)) {
//            foreach ($oi->opts as $opt) {
//                $option = new option($opt[0]);
//                $og     = new optiongroup($option->optiongroup_id);
//                if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))
//                    $oi->selectedOpts[$og->id] = array($option->id);
//                else
//                    array_push($oi->selectedOpts[$og->id], $option->id);
//            }
//        }
        //eDebug($oi->selectedOpts);

        assign_to_template(array(
            'oi' => $oi,
            'params' => $params
        ));
    }


	public static function pathFile($path, $file=false)
	{
		if($file!==false){
			$fullPath = $path.$file;
		}
		else {
			$fullPath = $path;
		}

		// Fix for Windows on paths. eg: $path = c:\diego/page/subpage convert to c:\diego\page\subpages
		$fullPath = str_replace('/', DS, $fullPath);

		if(CHECK_SYMBOLIC_LINKS) {
			$real = realpath($fullPath);
		}
		else {
			$real = file_exists($fullPath)?$fullPath:false;
		}

		// If $real is FALSE the file does not exist.
		if($real===false) {
			return false;
		}

		// If the $real path does not start with the systemPath then this is Path Traversal.
		if(strpos($fullPath, $real)!==0) {
			return false;
		}

		return true;
	}


			$eml->prepareBody();
		}

        list ($success, $message) = $this->checkDoNotEmailFields ($eml);
        if (!$success) {
            return array ($success, $message);
        }

		$result = $eml->send($historyFlag);
		if (isset($result['code']) && $result['code'] == 200) {
            if (YII_UNIT_TESTING) {
                return array(true, $eml->message);
            } else {
                return array(true, "");
            }
        } else {
            return array (false, Yii::t('app', "Email could not be sent"));
        }
	}


    public static function Zipped () {

        global $HTTP_ACCEPT_ENCODING;

        if( headers_sent() ){

            $encoding = false;

        }elseif( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ){

            $encoding = 'x-gzip';

        }elseif( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){

            $encoding = 'gzip';

        }else{

            $encoding = false;

        }

        if( $encoding ){

            $contents = ob_get_contents();
            ob_end_clean();
            header('Content-Encoding: '.$encoding);
            print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
            $size = strlen($contents);
            $contents = gzcompress($contents, 9);
            $contents = substr($contents, 0, $size);
            print($contents);
            exit();

        }else{

            ob_end_flush();
            exit();

        }
    }


    private function doTestEncodeFormulas(bool $legacy = false)
    {
        if ($legacy) {
            $this->encoder = new CsvEncoder(',', '"', '\\', '.', true);
        } else {
            $this->encoder = new CsvEncoder([CsvEncoder::ESCAPE_FORMULAS_KEY => true]);
        }

        $this->assertSame(<<<'CSV'
0
"	=2+3"

CSV
            , $this->encoder->encode(['=2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	-2+3"

CSV
            , $this->encoder->encode(['-2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	+2+3"

CSV
            , $this->encoder->encode(['+2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	@MyDataColumn"

CSV
            , $this->encoder->encode(['@MyDataColumn'], 'csv'));
    }


            $comments->records[$key]->avatar = $db->selectObject('user_avatar',"user_id='".$record->poster."'");
        }

        if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);
        // eDebug($sql, true);

        // count the unapproved comments
        if ($require_approval == 1 && $user->isAdmin()) {
            $sql  = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';
            $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';
            $sql .= 'WHERE cnt.content_id='.$this->params['content_id']." AND cnt.content_type='".$this->params['content_type']."' ";
            $sql .= 'AND com.approved=0';
            $unapproved = $db->countObjectsBySql($sql);
        } else {
            $unapproved = 0;
        }

        $this->config = $this->params['config'];
        $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');
        $ratings = !empty($this->params['ratings']) ? true : false;

        assign_to_template(array(
            'comments'=>$comments,
            'config'=>$this->params['config'],
            'unapproved'=>$unapproved,
			'content_id'=>$this->params['content_id'],
			'content_type'=>$this->params['content_type'],
			'user'=>$user,
			'hideform'=>$this->params['hideform'],
			'hidecomments'=>$this->params['hidecomments'],
			'title'=>$this->params['title'],
			'formtitle'=>$this->params['formtitle'],
            'type'=>$type,
            'ratings'=>$ratings,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
		));
	}


    public function get_view_config() {
        global $template;

        // set paths we will search in for the view
        $paths = array(
            BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',
            BASE.'framework/modules/common/views/file/configure',
        );

        foreach ($paths as $path) {
            $view = $path.'/'.$this->params['view'].'.tpl';
            if (is_readable($view)) {
                if (bs(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                if (bs3(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                $template = new controllertemplate($this, $view);
                $ar = new expAjaxReply(200, 'ok');
		        $ar->send();
            }
        }
    }


function singleQuoteReplace($param1 = false, $param2 = false, $param3)
{
    return str_replace("'", "''", str_replace("\'", "'", $param3));
}


public static function format ($post, $id) {
        // split post for readmore...
        $post = Typo::Xclean($post);
        $more = explode('[[--readmore--]]', $post);
        //print_r($more);
        if (count($more) > 1) {
            $post = explode('[[--readmore--]]', $post);
            $post = $post[0]." ".READ_MORE."";
        }else{
            $post = $post;
        }

        $post = Hooks::filter('post_content_filter', $post);
        return $post;
    }


    public function show()
    {
        $task = $this->getTask();
        $subtask = $this->getSubtask();

        $this->response->html($this->template->render('subtask_converter/show', array(
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    public function testCanCreateNewResponseWithStatusAndNoReason()
    {
        $r = new Response(200);
        $r2 = $r->withStatus(201);
        $this->assertEquals(200, $r->getStatusCode());
        $this->assertEquals('OK', $r->getReasonPhrase());
        $this->assertEquals(201, $r2->getStatusCode());
        $this->assertEquals('Created', $r2->getReasonPhrase());
    }


                return $fa->nameGlyph($icons, 'icon-');
            }
        } else {
            return array();
        }
    }


    function insertObject($object, $table) {
        //if ($table=="text") eDebug($object,true);
        $sql = "INSERT INTO `" . $this->prefix . "$table` (";
        $values = ") VALUES (";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            if ($var{0} != '_') {
                $sql .= "`$var`,";
                if ($values != ") VALUES (") {
                    $values .= ",";
                }
                $values .= "'" . mysqli_real_escape_string($this->connection, $val) . "'";
            }
        }
        $sql = substr($sql, 0, -1) . substr($values, 0) . ")";
        //if($table=='text')eDebug($sql,true);
        if (@mysqli_query($this->connection, $sql) != false) {
            $id = mysqli_insert_id($this->connection);
            return $id;
        } else
            return 0;
    }


	public function approvedFileExtension($filename, $type = 'image')
	{
		$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		if ($type == 'image') {
			switch ($ext) {
				case 'gif':
				case 'png':
				case 'jpeg':
				case 'jpg':
				case 'svg':
					return true;
				default:
					return false;
			}
		} elseif ($type == 'cert') {
			switch ($ext) {
				case 'pem':
					return true;
				default:
					return false;
			}
		}
	}


            $section  = new section($this->params);
        } else {
            notfoundController::handle_not_found();
            exit;
        }
        if (!empty($section->id)) {
            $check_id = $section->id;
        } else {
            $check_id = $section->parent;
        }
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {
            if (empty($section->id)) {
                $section->active = 1;
                $section->public = 1;
                if (!isset($section->parent)) {
                    // This is another precaution.  The parent attribute
                    // should ALWAYS be set by the caller.
                    //FJD - if that's the case, then we should die.
                    notfoundController::handle_not_authorized();
                    exit;
                    //$section->parent = 0;
                }
            }
            assign_to_template(array(
                'section' => $section,
                'glyphs' => self::get_glyphs(),
            ));
        } else {  // User does not have permission to manage sections.  Throw a 403
            notfoundController::handle_not_authorized();
        }
    }


$logo = "";
        }else{
            $logo = "";
        }
        return $logo;
    }


    public function saveconfig() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        $conf = serialize($calc->parseConfig($this->params));
        $calc->update(array('config'=>$conf));
        expHistory::back();
    }


    public static function TimeZone(){
        $timezones = DateTimeZone::listAbbreviations(DateTimeZone::ALL);

        $cities = array();
        foreach( $timezones as $key => $zones )
        {
            foreach( $zones as $id => $zone )
            {
                //print_r($zone);
                /**
                 * Only get timezones explicitely not part of "Others".
                 * @see http://www.php.net/manual/en/timezones.others.php
                 */
                if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $zone['timezone_id'] )
                    && $zone['timezone_id']) {
                    $cities[$zone['timezone_id']][] = $key;
                }
            }
        }

        // For each city, have a comma separated list of all possible timezones for that city.
        foreach( $cities as $key => $value )
            $cities[$key] = join( ', ', $value);

        // Only keep one city (the first and also most important) for each set of possibilities.
        $cities = array_unique( $cities );

        // Sort by area/city name.
        ksort( $cities );

        return $cities;
    }


$user = db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($check['user']), 'username');
			form_alternate_row('line' . $check['id']);
			$name = get_data_source_title($check['datasource']);
			$title = $name;
			if (strlen($name) > 50) {
				$name = substr($name, 0, 50);
			}
			form_selectable_cell('' . $name . '', $check['id']);
			form_selectable_cell($user, $check['id']);
			form_selectable_cell(date('F j, Y, G:i', $check['started']), $check['id']);
			form_selectable_cell($check['datasource'], $check['id']);
			form_selectable_cell(debug_icon(($check['done'] ? (strlen($issue_line) ? 'off' : 'on' ) : '')), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_writable']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_exists']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['active']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_match']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['valid_data']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon(($info['rra_timestamp2'] != '' ? 1 : '')), $check['id'], '', 'text-align: center;');
			form_selectable_cell('' . html_escape(strlen(trim($issue_line)) ? $issue_line : '<none>') . '', $check['id']);
			form_checkbox_cell($check['id'], $check['id']);
			form_end_row();
		}
	}else{


	public function add($array)
	{
		$this->db = array_merge($array, $this->db);
	}


function html_split_string($string, $length = 70, $forgiveness = 10) {
	$new_string = '';
	$j    = 0;
	$done = false;

	while (!$done) {
		if (strlen($string) > $length) {
			for($i = 0; $i < $forgiveness; $i++) {
				if (substr($string, $length-$i, 1) == " ") {
					$new_string .= substr($string, 0, $length-$i) . "<br>";

					break;
				}
			}

			$string = substr($string, $length-$i);
		} else {
			$new_string .= $string;
			$done        = true;
		}

		$j++;
		if ($j > 4) break;
	}

	return $new_string;
}


$contents = ['form' => tep_draw_form('currencies', 'currencies.php', 'page=' . $_GET['page'] . (isset($cInfo) ? '&cID=' . $cInfo->currencies_id : '') . '&action=insert')];


                    $category_query = "select id from ".prefix_table("nested_tree")." where title LIKE '".$array_category[0]."' AND parent_id = 0";
                } else {
                    rest_error('NO_CATEGORY');
                }

                // Delete item
                $response = DB::delete(prefix_table("items"), "id_tree = (".$category_query.") and label LIKE '".$item."'");
                $json['type'] = 'item';
                $json['item'] = $item;
                $json['category'] = $GLOBALS['request'][2];
                if ($response) {
                    $json['status'] = 'OK';
                } else {
                    $json['status'] = 'KO';
                }
            }

            if ($json) {
                echo json_encode($json);
            } else {
                rest_error('EMPTY');
            }
        } else {
            rest_error('METHOD');
        }
    }


    public function createComment($id, $source = "leaves/leaves"){
      $this->auth->checkIfOperationIsAllowed('view_leaves');
      $data = getUserContext($this);
      $oldComment = $this->leaves_model->getCommentsLeave($id);
      $newComment = new stdClass;
      $newComment->type = "comment";
      $newComment->author = $this->session->userdata('id');
      $newComment->value = $this->input->post('comment');
      $newComment->date = date("Y-n-j");
      if ($oldComment != NULL){
        array_push($oldComment->comments, $newComment);
      }else {
        $oldComment = new stdClass;
        $oldComment->comments = array($newComment);
      }
      $json = json_encode($oldComment);
      $this->leaves_model->addComments($id, $json);
      if(isset($_GET['source'])){
        $source = $_GET['source'];
      }
      redirect("/$source/$id");
    }


    public function getInt($key, $default = 0, $deep = false)
    {
        return (int) $this->get($key, $default, $deep);
    }


            } elseif (!empty($this->params['src'])) {
                if ($this->params['src'] == $loc->src) {
                    $this->config = $config->config;
                    break;
                }
            }
        }


	public function actionGetItems(){
		$sql = 'SELECT id, name as value FROM x2_docs WHERE name LIKE :qterm ORDER BY name ASC';
		$command = Yii::app()->db->createCommand($sql);
		$qterm = '%'.$_GET['term'].'%';
		$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
		$result = $command->queryAll();
		echo CJSON::encode($result); exit;
	}


            $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());
            $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);
        }


    function edit_option_master() {
        expHistory::set('editable', $this->params);

        $params = isset($this->params['id']) ? $this->params['id'] : $this->params;
        $record = new option_master($params);
        assign_to_template(array(
            'record'=>$record
        ));
    }


    function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
        if (empty($endtimestamp)) {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
        } else {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
        }
        if ($multiday)
            $date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
        $date_sql .= ")";
        return $date_sql;
    }


function mso_segment_array()
{
	$CI = &get_instance();

	if (isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI']) {
		// http://localhost/page/privet?get=hello
		$url = getinfo('site_protocol');
		$url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$url = str_replace($CI->config->config['base_url'], '', $url); // page/privet?get=hello

		if (strpos($url, '?') !== FALSE) {
			// есть «?»
			$url = explode('?', $url); // разделим в массив
			$url = $url[0]; // сегменты - это только первая часть
			$url = explode('/', $url); // разделим в массив по /

			// нужно изменить нумерацию - начало с 1
			$out = [];
			$i = 1;

			foreach ($url as $val) {
				if ($val) {
					$out[$i] = $val;
					$i++;
				}
			}

			return $out;
		} else {
			return $CI->uri->segment_array();
		}
	} else {
		return $CI->uri->segment_array();
	}
}


	public function delete_version() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // get the version
	    $version = new help_version($this->params['id']);
	    if (empty($version->id)) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // if we have errors than lets get outta here!
	    if (!expQueue::isQueueEmpty('error')) expHistory::back();

	    // delete the version
	    $version->delete();

	    expSession::un_set('help-version');

	    flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));
	    expHistory::back();
	}


    public function confirm()
    {
        $project = $this->getProject();
        $category = $this->getCategory();

        $this->response->html($this->helper->layout->project('category/remove', array(
            'project'  => $project,
            'category' => $category,
        )));
    }


    public function create(Codendi_Request $request)
    {
        $content_id = false;
        $vId = new Valid_UInt($this->widget_id . '_job_id');
        $vId->setErrorMessage("Can't add empty job id");
        $vId->required();
        if ($request->valid($vId)) {
            $job_id = $request->get($this->widget_id . '_job_id');
            $sql = 'INSERT INTO plugin_hudson_widget (widget_name, owner_id, owner_type, job_id) VALUES ("' . $this->id . '", ' . $this->owner_id . ", '" . $this->owner_type . "', " . db_escape_int($job_id) . " )";
            $res = db_query($sql);
            $content_id = db_insertid($res);
        }
        return $content_id;
    }


    private function load($id)
    {
        global $zdb;
        try {
            $select = $zdb->select(self::TABLE);
            $select->limit(1)->where(self::PK . ' = ' . $id);

            $results = $zdb->execute($select);
            $res = $results->current();

            $this->id = $id;
            $this->short = $res->short_label;
            $this->long = $res->long_label;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred loading title #' . $id . "Message:\n" .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public function testCanGiveCustomProtocolVersion()
    {
        $r = new Response(200, [], null, '1000');
        $this->assertEquals('1000', $r->getProtocolVersion());
    }


	protected function _filePutContents($path, $content) {
		$res = false;

		if ($local = $this->getTempFile($path)) {
			if (@file_put_contents($local, $content, LOCK_EX) !== false
			&& ($fp = @fopen($local, 'rb'))) {
				clearstatcache();
				$res = $this->_save($fp, $path, '', array());
				@fclose($fp);
			}
			file_exists($local) && @unlink($local);
		}

		return $res;
	}


    public function save()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }


	public function update()
	{
		global $DB;

		$ok = $DB->execute('
 			UPDATE nv_menus
			   SET codename = :codename, icon = :icon, lid = :lid, notes = :notes,
			   	   functions = :functions, enabled = :enabled
            WHERE id = :id',
			array(
				'id' => $this->id,
				'codename' => value_or_default($this->codename, ""),
				'icon' => value_or_default($this->icon, ""),
				'lid' => value_or_default($this->lid, 0),
				'notes' => value_or_default($this->notes, ""),
				'functions' => json_encode($this->functions),
				'enabled' => value_or_default($this->enabled, 0)
			)
        );

		if(!$ok)
			throw new Exception($DB->get_last_error());

		return true;
	}


    public function confirm()
    {
        $project = $this->getProject();
        $swimlane = $this->getSwimlane();

        $this->response->html($this->helper->layout->project('swimlane/remove', array(
            'project' => $project,
            'swimlane' => $swimlane,
        )));
    }


    function delete_recurring() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item->is_recurring == 1) { // need to give user options
            expHistory::set('editable', $this->params);
            assign_to_template(array(
                'checked_date' => $this->params['date_id'],
                'event'        => $item,
            ));
        } else { // Process a regular delete
            $item->delete();
        }
    }


    public function searchNew() {
        global $db, $user;
        //$this->params['query'] = str_ireplace('-','\-',$this->params['query']);
        $sql = "select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, ";
        $sql .= "match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) as relevance, ";
        $sql .= "CASE when p.model like '" . $this->params['query'] . "%' then 1 else 0 END as modelmatch, ";
        $sql .= "CASE when p.title like '%" . $this->params['query'] . "%' then 1 else 0 END as titlematch ";
        $sql .= "from " . $db->prefix . "product as p INNER JOIN " .
            $db->prefix . "content_expFiles as cef ON p.id=cef.content_id AND cef.content_type IN ('product','eventregistration','donation','giftcard') AND cef.subtype='mainimage'  INNER JOIN " . $db->prefix .
            "expFiles as f ON cef.expFiles_id = f.id WHERE ";
        if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';
        $sql .= " match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) AND p.parent_id=0 ";
        $sql .= " HAVING relevance > 0 ";
        //$sql .= "GROUP BY p.id ";
        $sql .= "order by modelmatch,titlematch,relevance desc LIMIT 10";

        eDebug($sql);
        $res = $db->selectObjectsBySql($sql);
        eDebug($res, true);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


	protected function configure() {
		parent::configure();

		if (!empty($this->options['tmpPath'])) {
			if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) {
				$this->tmp = $this->options['tmpPath'];
			}
		}
		if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
			$this->tmp = $tmp;
		}

		if (!$this->tmp && $this->tmbPath) {
			$this->tmp = $this->tmbPath;
		}

		if (!$this->tmp) {
			$this->disabled[] = 'mkfile';
			$this->disabled[] = 'paste';
			$this->disabled[] = 'duplicate';
			$this->disabled[] = 'upload';
			$this->disabled[] = 'edit';
			$this->disabled[] = 'archive';
			$this->disabled[] = 'extract';
		}

		// echo $this->tmp;

	}


    public static function access ($grp='4') {
        if ( isset($_SESSION['gxsess']['val']['group']) ) {
            if($_SESSION['gxsess']['val']['group'] <= $grp) {
                return true;
            }else{
                return false;
            }
        }
    }


      $input    = ['name' => 'ldap', 'rootdn_passwd' => $password];
      $result   = $ldap->prepareInputForUpdate($input);

      //Expected value to be encrypted using GLPIKEY key
      $expected = \Toolbox::encrypt(stripslashes($password), GLPIKEY);
      $this->string($result['rootdn_passwd'])->isIdenticalTo($expected);

      $input['_blank_passwd'] = 1;
      $result   = $ldap->prepareInputForUpdate($input);
      //rootdn_passwd is set but empty
      $this->string($result['rootdn_passwd'])->isEmpty();

      //Field name finishing with _field : set the value in lower case
      $input['_login_field'] = 'TEST';
      $result         = $ldap->prepareInputForUpdate($input);
      $this->string($result['_login_field'])->isIdenticalTo('test');

      $input['sync_field'] = 'sync_field';
      $result = $ldap->prepareInputForUpdate($input);
      $this->string($result['sync_field'])->isIdenticalTo('sync_field');

      //test sync_field update
      $ldap->fields['sync_field'] = 'sync_field';
      $result = $ldap->prepareInputForUpdate($input);
      $this->array($result)->notHasKey('sync_field');

      $this->calling($ldap)->isSyncFieldUsed = false;
      $result = $ldap->prepareInputForUpdate($input);
      $this->array($result)->hasKey('sync_field');
      $this->calling($ldap)->isSyncFieldUsed = true;

      $input['sync_field'] = 'another_field';
      $result = $ldap->prepareInputForUpdate($input);
      $this->boolean($result)->isFalse();
   }


    public function limit($value)
    {
        if ($value >= 0) {
            $this->limit = $value;
        }

        return $this;
    }


                    foreach ($events as $event) {
                        $extevents[$date][] = $event;
                    }


                foreach ($grpusers as $u) {
                    $emails[$u->email] = trim(user::getUserAttribution($u->id));
                }


    public static function getItems($term) {
        $model = X2Model::model(Yii::app()->controller->modelClass);
        if (isset($model)) {
            $tableName = $model->tableName();
            $sql = 'SELECT id, name as value
                 FROM ' . $tableName . ' WHERE name LIKE :qterm ORDER BY name ASC';
            $command = Yii::app()->db->createCommand($sql);
            $qterm = $term . '%';
            $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
            $result = $command->queryAll();
            echo CJSON::encode($result);
        }
        Yii::app()->end();
    }


}elseif($vars['paging'] < $limit  || $vars['paging'] = $limit ){
                    $prev = ($vars['paging'])-1;
                    if($smart == true){
                    $url = $vars['url']."/paging/".$prev;
                    }else{
                        $url = $vars['url']."&paging=".$prev;
                    }
                    $r .= "
Previous
";
                }


	private function validateCodeInjection()
	{
		$shortMimeType = $this->getShortMimeType(0);
		if ($this->validateAllCodeInjection || \in_array($shortMimeType, static::$phpInjection)) {
			$contents = $this->getContents();
			if ((1 === preg_match('/(<\?php?(.*?))/si', $contents)
			|| false !== stripos($contents, '<?=')
			|| false !== stripos($contents, '<? ')) && $this->searchCodeInjection()
			) {
				throw new \App\Exceptions\DangerousFile('ERR_FILE_PHP_CODE_INJECTION');
			}
		}
	}


    function set_menu_tabs()
    {
        $this->menu_tabs = array(
        'tab1' => __('Ban Users', 'all-in-one-wp-security-and-firewall'),
        );
    }


function checkRights(&$db,&$user)
{
	return $user->hasRight($db,'testplan_metrics');
}


					$this->archiveSize += filesize($p);
				}
			}
		} else {


foreach($functions as $function)
		{
			if($function->id == $f)
			{
				if($function->enabled=='1')
					$sortable_assigned[] = '
id.'" category="'.$function->category.'">icon.'" align="absmiddle" /> '.t($function->lid, $function->lid).'
';
				else
					$sortable_assigned[] = '
id.'" category="'.$function->category.'">icon.'" align="absmiddle" /> '.t($function->lid, $function->lid).'
';
			}
		}


    public function sdm_save_thumbnail_meta_data($post_id) {  // Save Thumbnail Upload metabox
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
	    return;
	if (!isset($_POST['sdm_thumbnail_box_nonce_check']) || !wp_verify_nonce($_POST['sdm_thumbnail_box_nonce_check'], 'sdm_thumbnail_box_nonce'))
	    return;

	if (isset($_POST['sdm_upload_thumbnail'])) {
	    update_post_meta($post_id, 'sdm_upload_thumbnail', $_POST['sdm_upload_thumbnail']);
	}
    }


	public function updateAmazonOrderTracking($order_id, $courier_id, $courier_from_list, $tracking_no) {
		$this->db->query("
			UPDATE `" . DB_PREFIX . "amazon_order`
			SET `courier_id` = '" . $courier_id . "',
				`courier_other` = " . (int)!$courier_from_list . ",
				`tracking_no` = '" . $tracking_no . "'
			WHERE `order_id` = " . (int)$order_id . "");


    public function saveLdapConfig(){
        $login_user = $this->checkLogin();
        $this->checkAdmin();
        $ldap_open = intval(I("ldap_open")) ;
        $ldap_form = I("ldap_form") ;

        if ($ldap_open) {
            if (!$ldap_form['user_field']) {
                $ldap_form['user_field'] = 'cn';
            }
            if( !extension_loaded( 'ldap' ) ) {
               $this->sendError(10011,"你尚未安装php-ldap扩展。如果是普通PHP环境，请手动安装之。如果是使用之前官方docker镜像，则需要重新安装镜像。方法是：备份 /showdoc_data 整个目录，然后全新安装showdoc，接着用备份覆盖/showdoc_data 。然后递归赋予777可写权限。");
               return ;
            }

            $ldap_conn = ldap_connect($ldap_form['host'], $ldap_form['port']);//建立与 LDAP 服务器的连接
            if (!$ldap_conn) {
               $this->sendError(10011,"Can't connect to LDAP server");
               return ;
            }
            ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $ldap_form['version']);
            $rs=ldap_bind($ldap_conn, $ldap_form['bind_dn'], $ldap_form['bind_password']);//与服务器绑定 用户登录验证 成功返回1
            if (!$rs) {
               $this->sendError(10011,"Can't bind to LDAP server");
               return ;
            }

            $result = ldap_search($ldap_conn,$ldap_form['base_dn'],"(cn=*)");
            $data = ldap_get_entries($ldap_conn, $result);

            for ($i=0; $i<$data["count"]; $i++) {
                $ldap_user = $data[$i][$ldap_form['user_field']][0] ;
                if (!$ldap_user) {
                    continue ;
                }
                //如果该用户不在数据库里，则帮助其注册
                if(!D("User")->isExist($ldap_user)){
                    D("User")->register($ldap_user,$ldap_user.time());
                }
            }
            D("Options")->set("ldap_form" , json_encode( $ldap_form)) ;
        }
        D("Options")->set("ldap_open" ,$ldap_open) ;
        $this->sendResult(array());

    }


        foreach ($nodes as $node) {
            if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
                if ($node->active == 1) {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
                } else {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
                }
                $ar[$node->id] = $text;
                foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
                    $ar[$id] = $text;
                }
            }
        }


	public static function account_verification($email, $hash)
	{
		global $DB;

		$status = false;

        if(strpos($hash, "-") > 0)
        {
            list($foo, $expiry) = explode("-", $hash);
            if(time() > $expiry)
            {
                // expired unconfirmed account!
                return $status;
            }
        }

		$DB->query('
			SELECT id, activation_key
			  FROM nv_webusers
			 WHERE email = '.protect($email).'
			   AND activation_key = '.protect($hash).'
		');
		$rs = $DB->first();

		if(!empty($rs->id))
		{
			$wu = new webuser();
			$wu->load($rs->id);

			// access is only enabled for blocked users (access==1) which already HAVE a password assigned
			if($wu->access==1 && !empty($wu->password))
			{
				// account is confirmed!
                if(empty($wu->email_verification_date)) // maybe the email was already verified by a previous newsletter subscription ;)
				    $wu->email_verification_date = time();
				$wu->access = 0;
				$wu->activation_key = "";
				$status = $wu->save();
			}
		}

		if(!$status)
		    return $status;
		else
		    return $wu->id;
	}


    public function getDisplayName ($plural=true) {
        return Yii::t('users', '{user}', array(
            '{user}' => Modules::displayName($plural, 'Users'),
        ));
    }


                    $expanded = implode($joiner, $kvp);
                    if ($isAssoc) {
                        // Don't prepend the value name when using the explode
                        // modifier with an associative array.
                        $actuallyUseQuery = false;
                    }
                } else {
                    if ($isAssoc) {
                        // When an associative array is encountered and the
                        // explode modifier is not set, then the result must be
                        // a comma separated list of keys followed by their
                        // respective values.
                        foreach ($kvp as $k => &$v) {
                            $v = $k . ',' . $v;
                        }
                    }
                    $expanded = implode(',', $kvp);
                }

            } else {
                if ($value['modifier'] == ':') {
                    $variable = substr($variable, 0, $value['position']);
                }
                $expanded = rawurlencode($variable);
                if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
                    $expanded = $this->decodeReserved($expanded);
                }
            }

            if ($actuallyUseQuery) {
                if (!$expanded && $joiner != '&') {
                    $expanded = $value['value'];
                } else {
                    $expanded = $value['value'] . '=' . $expanded;
                }
            }

            $replacements[] = $expanded;
        }

        $ret = implode($joiner, $replacements);
        if ($ret && $prefix) {
            return $prefix . $ret;
        }

        return $ret;
    }


    public function delete() {
        global $db, $history;

        /* The global constants can be overriden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        if (empty($this->params['id'])) {
            flash('error', gt('Missing id for the comment you would like to delete'));
            $lastUrl = expHistory::getLast('editable');
        }

        // delete the note
        $simplenote = new expSimpleNote($this->params['id']);
        $rows = $simplenote->delete();

        // delete the assocication too
        $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);

        // send the user back where they came from.
        $lastUrl = expHistory::getLast('editable');
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    public function getQueryGroupby()
    {
        //Last update date is stored in the changeset (the date of the changeset)
        return 'c.submitted_on';
    }


	public function uploadImage()
	{
		$filesCheck = array_filter($_FILES);
		if (!empty($filesCheck) && $this->approvedFileExtension($_FILES['file']['name'], 'image') && strpos($_FILES['file']['type'], 'image/') !== false) {
			ini_set('upload_max_filesize', '10M');
			ini_set('post_max_size', '10M');
			$tempFile = $_FILES['file']['tmp_name'];
			$targetPath = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
			$this->makeDir($targetPath);
			$targetFile = $targetPath . $_FILES['file']['name'];
			$this->setAPIResponse(null, pathinfo($_FILES['file']['name'], PATHINFO_BASENAME) . ' has been uploaded', null);
			return move_uploaded_file($tempFile, $targetFile);
		}
	}


    public function manage()
    {
        expHistory::set('manageable',$this->params);
        $gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all',null,'rank asc,name asc');

        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions
        ));
    }


	public function quicksearch($text)
	{
		global $DB;
		global $website;

		$like = ' LIKE '.protect('%'.$text.'%');

		// we search for the IDs at the dictionary NOW (to avoid inefficient requests)

		$DB->query('SELECT DISTINCT (nvw.node_id)
					 FROM nv_webdictionary nvw
					 WHERE nvw.node_type = "feed"
					   AND nvw.website = '.$website->id.'
					   AND nvw.text '.$like, 'array');

		$dict_ids = $DB->result("node_id");

		// all columns to look for
		$cols[] = 'i.id' . $like;

		if(!empty($dict_ids))
			$cols[] = 'i.id IN ('.implode(',', $dict_ids).')';

		$where = ' AND ( ';
		$where.= implode( ' OR ', $cols);
		$where .= ')';

		return $where;
	}


	protected function info($args) {
		$files = array();
		$sleep = 0;
		$compare = null;
		// long polling mode
		if ($args['compare'] && count($args['targets']) === 1) {
			$compare = intval($args['compare']);
			$hash = $args['targets'][0];
			if ($volume = $this->volume($hash)) {
				$standby = (int)$volume->getOption('plStandby');
				$_compare = false;
				if (($syncCheckFunc = $volume->getOption('syncCheckFunc')) && is_callable($syncCheckFunc)) {
					$_compare = call_user_func_array($syncCheckFunc, array($volume->realpath($hash), $standby, $compare, $volume, $this));
				}
				if ($_compare !== false) {
					$compare = $_compare;
				} else {
					$sleep = max(1, (int)$volume->getOption('tsPlSleep'));
					$limit = max(1, $standby / $sleep) + 1;
					$timelimit = ini_get('max_execution_time');
					do {
						$timelimit && @ set_time_limit($timelimit + $sleep);
						$volume->clearstatcache();
						if (($info = $volume->file($hash)) != false) {
							if ($info['ts'] != $compare) {
								$compare = $info['ts'];
								break;
							}
						} else {
							$compare = 0;
							break;
						}
						if (--$limit) {
							sleep($sleep);
						}
					} while($limit);
				}
			}
		} else {
			foreach ($args['targets'] as $hash) {
				if (($volume = $this->volume($hash)) != false
				&& ($info = $volume->file($hash)) != false) {
					$info['path'] = $volume->path($hash);
					$files[] = $info;
				}
			}
		}

		$result = array('files' => $files);
		if (!is_null($compare)) {
			$result['compare'] = strval($compare);
		}
		return $result;
	}


                foreach ($grpusers as $u) {
                    $emails[$u->email] = trim(user::getUserAttribution($u->id));
                }


static function displayname() { return gt("Navigation"); }


    public static function recent($vars, $type = 'post') {
        $sql = "SELECT * FROM `posts` WHERE `type` = '{$type}' ORDER BY `date` DESC LIMIT {$vars}";
        $posts = Db::result($sql);
        if(isset($posts['error'])){
            $posts['error'] = "No Posts found.";
        }else{
            $posts = $posts;
        }
        return $posts;
    }


    private function getSwimlane()
    {
        $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));

        if (empty($swimlane)) {
            throw new PageNotFoundException();
        }

        return $swimlane;
    }


    public static function DragnDropReRank2() {
        global $router, $db;

        $id = $router->params['id'];
        $page = new section($id);
        $old_rank = $page->rank;
        $old_parent = $page->parent;
        $new_rank = $router->params['position'] + 1;  // rank
        $new_parent = intval($router->params['parent']);

        $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent);  // close in hole
        $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent);  // make room

        $params = array();
        $params['parent'] = $new_parent;
        $params['rank'] = $new_rank;
        $page->update($params);

        self::checkForSectionalAdmins($id);
        expSession::clearAllUsersSessionCache('navigation');
    }


    public function params()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

        if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {
            $this->create();
            return;
        }

        $action = $this->actionManager->getAction($values['action_name']);
        $action_params = $action->getActionRequiredParameters();

        if (empty($action_params)) {
            $this->doCreation($project, $values + array('params' => array()));
        }

        $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
        unset($projects_list[$project['id']]);

        $this->response->html($this->template->render('action_creation/params', array(
            'values' => $values,
            'action_params' => $action_params,
            'columns_list' => $this->columnModel->getList($project['id']),
            'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
            'projects_list' => $projects_list,
            'colors_list' => $this->colorModel->getList(),
            'categories_list' => $this->categoryModel->getList($project['id']),
            'links_list' => $this->linkModel->getList(0, false),
            'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'swimlane_list' => $this->swimlaneModel->getList($project['id']),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


    public function testNoAuthority($input)
    {
        $uri = new Uri($input);

        $this->assertEquals($input, (string) $uri);
    }


    public function confirm()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);

        $this->response->html($this->template->render('project_tag/remove', array(
            'tag'     => $tag,
            'project' => $project,
        )));
    }


                    $layout[$loc] = array_merge($layout[$loc],$data);
                }
            }
        }
        return $layout;
    }


    public function checkLdapLogin($username ,$password ){
            $ldap_open = D("Options")->get("ldap_open" ) ;
            $ldap_form = D("Options")->get("ldap_form" ) ;
            $ldap_form = json_decode($ldap_form,1);
            if (!$ldap_open) {
                return false;
            }
            if (!$ldap_form['user_field']) {
                $ldap_form['user_field'] = 'cn';
            }
            $ldap_conn = ldap_connect($ldap_form['host'], $ldap_form['port']);//建立与 LDAP 服务器的连接
            if (!$ldap_conn) {
               return false;
            }
            ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $ldap_form['version']);
            $rs=ldap_bind($ldap_conn, $ldap_form['bind_dn'], $ldap_form['bind_password']);//与服务器绑定 用户登录验证 成功返回1
            if (!$rs) {
               return false ;
            }

            $result = ldap_search($ldap_conn,$ldap_form['base_dn'],"(cn=*)");
            $data = ldap_get_entries($ldap_conn, $result);
            for ($i=0; $i<$data["count"]; $i++) {
                $ldap_user = $data[$i][$ldap_form['user_field']][0] ;
                $dn = $data[$i]["dn"] ;
                if ($ldap_user == $username) {
                    //如果该用户不在数据库里，则帮助其注册
                    $userInfo = D("User")->isExist($username) ;
                    if(!$userInfo){
                        D("User")->register($ldap_user,$ldap_user.time());
                    }
                    $rs2=ldap_bind($ldap_conn, $dn , $password);
                    if ($rs2) {
                       D("User")->updatePwd($userInfo['uid'], $password);
                       return $this->checkLogin($username,$password);
                    }
                }
            }

            return false ;

    }


    function delete_recurring() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item->is_recurring == 1) { // need to give user options
            expHistory::set('editable', $this->params);
            assign_to_template(array(
                'checked_date' => $this->params['date_id'],
                'event'        => $item,
            ));
        } else { // Process a regular delete
            $item->delete();
        }
    }


    public function enable()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $swimlane_id = $this->request->getIntegerParam('swimlane_id');

        if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane updated successfully.'));
        } else {
            $this->flash->failure(t('Unable to update this swimlane.'));
        }

        $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
    }


	public function delete() {
	    global $db;

        /* The global constants can be overriden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    if (empty($this->params['id'])) {
	        flash('error', gt('Missing id for the comment you would like to delete'));
	        expHistory::back();
	    }

	    // delete the comment
        $comment = new expComment($this->params['id']);
        $comment->delete();

        // delete the association too
        $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']);

        // send the user back where they came from.
        expHistory::back();
	}


    function searchCategory() {
        return gt('Event');
    }


    public static function pending_count()
    {
        global $DB;
        global $website;

        $pending_comments = $DB->query_single(
            'COUNT(*)',
            'nv_comments',
            ' website = '.protect($website->id).' AND
              status = -1'
        );

        return $pending_comments;
    }


	protected function _fclose($fp, $path='') {
		@fclose($fp);
		if ($path) {
			@unlink($this->getTempFile($path));
		}
	}


	function manage() {
	    global $db;

	    expHistory::set('manageable', $this->params);
//	    $classes = array();
        $dir = BASE."framework/modules/ecommerce/billingcalculators";
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
                    include_once("$dir/$file");
                    $classname = substr($file, 0, -4);
                    $id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
                    if (empty($id)) {
//                        $calobj = null;
                        $calcobj = new $classname();
                        if ($calcobj->isSelectable() == true) {
                            $obj = new billingcalculator(array(
                                'title'=>$calcobj->name(),
//                                'user_title'=>$calcobj->title,
                                'body'=>$calcobj->description(),
                                'calculator_name'=>$classname,
                                'enabled'=>false));
                            $obj->save();
                        }
                    }
                }
            }
        }

        $bcalc = new billingcalculator();
        $calculators = $bcalc->find('all');
        assign_to_template(array(
            'calculators'=>$calculators
        ));
	}


function load_gallery($auc_id)
{
    $UPLOADED_PICTURES = array();
    if (is_dir(UPLOAD_PATH . $auc_id)) {
        if ($dir = opendir(UPLOAD_PATH . $auc_id)) {
            while ($file = @readdir($dir)) {
                if ($file != '.' && $file != '..' && strpos($file, 'thumb-') === false) {
                    $UPLOADED_PICTURES[] = UPLOAD_FOLDER . $auc_id . '/' . $file;
                }
            }
            closedir($dir);
        }
    }
    return $UPLOADED_PICTURES;
}


    public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $category = $this->getCategory();

        if ($this->categoryModel->remove($category['id'])) {
            $this->flash->success(t('Category removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this category.'));
        }

        $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));
    }


    public static function dropdown($vars){
        if(is_array($vars)){
            //print_r($vars);
            $name = $vars['name'];
            $where = "WHERE `status` = '1' AND ";
            if(isset($vars['type'])) {
                $where .= " `type` = '{$vars['type']}' AND ";
            }else{
                $where .= " ";
            }
            $where .= " `status` = '1' ";
            $order_by = "ORDER BY ";
            if(isset($vars['order_by'])) {
                $order_by .= " {$vars['order_by']} ";
            }else{
                $order_by .= " `name` ";
            }
            if (isset($vars['sort'])) {
                $sort = " {$vars['sort']}";
            }else{
                $sort = 'ASC';
            }
        }
        $cat = Db::result("SELECT * FROM `posts` {$where} {$order_by} {$sort}");
        $num = Db::$num_rows;
        $drop = "<select name=\"{$name}\" class=\"form-control\"><option></option>";
        if($num > 0){
            foreach ($cat as $c) {
                # code...
                // if($c->parent == ''){
                    if(isset($vars['selected']) && $c->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                    $drop .= "<option value=\"{$c->id}\" $sel style=\"padding-left: 10px;\">{$c->title}</option>";
                    // foreach ($cat as $c2) {
                    //     # code...
                    //     if($c2->parent == $c->id){
                    //         if(isset($vars['selected']) && $c2->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                    //         $drop .= "<option value=\"{$c2->id}\" $sel style=\"padding-left: 10px;\">   {$c2->name}</option>";
                    //     }
                    // }
                // }

            }
        }
        $drop .= "</select>";

        return $drop;
    }


    public function remove()
    {
        $project = $this->getProject();
        $this->checkCSRFParam();
        $column_id = $this->request->getIntegerParam('column_id');

        if ($this->columnModel->remove($column_id)) {
            $this->flash->success(t('Column removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this column.'));
        }

        $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));
    }


	public function update()
	{
		global $DB;
		global $events;

		if(!is_array($this->categories))
			$this->categories = array();

		$ok = $DB->execute('
 			UPDATE nv_feeds
			  SET categories = :categories, format = :format, image = :image, entries = :entries,
			  	  content = :content, views = :views, permission = :permission, enabled = :enabled
			WHERE id = :id	AND	website = :website',
			array(
				'id' => $this->id,
				'website' => $this->website,
				'categories' => implode(',', $this->categories),
				'format' => $this->format,
				'image' => value_or_default($this->image, 0),
				'entries' => value_or_default($this->entries, 10),
				'content' => $this->content,
				'views' => value_or_default($this->views, 0),
				'permission' => value_or_default($this->permission, 0),
				'enabled' => value_or_default($this->enabled, 0)
			)
		);

		if(!$ok)
		    throw new Exception($DB->get_last_error());

		webdictionary::save_element_strings('feed', $this->id, $this->dictionary);
		path::saveElementPaths('feed', $this->id, $this->paths);

        if(method_exists($events, 'trigger'))
        {
            $events->trigger(
                'feed',
                'save',
                array(
                    'feed' => $this
                )
            );
        }

		return true;
	}


    private function runCallback() {
        foreach ($this->records as &$record) {
            if (isset($record->ref_type)) {
                $refType = $record->ref_type;
                if (class_exists($record->ref_type)) {
                    $type = new $refType();
                    $classinfo = new ReflectionClass($type);
                    if ($classinfo->hasMethod('paginationCallback')) {
                        $item = new $type($record->original_id);
                        $item->paginationCallback($record);
                    }
                }
            }
        }
    }


    public function sdm_save_upload_meta_data($post_id) {  // Save File Upload metabox
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
	    return;
	if (!isset($_POST['sdm_upload_box_nonce_check']) || !wp_verify_nonce($_POST['sdm_upload_box_nonce_check'], 'sdm_upload_box_nonce'))
	    return;

	if (isset($_POST['sdm_upload'])) {
	    update_post_meta($post_id, 'sdm_upload', $_POST['sdm_upload']);
	}
    }


    protected function fsock_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp)
    {
        $connect_timeout = 3;
        $connect_try = 3;
        $method = 'GET';
        $readsize = 4096;
        $ssl = '';

        $getSize = null;
        $headers = '';

        $arr = parse_url($url);
        if (!$arr) {
            // Bad request
            return false;
        }
        if ($arr['scheme'] === 'https') {
            $ssl = 'ssl://';
        }

        // query
        $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : '';
        // port
        $port = isset($arr['port']) ? $arr['port'] : '';
        $arr['port'] = $port ? $port : ($ssl ? 443 : 80);

        $url_base = $arr['scheme'] . '://' . $arr['host'] . ($port ? (':' . $port) : '');


	public function fixsessions() {
	    global $db;

//		$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');
		$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');
		flash('message', gt('Sessions Table was Repaired'));
		expHistory::back();
	}


            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }


                    foreach ($week as $dayNum => $day) {
                        if ($dayNum == $now['mday']) {
                            $currentweek = $weekNum;
                        }
                        if ($dayNum <= $endofmonth) {
//                            $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects("eventdate", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
                            $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find("count", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
                        }
                    }


            self::removeLevel($kid->id);
        }
    }


	protected function _archive($dir, $files, $name, $arc)
	{
		// get current directory
		$cwd = getcwd();

		$tmpDir = $this->tempDir();
		if (!$tmpDir) {
			return false;
		}

		//download data
		if (!$this->ftp_download_files($dir, $files, $tmpDir)) {
			//cleanup
			$this->rmdirRecursive($tmpDir);
			return false;
		}

		$remoteArchiveFile = false;
		if ($path = $this->makeArchive($tmpDir, $files, $name, $arc)) {
			$remoteArchiveFile = $this->_joinPath($dir, $name);
			if (!ftp_put($this->connect, $remoteArchiveFile, $path, FTP_BINARY)) {
				$remoteArchiveFile = false;
			}
		}

		//cleanup
		if(!$this->rmdirRecursive($tmpDir)) {
			return false;
		}

		return $remoteArchiveFile;
	}


    function move_standalone() {
        expSession::clearAllUsersSessionCache('navigation');
        assign_to_template(array(
            'parent' => $this->params['parent'],
        ));
    }


    function categoryBreadcrumb() {
//        global $db, $router;

        //eDebug($this->category);

        /*if(isset($router->params['action']))
        {
            $ancestors = $this->category->pathToNode();
        }else if(isset($router->params['section']))
        {
            $current = $db->selectObject('section',' id= '.$router->params['section']);
            $ancestors[] = $current;
            if( $current->parent != -1 || $current->parent != 0 )
            {
                while ($db->selectObject('section',' id= '.$router->params['section']);)
                    if ($section->id == $id) {
                        $current = $section;
                        break;
                    }
                }
            }
            eDebug($sections);
            $ancestors = $this->category->pathToNode();
        }*/

        $ancestors = $this->category->pathToNode();
        // eDebug($ancestors);
        assign_to_template(array(
            'ancestors' => $ancestors
        ));
    }


	protected function removeNetVolume($key) {
		$netVolumes = $this->getNetVolumes();
		if (is_string($key) && isset($netVolumes[$key])) {
			unset($netVolumes[$key]);
			$this->saveNetVolumes($netVolumes);
		}
	}


    public static function get_session($vars) {

    }


    public static function header($vars=""){
        header("Cache-Control: must-revalidate,max-age=300,s-maxage=900");
        $offset = 60 * 60 * 24 * 3;
        $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        header($ExpStr);
        header("Content-Type: text/html; charset=utf-8");

        if (isset($vars)) {
            # code...
            $GLOBALS['data'] = $vars;
            self::theme('header', $vars);
        }else{
            self::theme('header');
        }

    }


    public function enable()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $swimlane_id = $this->request->getIntegerParam('swimlane_id');

        if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane updated successfully.'));
        } else {
            $this->flash->failure(t('Unable to update this swimlane.'));
        }

        $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
    }


    public static function initializeNavigation() {
        $sections = section::levelTemplate(0, 0);
        return $sections;
    }


function _makeChooseCheckbox($value, $title) {
    //    return '<INPUT type=checkbox name=st_arr[] value=' . $value . ' checked>';
    global $THIS_RET;
    return "<input name=unused[$THIS_RET[STUDENT_ID]] value=" . $THIS_RET[STUDENT_ID] . "  type='checkbox' id=$THIS_RET[STUDENT_ID] onClick='setHiddenCheckboxStudents(\"st_arr[]\",this,$THIS_RET[STUDENT_ID]);' />";
}


	protected function connect() {
		if ($this->connection and $this->connection->isValid()) {
			return;
		}
		$command = sprintf('%s --authentication-file=/proc/self/fd/3 //%s/%s',
			Server::CLIENT,
			$this->server->getHost(),
			$this->name
		);
		$this->connection = new Connection($command);
		$this->connection->writeAuthentication($this->server->getUser(), $this->server->getPassword());
		if (!$this->connection->isValid()) {
			throw new ConnectionException();
		}
	}


				unset($map[$n], $n, $d);
			}
			unset($map);
			if(!self::$client) {
				self::$client = false;
			}
		}
	}


public function display_sdm_stats_meta_box($post) {  //Stats metabox
	$old_count = get_post_meta($post->ID, 'sdm_count_offset', true);
	$value = isset($old_count) && $old_count != '' ? $old_count : '0';

	// Get checkbox for "disable download logging"
	$no_logs = get_post_meta($post->ID, 'sdm_item_no_log', true);
	$checked = isset($no_logs) && $no_logs === 'on' ? 'checked="checked"' : '';

	_e('These are the statistics for this download item.', 'simple-download-monitor');
	echo '

';

	global $wpdb;
	$wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'sdm_downloads WHERE post_id=%s', $post->ID));

	echo '
';
	_e('Number of Downloads:', 'simple-download-monitor');
	echo ' ' . $wpdb->num_rows . '';
	echo '
';

	echo '
';
	_e('Offset Count: ', 'simple-download-monitor');
	echo '
';
	echo ' <input type="text" size="10" name="sdm_count_offset" value="' . $value . '" />';
	echo '
' . __('Enter any positive or negative numerical value; to offset the download count shown to the visitors (when using the download counter shortcode).', 'simple-download-monitor') . '
';
	echo '
';

	echo '
';
	echo '
';
	echo '<input type="checkbox" name="sdm_item_no_log" ' . $checked . ' />';
	echo '';
	_e('Disable download logging for this item.', 'simple-download-monitor');
	echo '
';

	wp_nonce_field('sdm_count_offset_nonce', 'sdm_count_offset_nonce_check');
    }


printf('
%s
%s %s
',$row->post_title,$row->meta_key,$row->meta_value);
	}
}


    public function confirm()
    {
        $project = $this->getProject();
        $swimlane = $this->getSwimlane();

        $this->response->html($this->helper->layout->project('swimlane/remove', array(
            'project' => $project,
            'swimlane' => $swimlane,
        )));
    }


    function update_optiongroup_master() {
        global $db;

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $og = new optiongroup_master($id);
        $oldtitle = $og->title;
        $og->update($this->params);

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $og->title) {
            $db->sql('UPDATE '.$db->prefix.'optiongroup SET title="'.$og->title.'" WHERE title="'.$oldtitle.'"');
        }

        expHistory::back();
    }


	function manage() {
	    global $db;

	    expHistory::set('manageable', $this->params);
//	    $classes = array();
        $dir = BASE."framework/modules/ecommerce/billingcalculators";
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
                    include_once("$dir/$file");
                    $classname = substr($file, 0, -4);
                    $id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
                    if (empty($id)) {
//                        $calobj = null;
                        $calcobj = new $classname();
                        if ($calcobj->isSelectable() == true) {
                            $obj = new billingcalculator(array(
                                'title'=>$calcobj->name(),
//                                'user_title'=>$calcobj->title,
                                'body'=>$calcobj->description(),
                                'calculator_name'=>$classname,
                                'enabled'=>false));
                            $obj->save();
                        }
                    }
                }
            }
        }

        $bcalc = new billingcalculator();
        $calculators = $bcalc->find('all');
        assign_to_template(array(
            'calculators'=>$calculators
        ));
	}


    public function getQueryOrderby()
    {
        return $this->getBind()->getQueryOrderby();
    }


function _makeExtra($value, $title = '') {
    global $THIS_RET;

    if ($THIS_RET['WITH_TEACHER_ID'])
        $return .= ''._with.': ' . GetTeacher($THIS_RET['WITH_TEACHER_ID']) . '
';
    if ($THIS_RET['NOT_TEACHER_ID'])
        $return .= ''._notWith.': ' . GetTeacher($THIS_RET['NOT_TEACHER_ID']) . '
';
    if ($THIS_RET['WITH_PERIOD_ID'])
        $return .= ''._on.': ' . GetPeriod($THIS_RET['WITH_PERIOD_ID']) . '
';
    if ($THIS_RET['NOT_PERIOD_ID'])
        $return .= ''._notOn.': ' . GetPeriod($THIS_RET['NOT_PERIOD_ID']) . '
';
    if ($THIS_RET['PRIORITY'])
        $return .= ''._priority.': ' . $THIS_RET['PRIORITY'] . '
';
    if ($THIS_RET['MARKING_PERIOD_ID'])
        $return .= ''._markingPeriod.': ' . GetMP($THIS_RET['MARKING_PERIOD_ID']) . '
';

    return $return;
}


function db_start()
{
	global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;

	switch ($DatabaseType) {
		case 'mysqli':
			$connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);
			break;
	}
	// Error code for both.
	if ($connection === false) {
		switch ($DatabaseType) {
			case 'mysqil':
				$errormessage = mysqli_error($connection);
				break;
		}
		db_show_error("", "" . _couldNotConnectToDatabase . ": $DatabaseServer", $errormessage);
	}
	return $connection;
}


    public function getQuerySelect()
    {
        return $this->getBind()->getQuerySelect();
    }


    protected function unserialize(string $data)
    {
        if (is_numeric($data)) {
            return $data;
        }

        $unserialize = $this->options['serialize'][1] ?? "unserialize";

        return $unserialize($data);
    }


        $percent = round($percent, 0);
    } else {
        $percent = round($percent, 2); // school default
    }
    if ($ret == '%')
        return $percent;

    if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])
        $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\'' . $cp[1]['SYEAR'] . '\' AND SCHOOL_ID=\'' . $cp[1]['SCHOOL_ID'] . '\' AND GRADE_SCALE_ID=\'' . $grade_scale_id . '\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));

    foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {
        if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])
            return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];
    }
}


	public function isAllowedFilename($filename){
		$allow_array = array(
			'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',
			'.mp3','.wav','.m4a','.ogg','.webma','.mp4','.flv',
			'.mov','.webmv','.flac','.mkv',
			'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso','.bz2','.epub',
			'.pdf','.ofd','.swf','.epub','.xps',
			'.doc','.docx','.odt','.rtf','.docm','.dotm','.dot','.dotx','.wps',
			'.ppt','.pptx','.xls','.xlsx','.txt','.psd','.csv',
			'.cer','.ppt','.pub','.properties','.json','.css',
			) ;

		$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名（转为小写后）
		if(in_array( $ext , $allow_array ) ){
			return true ;
		}
		return false;
	}


    public static function delete($id){

        return Categories::delete($id);

    }


    public function sendAsync(RequestInterface $request, array $options = [])
    {
        // Merge the base URI into the request URI if needed.
        $options = $this->prepareDefaults($options);

        return $this->transfer(
            $request->withUri($this->buildUri($request->getUri(), $options)),
            $options
        );
    }


    public function update() {

        //populate the alt tag field if the user didn't
        if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];

        // call expController update to save the image
        parent::update();
    }


    public function show()
    {
        $task = $this->getTask();
        $subtask = $this->getSubtask();

        $this->response->html($this->template->render('subtask_restriction/show', array(
            'status_list' => array(
                SubtaskModel::STATUS_TODO => t('Todo'),
                SubtaskModel::STATUS_DONE => t('Done'),
            ),
            'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    public function videoThumbnailTreeAction()
    {
        $this->checkPermission('thumbnails');

        $thumbnails = [];

        $list = new Asset\Video\Thumbnail\Config\Listing();

        $groups = [];
        foreach ($list->getThumbnails() as $item) {
            if ($item->getGroup()) {
                if (!$groups[$item->getGroup()]) {
                    $groups[$item->getGroup()] = [
                        'id' => 'group_' . $item->getName(),
                        'text' => $item->getGroup(),
                        'expandable' => true,
                        'leaf' => false,
                        'allowChildren' => true,
                        'iconCls' => 'pimcore_icon_folder',
                        'group' => $item->getGroup(),
                        'children' => [],
                    ];
                }
                $groups[$item->getGroup()]['children'][] =
                    [
                        'id' => $item->getName(),
                        'text' => $item->getName(),
                        'leaf' => true,
                        'iconCls' => 'pimcore_icon_videothumbnails',
                        'cls' => 'pimcore_treenode_disabled',
                        'writeable' => $item->isWriteable(),
                    ];
            } else {
                $thumbnails[] = [
                    'id' => $item->getName(),
                    'text' => $item->getName(),
                    'leaf' => true,
                    'iconCls' => 'pimcore_icon_videothumbnails',
                    'cls' => 'pimcore_treenode_disabled',
                    'writeable' => $item->isWriteable(),
                ];
            }
        }

        foreach ($groups as $group) {
            $thumbnails[] = $group;
        }

        return $this->adminJson($thumbnails);
    }


function db_seq_nextval($seqname)
{
    global $DatabaseType;

    if ($DatabaseType == 'mysqli')
        $seq = "fn_" . strtolower($seqname) . "()";

    return $seq;
}


    protected function getComment()
    {
        $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));

        if (empty($comment)) {
            throw new PageNotFoundException();
        }

        if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {
            throw new AccessForbiddenException();
        }

        return $comment;
    }


$contents = ['form' => tep_draw_form('customer_data_groups', 'customer_data_groups.php', 'page=' . $_GET['page'] . '&action=insert')];


						$dt = date('Y-m-d', strtotime($match));

					$sql = par_rep("/'$match'/", "'$dt'", $sql);
				}
			}
			if (substr($sql, 0, 6) == "BEGIN;") {
				$array = explode(";", $sql);

				foreach ($array as $value) {
					if ($value != "") {
						$user_agent = explode('/', $_SERVER['HTTP_USER_AGENT']);
						if ($user_agent[0] == 'Mozilla') {
							$result = $connection->query($value);
						}
						if (!$result) {
							$user_agent = explode('/', $_SERVER['HTTP_USER_AGENT']);
							if ($user_agent[0] == 'Mozilla') {
								$connection->query("ROLLBACK");
								die(db_show_error($sql, _dbExecuteFailed, mysqli_error($connection)));
							}
						}
					}
				}
			} else {
				$user_agent = explode('/', $_SERVER['HTTP_USER_AGENT']);
				if ($user_agent[0] == 'Mozilla') {
					$result = $connection->query($sql) or die(db_show_error($sql, _dbExecuteFailed, mysqli_error($connection)));
				}
			}
			break;
	}


    public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));

        if (! empty($action) && $this->actionModel->remove($action['id'])) {
            $this->flash->success(t('Action removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this action.'));
        }

        $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));
    }


    protected function getSubtask()
    {
        $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));

        if (empty($subtask)) {
            throw new PageNotFoundException();
        }

        return $subtask;
    }


    public function privateCore(&$response, $user, $permissions)
    {
        parent::privateCore($response, $user, $permissions);
        $this->model = new PageOption();
        $this->loadSelectedViewName();
        $this->backPage = $this->request->get('url') ?: $this->selectedViewName;
        $this->selectedUser = $this->user->admin ? $this->request->get('nick') : $this->user->nick;
        $this->loadPageOptions();

        $action = $this->request->get('action', '');
        switch ($action) {
            case 'delete':
                $this->deleteAction();
                break;

            case 'save':
                $this->saveAction();
                break;
        }
    }


                $pfTaskJob->update($input);
                $tasks_id = $data['plugin_glpiinventory_tasks_id'];
            }
        } else {
           // case 2: if not exist, create a new task + taskjob
            $this->getFromDB($packages_id);

           //Add the new task
            $input = [
            'name'                    => '[deploy on demand] ' . $this->fields['name'],
            'entities_id'             => $computer->fields['entities_id'],
            'reprepare_if_successful' => 0,
            'is_deploy_on_demand'     => 1,
            'is_active'               => 1,
            ];
            $tasks_id = $pfTask->add($input);

           //Add a new job for the newly created task
           //and enable it
            $input = [
            'plugin_glpiinventory_tasks_id' => $tasks_id,
            'entities_id' => $computer->fields['entities_id'],
            'name'        => 'deploy',
            'method'      => 'deployinstall',
            'targets'     => '[{"PluginGlpiinventoryDeployPackage":"' . $packages_id . '"}]',
            'actors'      => exportArrayToDB([['Computer' => $computers_id]]),
            'enduser'     => exportArrayToDB([$users_id  => [$computers_id]]),
            ];
            $pfTaskJob->add($input);
        }

       //Prepare the task (and only this one)
        $pfTask->prepareTaskjobs(['deployinstall'], $tasks_id);
    }


    public function save()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }


	public function netmountPrepare($options) {
		if (!empty($_REQUEST['encoding']) && @iconv('UTF-8', $_REQUEST['encoding'], '') !== false) {
			$options['encoding'] = $_REQUEST['encoding'];
			if (!empty($_REQUEST['locale']) && @setlocale(LC_ALL, $_REQUEST['locale'])) {
				setlocale(LC_ALL, elFinder::$locale);
				$options['locale'] = $_REQUEST['locale'];
			}
		}
		$options['statOwner'] = true;
		$options['allowChmodReadOnly'] = true;
		return $options;
	}