    function searchByModelForm() {
        // get the search terms
        $terms = $this->params['search_string'];

        $sql = "model like '%" . $terms . "%'";

        $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;
        $page = new expPaginator(array(
            'model'      => 'product',
            'where'      => $sql,
            'limit'      => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,
            'order'      => 'title',
            'dir'        => 'DESC',
            'page'       => (isset($this->params['page']) ? $this->params['page'] : 1),
            'controller' => $this->params['controller'],
            'action'     => $this->params['action'],
            'columns'    => array(
                gt('Model #')      => 'model',
                gt('Product Name') => 'title',
                gt('Price')        => 'base_price'
            ),
        ));

        assign_to_template(array(
            'page'  => $page,
            'terms' => $terms
        ));
    }


	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 remind()
	{
		/*if (!check_captcha())
		{
			$this->templatemanager->notify_next(__("You have entered wrong security code."), "error", __("Error!"));
			redirect("administration/auth/forgot");
			die;
		}//*/

		$email = trim($this->input->post("email", true));

		$u = User::factory()->get_by_email($email);

		if (!$u->exists())
		{
			$this->templatemanager->notify_next(__("User with that e-mail does not exists!"), "error", __("Error"));
			redirect("administration/auth/forgot");
		}

		$u->key = random_string('unique');
		$u->save();

		Log::write('requested password change', LogSeverity::Notice, $u->id);

		//set variables for template
		$vars = array(
			'name'=>$u->name
			,'email'=>$u->email

			,'website_title'=>Setting::value('website_title', CS_PRODUCT_NAME)
			,'reset_link'=>site_url('administration/auth/resetpass/'.$u->id.'/'.$u->key)
			,'site_url'=>site_url()
		);

		//get email template
		$template = file_get_contents(APPPATH . "templates/forgot_password.html");
		$template = __($template, null, 'email');
		$template .= "
\n
\n
\n" . __(file_get_contents(APPPATH . "templates/signature.html"), null, 'email');
		$template = parse_template($template, $vars);

		//send email
		$this->email->to("$email");
		$this->email->subject(__("%s password reset", Setting::value('website_title', CS_PRODUCT_NAME), 'email'));
		$this->email->message($template);
		$this->email->set_alt_message(strip_tags($template));

		$from = Setting::value("default_email", false);

		if (empty($from))
			$from = "noreply@".get_domain_name(true);

		$this->email->from($from);

		$sent = $this->email->send();

		if ($sent)
			$this->templatemanager->notify_next(__("Please check your e-mail for further information."), "notice", __("Notice"));
		else
			$this->templatemanager->notify_next(__("Activation e-mail could not be sent!"), "error", __("Error"));

		redirect("administration/auth/login");
	}


    public function getQueryOrderby()
    {
        return '`' . $this->name . '`';
    }


    public function showUnpublished() {
        expHistory::set('viewable', $this->params);

        // setup the where clause for looking up records.
        $where = parent::aggregateWhereClause();
        $where = "((unpublish != 0 AND unpublish < ".time().") OR (publish > ".time().")) AND ".$where;
        if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';

        $page = new expPaginator(array(
            'model'=>'news',
            'where'=>$where,
            'limit'=>25,
            'order'=>'unpublish',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title',
                gt('Published On')=>'publish',
                gt('Status')=>'unpublish'
            ),
        ));

        assign_to_template(array(
            'page'=>$page
        ));
    }


    public function search() {
//        global $db, $user;
        global $db;

        $sql = "select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "addresses as a "; //R JOIN " .
        //$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
        $sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
            "*' IN BOOLEAN MODE) ";
        $sql .= "order by match (a.firstname,a.lastname,a.email,a.organization)  against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
        $res = $db->selectObjectsBySql($sql);
        foreach ($res as $key=>$record) {
            $res[$key]->title = $record->firstname . ' ' . $record->lastname;
        }
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


            $loc = expCore::makeLocation('navigation', '', $standalone->id);
            if (expPermissions::check('manage', $loc)) return true;
        }
        return false;
    }


        foreach ($flatArray as $key => $value) {
            $pattern = '/' . $key . '([^.]|$)/';
            if (preg_match($pattern, $expression, $matches)) {

                switch (gettype($flatArray[$key])) {
                    case 'boolean':
                        $expression = str_replace($key, $flatArray[$key] ? 'true' : 'false', $expression);
                        break;
                    case 'NULL':
                        $expression = str_replace($key, 'false', $expression);
                        break;
                    case 'string':
                        $expression = str_replace($key, '"' . $flatArray[$key] . '"', $expression);
                        break;
                    case 'object':
                        $expression = self::executeClosure($expression, $key, $flatArray[$key], $flatArray);
                        break;
                    default:
                        $expression = str_replace($key, $flatArray[$key], $expression);
                        break;
                }
                $bool = eval("return $expression;");
            }
        }


        $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 manage_sitemap() {
        global $db, $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sasections'   => $db->selectObjects('section', 'parent=-1'),
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


	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();
	}


    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();
    }


    public function getQuerySelect()
    {
        $R1 = 'R1_' . $this->field->id;
        $R2 = 'R2_' . $this->field->id;
        return "$R2.id AS `" . $this->field->name . "`";
    }


						unset($return[$key]);
				}
			}
			break;
	}
	return @array_change_key_case($return, CASE_UPPER);
}


    public function actionDeleteDropdown() {
        $dropdowns = Dropdowns::model()->findAll();

        if (isset($_POST['dropdown'])) {
            if ($_POST['dropdown'] != Actions::COLORS_DROPDOWN_ID) {
                $model = Dropdowns::model()->findByPk($_POST['dropdown']);
                $model->delete();
                $this->redirect('manageDropDowns');
            }
        }

        $this->render('deleteDropdowns', array(
            'dropdowns' => $dropdowns,
        ));
    }


    public static function showModal($params) {

        if (!isset($params['argument']) || empty($params['argument'])) {
            return array(
                'processed' => true,
                'process_status' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/chatcommand', 'Please provide modal URL!')
            );
        }

        $paramsURL = explode(' ',$params['argument']);
        $URL = array_shift($paramsURL);

        if (is_numeric($URL)) {
            $URL =  (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . erLhcoreClassDesign::baseurldirect('form/formwidget') . '/' . $URL;
        }


    function storeSerializedSession($serialized_session_data, $session_id)
    {
        $doSession = OA_Dal::staticGetDO('session', $session_id);
        if ($doSession) {
            $doSession->sessiondata = $serialized_session_data;
            $doSession->update();
        }
        else {
            $doSession = OA_Dal::factoryDO('session');
            $doSession->sessionid = $session_id;
            $doSession->sessiondata = $serialized_session_data;
            $doSession->insert();
        }
    }


    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;
    }


    public function __construct($site)
    {
        // If the REST API Proxy Plugin isn't active, always use the current site.
        if(! PMB_REST_PROXY_EXISTS){
            $site = '';
        }
        $this->setSite($site);
        $this->getSiteInfo();
    }


   public function testEncrypt($string, $key, $expected) {
      $this->string(\Toolbox::encrypt($string, $key))->isIdenticalTo($expected);
   }


$contents = ['form' => tep_draw_form('testimonials', 'testimonials.php', 'page=' . $_GET['page'] . '&tID=' . $tInfo->testimonials_id . '&action=deleteconfirm')];


    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();
    }


            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }


    public function testAddsSlashForRelativeUriStringWithHost()
    {
        $uri = (new Uri)->withPath('foo')->withHost('bar.com');
        $this->assertEquals('foo', $uri->getPath());
        $this->assertEquals('bar.com/foo', (string) $uri);
    }


	public function setPageTextMatch( array $pageTextMatch = [] ) {
		$this->pageTextMatch = (array)$pageTextMatch;
	}


function XMLRPCaddImageGroupToComputerGroup($imageGroup, $computerGroup){
    $imageid = getResourceGroupID("image/$imageGroup");
    $compid = getResourceGroupID("computer/$computerGroup");
    if($imageid && $compid){
        $tmp = getUserResources(array("imageAdmin"),
                                array("manageMapping"), 1);
        $imagegroups = $tmp['image'];
        $tmp = getUserResources(array("computerAdmin"),
                                array("manageMapping"), 1);
        $computergroups = $tmp['computer'];

        if(array_key_exists($compid, $computergroups) &&
            array_key_exists($imageid, $imagegroups)){
            $mapping = getResourceMapping("image", "computer",
                                          $imageid,
                                          $compid);
            if(!array_key_exists($imageid, $mapping) ||
                !array_key_exists($compid, $mapping[$imageid])){
                $query = "INSERT INTO resourcemap "
                       .        "(resourcegroupid1, "
			           .        "resourcetypeid1, "
			           .        "resourcegroupid2, "
			           .        "resourcetypeid2) "
			           . "VALUES ($imageid, "
			           .         "13, "
			           .         "$compid, "
			           .         "12)";
                doQuery($query, 101);
            }
            return array('status' => 'success');
        } else {
            return array('status' => 'error',
                         'errorcode' => 84,
                         'errormsg' => 'cannot access computer and/or image group');
        }
    } else {
        return array('status' => 'error',
                     'errorcode' => 83,
                     'errormsg' => 'invalid resource group name');
    }
}


function gce_ajax_list() {

	$nonce = $_POST['gce_nonce'];

    // check to see if the submitted nonce matches with the
    // generated nonce we created earlier
    if ( ! wp_verify_nonce( $nonce, 'gce_ajax_nonce' ) ) {
        die ( 'Request has failed.');
	}

	$grouped          = $_POST['gce_grouped'];
	$start            = $_POST['gce_start'];
	$ids              = $_POST['gce_feed_ids'];
	$title_text       = $_POST['gce_title_text'];
	$sort             = $_POST['gce_sort'];
	$paging           = $_POST['gce_paging'];
	$paging_interval  = $_POST['gce_paging_interval'];
	$paging_direction = $_POST['gce_paging_direction'];
	$start_offset     = $_POST['gce_start_offset'];
	$paging_type      = $_POST['gce_paging_type'];

	if( $paging_direction == 'back' ) {
		if( $paging_type == 'month' ) {

			$this_month = mktime( 0, 0, 0, date( 'm', $start ) - 1, 1, date( 'Y', $start ) );
			$prev_month = mktime( 0, 0, 0, date( 'm', $start ) - 2, 1, date( 'Y', $start ) );
			$prev_interval_days = date( 't', $prev_month );
			$month_days = date( 't', $this_month );

			$int = $month_days + $prev_interval_days;
			$int = $int * 86400;

			$start = $start - ( $int );

			$changed_month_days = date( 't', $start );
			$paging_interval = $changed_month_days * 86400;
		} else {
			$start = $start - ( $paging_interval * 2 );
		}

	} else {
		if( $paging_type == 'month' ) {
			$days_in_month = date( 't', $start );
			$paging_interval = 86400 * $days_in_month;
		}
	}

	$d = new GCE_Display( explode( '-', $ids ), $title_text, $sort  );

	echo $d->get_list( $grouped, $start, $paging, $paging_interval, $start_offset );

	die();
}


	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();
	}


	public function testDolEval()
	{
		global $conf,$user,$langs,$db;
		$conf=$this->savconf;
		$user=$this->savuser;
		$langs=$this->savlangs;
		$db=$this->savdb;

		$result=dol_eval('1==1', 1, 0);
		print "result = ".$result."\n";
		$this->assertTrue($result);

		$result=dol_eval('1==2', 1, 0);
		print "result = ".$result."\n";
		$this->assertFalse($result);

		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
		include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
		$result=dol_eval('(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref: "Parent project not found"', 1, 1);
		print "result = ".$result."\n";
		$this->assertEquals('Parent project not found', $result);

		$result=dol_eval('$a=function() { }; $a;', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a=exec("ls");', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a=exec ("ls")', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a="test"; $$a;', 1, 0);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('`ls`', 1, 0);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);
	}


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


            $text = preg_replace($exp, '', $text);
        }

        // Primary expression to filter out tags
        $exp = '/(?:^|\s|\.)(#\w+[-\w]+\w+|#\w+)(?:$|[^\'"])/u';

        $matches = array();
        preg_match_all($exp, $text, $matches);

        return $matches;
    }


    public function addFile($filename, $conditional_ie = false)
    {
        $hash = md5($filename);
        if (!empty($this->_files[$hash])) {
            return;
        }

        $has_onload = $this->_eventBlacklist($filename);
        $this->_files[$hash] = array(
            'has_onload' => $has_onload,
            'filename' => $filename,
            'conditional_ie' => $conditional_ie
        );
    }


    private function getCategory()
    {
        $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));

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

        return $category;
    }


    public function crossOriginRedirectProvider()
    {
        return [
            ['http://example.com?a=b', 'http://test.com/', false],
            ['https://example.com?a=b', 'https://test.com/', false],
            ['http://example.com?a=b', 'https://test.com/', false],
            ['https://example.com?a=b', 'http://test.com/', false],
            ['http://example.com?a=b', 'http://example.com/', true],
            ['https://example.com?a=b', 'https://example.com/', true],
            ['http://example.com?a=b', 'https://example.com/', true],
            ['https://example.com?a=b', 'http://example.com/', false],
        ];
    }


    static function author() {
        return "Dave Leffler";
    }


                    $db->updateObject($value, 'section');
                }
                $db->updateObject($moveSec, 'section');
                //handle re-ranking of previous parent
                $oldSiblings = $db->selectObjects("section", "parent=" . $oldParent . " AND rank>" . $oldRank . " ORDER BY rank");
                $rerank      = 1;
                foreach ($oldSiblings as $value) {
                    if ($value->id != $moveSec->id) {
                        $value->rank = $rerank;
                        $db->updateObject($value, 'section');
                        $rerank++;
                    }
                }
                if ($oldParent != $moveSec->parent) {
                    //we need to re-rank the children of the parent that the moving section has just left
                    $childOfLastMove = $db->selectObjects("section", "parent=" . $oldParent . " ORDER BY rank");
                    for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {
                        $childOfLastMove[$i]->rank = $i;
                        $db->updateObject($childOfLastMove[$i], 'section');
                    }
                }
            }
        }
        self::checkForSectionalAdmins($move);
        expSession::clearAllUsersSessionCache('navigation');
    }


    public static function getKey ($var) {
        return self::$hooks[$var];
    }


		form_end_row();
		$i++;
	}

	html_end_box(false);

/*
	print "<pre>";
	if (isset($check) && is_array($check)) {
		print_r($check);
	}
	print "</pre>";
*/

}


    static function displayname() {
        return gt("e-Commerce Category Manager");
    }


    public function updatePreferences(Codendi_Request $request)
    {
        $request->valid(new Valid_String('cancel'));
        if (!$request->exist('cancel')) {
            $job_id = $request->get($this->widget_id . '_job_id');
            $sql = "UPDATE plugin_hudson_widget SET job_id=" . $job_id . " WHERE owner_id = " . $this->owner_id . " AND owner_type = '" . $this->owner_type . "' AND id = " . (int) $request->get('content_id');
            $res = db_query($sql);
        }


    public static function getList () {
        $handle = dir(GX_PATH.'/inc/lang/');
        while (false !== ($entry = $handle->read())) {
            if ($entry != "." && $entry != ".." ) {
                $file = GX_PATH.'/inc/lang/'.$entry;
                $ext = pathinfo($file, PATHINFO_EXTENSION);
                if(is_file($file) == true && $ext == 'php'){
                    $lang[] = $entry;
                }
            }
        }

        $handle->close();
        return $lang;
    }


    public static function _date2timestamp( $datetime, $wtz=null ) {
      if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
      if( !isset( $datetime['min'] ))  $datetime['min']  = 0;
      if( !isset( $datetime['sec'] ))  $datetime['sec']  = 0;
      if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty(  $datetime['tz'] )))
        return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      $output = $offset = 0;
      if( empty( $wtz )) {
        if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
          $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
          $wtz    = 'UTC';
        }
        else
          $wtz    = $datetime['tz'];
      }
      if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
        $wtz      = 'UTC';
      try {
        $strdate  = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
        $d        = new DateTime( $strdate, new DateTimeZone( $wtz ));
        if( 0    != $offset )  // adjust for offset
          $d->modify( $offset.' seconds' );
        $output   = $d->format( 'U' );
        unset( $d );
      }
      catch( Exception $e ) {
        $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      }
      return $output;
    }


            $opt .= "<option value=\"{$key}\" title=\"".htmlspecialchars($value)."\" {$sel}>".htmlspecialchars($value)."</option>";

        }
        return $opt;

    }


    public function confirm()
    {
        $task = $this->getTask();
        $link = $this->getTaskLink();

        $this->response->html($this->template->render('task_internal_link/remove', array(
            'link' => $link,
            'task' => $task,
        )));
    }


                    $value = str_replace($originalName, $cleanedName, $value);
                }
                unset($value);
            }
            $result = hash_equals(GeneralUtility::hmac(serialize($fieldChangeFunctions)), $this->parameters['fieldChangeFuncHash']);
        }
        return $result;
    }


    public static function desc($vars){
        if(!empty($vars)){
            $desc = substr(strip_tags(htmlspecialchars_decode($vars).". ".self::$desc),0,150);
        }else{
            $desc = substr(self::$desc,0,150);
        }
        $desc = Hooks::filter('site_desc_filter', $desc);
        return $desc;
    }


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

        /* 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('No ID supplied for comment to approve'));
	        expHistory::back();
	    }

	    $comment = new expComment($this->params['id']);
	    assign_to_template(array(
            'comment'=>$comment
        ));
	}


function db_properties($table)
{
	global $DatabaseType, $DatabaseUsername;

	switch ($DatabaseType) {
		case 'mysqli':
			$result = DBQuery("SHOW COLUMNS FROM $table");
			while ($row = db_fetch_row($result)) {
				$properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));
				if (!$pos = strpos($row['TYPE'], ','))
					$pos = strpos($row['TYPE'], ')');
				else
					$properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);

				$properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);

				if ($row['NULL'] != '')
					$properties[strtoupper($row['FIELD'])]['NULL'] = "Y";
				else
					$properties[strtoupper($row['FIELD'])]['NULL'] = "N";
			}
			break;
	}
	return $properties;
}


    public function renderAttribute ($name) {
        switch ($name) {
            case 'name':
                echo $this->relatedModel->getLink (/*array (
                    'class' => 'quick-read-link',
                    'data-id' => $this->relatedModel->id,
                    'data-class' => get_class ($this->relatedModel),
                    'data-name' => CHtml::encode ($this->relatedModel->name),
                )*/);
                break;
            case 'relatedModelName':
                echo $this->getRelatedModelName ();
                break;
            case 'assignedTo':
                echo $this->relatedModel->renderAttribute ('assignedTo');
                break;
            case 'label':
                echo $this->getLabel ();
                break;
            case 'createDate':
                echo X2Html::dynamicDate ($this->relatedModel->createDate);
                break;
        }
    }


    function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }


    function selectArraysBySql($sql) {
        $res = @mysqli_query($this->connection, $this->injectProof($sql));
        if ($res == null)
            return array();
        $arrays = array();
        for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)
            $arrays[] = mysqli_fetch_assoc($res);
        return $arrays;
    }


    public function getRequestFormat($default = 'html')
    {
        if (null === $this->format) {
            $this->format = $this->get('_format', $default);
        }

        return $this->format;
    }


	static public function getCategoryName($_id = 0) {

		if ($_id != 0) {
			$stmt = Database::prepare("
				SELECT `name` FROM `" . TABLE_PANEL_TICKET_CATS . "` WHERE `id` = :id"
			);
			$category = Database::pexecute_first($stmt, array('id' => $_id));
			return $category['name'];
		}
		return null;
	}


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

        $this->response->html($this->helper->layout->project('column/remove', array(
            'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),
            'project' => $project,
        )));
    }


    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,
        )));
    }


    protected function itemLocked($hash)
    {
        if (!elFinder::$commonTempPath) {
            return false;
        }
        $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
        if (file_exists($lock)) {
            if (filemtime($lock) + $this->itemLockExpire < time()) {
                unlink($lock);
                return false;
            }
            return true;
        }

        return false;
    }


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

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


    public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
    {
        if (\strpos((string) $response->getStatusCode(), '3') !== 0
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request, $response, $options);
        $nextRequest = $this->modifyRequest($request, $options, $response);

        // If authorization is handled by curl, unset it if host is different.
        if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()
            && defined('\CURLOPT_HTTPAUTH')
        ) {
            unset(
                $options['curl'][\CURLOPT_HTTPAUTH],
                $options['curl'][\CURLOPT_USERPWD]
            );
        }

        if (isset($options['allow_redirects']['on_redirect'])) {
            ($options['allow_redirects']['on_redirect'])(
                $request,
                $response,
                $nextRequest->getUri()
            );
        }

        $promise = $this($nextRequest, $options);

        // Add headers to be able to track history of redirects.
        if (!empty($options['allow_redirects']['track_redirects'])) {
            return $this->withTracking(
                $promise,
                (string) $nextRequest->getUri(),
                $response->getStatusCode()
            );
        }

        return $promise;
    }


    public static function add($tags) {

        $tag = explode(",", $tags);
        foreach ($tag as $t) {
            if (self::exist($t)) {
                return false;
            }else{
                $slug = Typo::slugify(Typo::cleanX($t));
                $cat = Typo::cleanX($t);
                $tag = Db::insert(
                            sprintf("INSERT INTO `cat` VALUES (null, '%s', '%s', '%d', '', 'tag' )",
                                $cat, $slug, 0
                            )
                        );
                return true;
            }
        }

    }


    private function drain(StreamInterface $source, StreamInterface $sink)
    {
        Psr7\copy_to_stream($source, $sink);
        $sink->seek(0);
        $source->close();

        return $sink;
    }


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


                $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);
                if (!empty($newret)) $ret .= $newret . '<br>';
                if ($iLoc->mod == 'container') {
                    $ret .= scan_container($container->internal, $page_id);
                }
            }
            return $ret;
        }


    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 function setContainer($container)
    {
        $this->container = $container;
        $container->setType('ctArticles');
    }


function nvweb_website_comments_list($offset=0, $limit=2147483647, $permission=NULL, $order='oldest')
{
    global $DB;
    global $website;
    global $current;

    if($order=='newest')
        $orderby = "nvc.date_created DESC";
    else
        $orderby = "nvc.date_created ASC";

    $DB->query('SELECT SQL_CALC_FOUND_ROWS nvc.*, nvwu.username, nvwu.avatar, nvwd.text as item_title
				  FROM nv_comments nvc
				 LEFT OUTER JOIN nv_webusers nvwu
							  ON nvwu.id = nvc.user
				 LEFT OUTER JOIN nv_webdictionary nvwd
				              ON nvwd.node_id = nvc.object_id AND
                                 nvwd.website = nvc.website AND
                                 nvwd.node_type = nvc.object_type AND
                                 nvwd.subtype = "title" AND
                                 nvwd.lang = '.protect($current['lang']).'
				 WHERE nvc.website = '.protect($website->id).'
				   AND status = 0
				ORDER BY '.$orderby.'
				LIMIT '.$limit.'
			   OFFSET '.$offset);

    $rs = $DB->result();
    $total = $DB->foundRows();

    return array($rs, $total);
}


    public function __construct()
    {
        parent::__construct();

        $this->middleware(
            function ($request, $next) {
                app('view')->share('title', (string) trans('firefly.currencies'));
                app('view')->share('mainTitleIcon', 'fa-usd');
                $this->repository     = app(CurrencyRepositoryInterface::class);
                $this->userRepository = app(UserRepositoryInterface::class);

                return $next($request);
            }
        );
    }


    public function testGetRoutes($uri, $expectedVersion, $expectedController, $expectedAction, $expectedId)
    {
        $request = new Enlight_Controller_Request_RequestTestCase();
        $request->setMethod('GET');

        $response = new Enlight_Controller_Response_ResponseTestCase();

        $request->setPathInfo($uri);
        $this->router->assembleRoute($request, $response);

        static::assertEquals($expectedController, $request->getControllerName());
        static::assertEquals($expectedAction, $request->getActionName());
        static::assertEquals($expectedVersion, $request->getParam('version'));
        static::assertEquals($expectedId, $request->getParam('id'));
        static::assertEquals(200, $response->getHttpResponseCode());
    }


    public function savePassword()
    {
        $user = $this->getUser();
        $values = $this->request->getValues();

        list($valid, $errors) = $this->userValidator->validatePasswordModification($values);

        if (! $this->userSession->isAdmin()) {
            $values['id'] = $this->userSession->getId();
        }

        if ($valid) {
            if ($this->userModel->update($values)) {
                $this->flash->success(t('Password modified successfully.'));
                $this->userLockingModel->resetFailedLogin($user['username']);
                $this->response->redirect($this->helper->url->to('UserViewController', 'show', array('user_id' => $user['id'])), true);
                return;
            } else {
                $this->flash->failure(t('Unable to change the password.'));
            }
        }

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


   static function searchUser(AuthLDAP $authldap) {

      if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),
                                $authldap->getField('rootdn'),
                                Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),
                                $authldap->getField('use_tls'),
                                $authldap->getField('deref_option'))) {
         self::showLdapUsers();

      } else {
         echo "<div class='center b firstbloc'>".__('Unable to connect to the LDAP directory');
      }
   }


if ($current_realm_id == -1 || is_realm_allowed($current_realm_id) || !isset($user_auth_realm_filenames{basename($item_url)})) {
						/* draw normal (non sub-item) menu item */
						$item_url = $config['url_path'] . $item_url;
						if (is_menu_pick_active($item_url)) {
							print "
$item_title
\n";
						} else {
							print "
$item_title
\n";
						}
					}
				}
			}


	public function load_by_hash($hash)
	{
		global $DB;
		global $session;
        global $events;

        $ok = $DB->query('SELECT * FROM nv_webusers WHERE cookie_hash = '.protect($hash));
        if($ok)
            $data = $DB->result();

        if(!empty($data))
		{
			$this->load_from_resultset($data);

			// check if the user is still allowed to sign in
			$blocked = 1;
			if( $this->access == 0 ||
                ( $this->access == 2 &&
                    ($this->access_begin==0 || $this->access_begin < time()) &&
                    ($this->access_end==0 || $this->access_end > time())
                )
            )
			{
				$blocked = 0;
			}

			if($blocked==1)
				return false;

			$session['webuser'] = $this->id;

            // maybe this function is called without initializing $events
            if(method_exists($events, 'trigger'))
            {
                $events->trigger(
                    'webuser',
                    'sign_in',
                    array(
                        'webuser' => $this,
                        'by' => 'cookie'
                    )
                );
            }
		}

	}


	public static function startup()
	{
		//Override the default expire time of token
		\CsrfMagic\Csrf::$expires = 259200;
		\CsrfMagic\Csrf::$callback = function ($tokens) {
			throw new \App\Exceptions\AppException('Invalid request - Response For Illegal Access', 403);
		};
		$js = 'vendor/yetiforce/csrf-magic/src/Csrf.min.js';
		if (!IS_PUBLIC_DIR) {
			$js = 'public_html/' . $js;
		}
		\CsrfMagic\Csrf::$dirSecret = __DIR__;
		\CsrfMagic\Csrf::$rewriteJs = $js;
		\CsrfMagic\Csrf::$cspToken = \App\Session::get('CSP_TOKEN');
		\CsrfMagic\Csrf::$frameBreaker = \Config\Security::$csrfFrameBreaker;
		\CsrfMagic\Csrf::$windowVerification = \Config\Security::$csrfFrameBreakerWindow;

		/*
		 * if an ajax request initiated, then if php serves content with <html> tags
		 * as a response, then unnecessarily we are injecting csrf magic javascipt
		 * in the response html at <head> and <body> using csrf_ob_handler().
		 * So, to overwride above rewriting we need following config.
		 */
		if (static::isAjax()) {
			\CsrfMagic\Csrf::$frameBreaker = false;
			\CsrfMagic\Csrf::$rewriteJs = null;
		}
	}


    function productFeed() {
//        global $db;
        //check query password to avoid DDOS
        /*
            * condition  = new
            * description
            * id - SKU
            * link
            * price
            * title
            * brand - manufacturer
            * image link - fullsized image, up to 10, comma seperated
            * product type - category - "Electronics > Audio > Audio Accessories MP3 Player Accessories","Health & Beauty > Healthcare > Biometric Monitors > Pedometers"
         */
        $out = '"id","condition","description","like","price","title","brand","image link","product type"' . chr(13) . chr(10);

        $p = new product();
        $prods = $p->find('all', 'parent_id=0 AND ');
        //$prods =  $db->selectObjects('product','parent_id=0 AND');
    }


$json_response = ['status' => 'error', 'message' => $e->getMessage()];


  function extract_plural_forms_header_from_po_header($header) {
    if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs))
      $expr = $regs[2];
    else
      $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
    return $expr;
  }


static function isSearchable() { return true; }


                        $product = X2Model::model('Products')->findByAttributes(array('name'=>$lineItem->name));
                        if (isset($product))
                            $lineItem->productId = $product->id;
            if(empty($lineItem->currency))
				$lineItem->currency = $defaultCurrency;
			if($lineItem->isPercentAdjustment) {
				$lineItem->adjustment = Fields::strToNumeric(
                    $lineItem->adjustment,'percentage');
			} else {
				$lineItem->adjustment = Fields::strToNumeric(
                    $lineItem->adjustment,'currency',$curSym);
			}
			$lineItem->price = Fields::strToNumeric($lineItem->price,'currency',$curSym);
			$lineItem->total = Fields::strToNumeric($lineItem->total,'currency',$curSym);
		}


   private function getNewPrinter() {
      $printer  = getItemByTypeName('Printer', '_test_printer_all');
      $pfields  = $printer->fields;
      unset($pfields['id']);
      unset($pfields['date_creation']);
      unset($pfields['date_mod']);
      $pfields['name'] = $this->getUniqueString();
      $this->integer((int)$printer->add($pfields))->isGreaterThan(0);
      return $printer;
   }


    function ac_checkme($id, $name) {
        global $cms_db;

        $ret = true;
        $cquery = sprintf("select count(*) from %s where sid='%s' and name='%s'",
            $cms_db['sessions'],
            $id,
            $name);
        $squery = sprintf("select sid from %s where sid  = '%s' and name = '%s'",
            $cms_db['sessions'],
            $id,
            addslashes($name));
        $this->db->query($squery);
        if ( $this->db->affected_rows() == 0
            && $this->db->query($cquery)
	        && $this->db->next_record() && $this->db->f(0) == 0 ) {
            // nothing found here
            $ret = false;
        }
        return $ret;
    }


            $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,
		));
	}


    protected function generateCookieHash($class, $username, $expires, $password)
    {
        return hash_hmac('sha256', $class.$username.$expires.$password, $this->getSecret());
    }


  function select_string($n) {
    if (!is_int($n)) {
      throw new InvalidArgumentException(
        "Select_string only accepts integers: " . $n);
    }
    $string = $this->get_plural_forms();
    $string = str_replace('nplurals',"\$total",$string);
    $string = str_replace("n",$n,$string);
    $string = str_replace('plural',"\$plural",$string);

    $total = 0;
    $plural = 0;

    eval("$string");
    if ($plural >= $total) $plural = $total - 1;
    return $plural;
  }


    public function disable($id) {
        $this->active($id, FALSE);
    }


    public function delete(){
        $page_id = I("page_id/d")? I("page_id/d") : 0;
        $page = D("Page")->where(" page_id = '$page_id' ")->find();

        $login_user = $this->checkLogin();
        if (!$this->checkItemManage($login_user['uid'] , $page['item_id']) && $login_user['uid'] != $page['author_uid']) {
            $this->sendError(10303);
            return ;
        }

        if ($page) {

            $ret = D("Page")->softDeletePage($page_id);
            //更新项目时间
            D("Item")->where(" item_id = '$page[item_id]' ")->save(array("last_update_time"=>time()));

        }
        if ($ret) {
           $this->sendResult(array());
        }else{
           $this->sendError(10101);
        }
    }


    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 getQuerySelect()
    {
        return "R_{$this->id}.rank AS `$this->name`";
    }


    public function testUserCredentials($email, $password, $server, $port, $security) {
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.phpmailer.php'));
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.smtp.php'));
        $phpMail = new PHPMailer(true);

        $phpMail->isSMTP();
        $phpMail->SMTPAuth = true;
        $phpMail->Username = $email;
        $phpMail->Password = $password;
        $phpMail->Host = $server;
        $phpMail->Port = $port;
        $phpMail->SMTPSecure = $security;

        try {
            $validCredentials = $phpMail->SmtpConnect();
        } catch(phpmailerException $error) {
            $validCredentials = false;
        }
        return $validCredentials;
    }


	private function readData() {

		if (isset($this->tid)
			&& $this->tid != - 1
		) {
			$_ticket_stmt = Database::prepare('
				SELECT * FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'
			);
			$_ticket = Database::pexecute_first($_ticket_stmt, array('tid' => $this->tid));

			$this->Set('customer', $_ticket['customerid'], true, false);
			$this->Set('admin', $_ticket['adminid'], true, false);
			$this->Set('subject', $_ticket['subject'], true, false);
			$this->Set('category', $_ticket['category'], true, false);
			$this->Set('priority', $_ticket['priority'], true, false);
			$this->Set('message', $_ticket['message'], true, false);
			$this->Set('dt', $_ticket['dt'], true, false);
			$this->Set('lastchange', $_ticket['lastchange'], true, false);
			$this->Set('ip', $_ticket['ip'], true, false);
			$this->Set('status', $_ticket['status'], true, false);
			$this->Set('lastreplier', $_ticket['lastreplier'], true, false);
			$this->Set('by', $_ticket['by'], true, false);
			$this->Set('answerto', $_ticket['answerto'], true, false);
			$this->Set('archived', $_ticket['archived'], true, false);
		}
	}


                foreach ($page as $pageperm) {
                    if (!empty($pageperm['manage'])) return true;
                }


    public function backup($type='json')
    {
        global $DB;
        global $website;

        $out = array();

        $DB->query('SELECT * FROM nv_templates WHERE website = '.protect($website->id), 'object');

        if($type='json')
            $out = json_encode($DB->result());

        return $out;
    }


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

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


function SafeStripSlashes($string) {
	return (get_magic_quotes_gpc() ? stripslashes($string) : $string);
}


    static function is_username($username, &$error='') {
        if (strlen($username)<2)
            $error = __('Username must have at least two (2) characters');
        elseif (!preg_match('/^[\p{L}\d._-]+$/u', $username))
            $error = __('Username contains invalid characters');
        return $error == '';
    }


    private function getTaskLink()
    {
        $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));

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

        return $link;
    }


    public function downloadfile() {
        if (empty($this->params['fileid'])) {
            flash('error', gt('There was an error while trying to download your file.  No File Specified.'));
            expHistory::back();
        }

        $fd = new filedownload($this->params['fileid']);
        if (empty($this->params['filenum'])) $this->params['filenum'] = 0;

        if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {
            flash('error', gt('There was an error while trying to download your file.  The file you were looking for could not be found.'));
            expHistory::back();
        }

        $fd->downloads++;
        $fd->save();

        // this will set the id to the id of the actual file..makes the download go right.
        $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;
        parent::downloadfile();
    }


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


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


    public static function update($vars) {
        if(is_array($vars)){

            //print_r($vars);
            $u = $vars['user'];
            $sql = array(
                            'table' => 'user',
                            'id' => $vars['id'],
                            'key' => $u,
                        );
            Db::update($sql);
            if(isset($vars['detail']) && $vars['detail'] != ''){

                $u = $vars['detail'];
                $sql = array(
                                'table' => 'user_detail',
                                'id' => $vars['id'],
                                'key' => $u,
                            );
                Db::update($sql);
            }
            Hooks::run('user_sqledit_action', $vars);

        }
    }


	public function approve_submit() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('No ID supplied for comment to approve'));
	        expHistory::back();
	    }

        /* 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'];

	    $comment = new expComment($this->params['id']);
	    $comment->body = $this->params['body'];
	    $comment->approved = $this->params['approved'];
	    $comment->save();
	    expHistory::back();
	}


    public function upload() {
        if (!AuthUser::hasPermission('file_manager_upload')) {
            Flash::set('error', __('You do not have sufficient permissions to upload a file.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $mask = Plugin::getSetting('umask', 'file_manager');
        umask(octdec($mask));

        $data = $_POST['upload'];
        $path = str_replace('..', '', $data['path']);
        $overwrite = isset($data['overwrite']) ? true : false;

        // Clean filenames
        $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);
        $filename = preg_replace('/[^a-z0-9_\-\.]/i', '', $filename);

        if (isset($_FILES)) {
            $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);

            if ($file === false)
                Flash::set('error', __('File has not been uploaded!'));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }


    public function actionGetItems(){
        $model = X2Model::model ($this->modelClass);
        if (isset ($model)) {
            $tableName = $model->tableName ();
            $sql =
                'SELECT id, fileName as value
                 FROM '.$tableName.'
                 WHERE associationType!="theme" and fileName LIKE :qterm
                 ORDER BY fileName ASC';
            $command = Yii::app()->db->createCommand($sql);
            $qterm = $_GET['term'].'%';
            $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
            $result = $command->queryAll();
            echo CJSON::encode($result);
        }
        Yii::app()->end();
    }


	public function delete() {
	    global $user;

        $count = $this->address->find('count', 'user_id=' . $user->id);
        if($count > 1)
        {
            $address = new address($this->params['id']);
	        if ($user->isAdmin() || ($user->id == $address->user_id)) {
                if ($address->is_billing)
                {
                    $billAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $billAddress->is_billing = true;
                    $billAddress->save();
                }
                if ($address->is_shipping)
                {
                    $shipAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $shipAddress->is_shipping = true;
                    $shipAddress->save();
                }
	            parent::delete();
	        }
        }
        else
        {
            flash("error", gt("You must have at least one address."));
        }
	    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 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 function getPLaying(){
        $url = "http://api.themoviedb.org/3/movie/now_playing?api_key=".$this->apikey;
        $now_playing = $this->curl($url);
        return $now_playing;
    }


    function edit() {
        global $user;

        /* 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['formtitle']))
        {
            if (empty($this->params['id']))
            {
                $formtitle = gt("Add New Note");
            }
            else
            {
                $formtitle = gt("Edit Note");
            }
        }
        else
        {
            $formtitle = $this->params['formtitle'];
        }

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $simpleNote = new expSimpleNote($id);
        //FIXME here is where we might sanitize the note before displaying/editing it

        assign_to_template(array(
            'simplenote'=>$simpleNote,
            'user'=>$user,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'formtitle'=>$formtitle,
            'content_type'=>$this->params['content_type'],
            'content_id'=>$this->params['content_id'],
            'tab'=>empty($this->params['tab'])?0:$this->params['tab']
        ));
    }


    public static function _date2timestamp( $datetime, $wtz=null ) {
      if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
      if( !isset( $datetime['min'] ))  $datetime['min']  = 0;
      if( !isset( $datetime['sec'] ))  $datetime['sec']  = 0;
      if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty(  $datetime['tz'] )))
        return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      $output = $offset = 0;
      if( empty( $wtz )) {
        if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
          $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
          $wtz    = 'UTC';
        }
        else
          $wtz    = $datetime['tz'];
      }
      if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
        $wtz      = 'UTC';
      try {
        $strdate  = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
        $d        = new DateTime( $strdate, new DateTimeZone( $wtz ));
        if( 0    != $offset )  // adjust for offset
          $d->modify( $offset.' seconds' );
        $output   = $d->format( 'U' );
        unset( $d );
      }
      catch( Exception $e ) {
        $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      }
      return $output;
    }


    public static function validateByRegex($path, $values, $regex)
    {
        $result = preg_match($regex, $values[$path]);
        return array($path => ($result ? '' : __('Incorrect value!')));
    }


            $files[$key]->save();
        }

//        eDebug($files,true);
    }


                    $that->options['id_field'] => new \MongoDate(),
                );
            }));


            foreach($item->attributes as $name => $value)
                if ($name !== 'id' && $name !== 'listId')
                    $copy->$name = $value;
            $lineItems[] = $copy;
        }
        return $lineItems;
    }


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;
    }


                $banner->increaseImpressions();
            }
        }

        // assign banner to the template and show it!
        assign_to_template(array(
            'banners'=>$banners
        ));
    }


    public function save($check_notify = false)
    {
        if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {
            $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));
        }

        return parent::save($check_notify);
    }


	public function install(array $options = null, &$status=null)
	{
		parent::install($options);
		parent::setup($options);

		//check if ssl is enabled
        $this->appcontext->run('v-list-web-domain', [$this->appcontext->user(), $this->domain, 'json'], $status);
		$sslEnabled = ($status->json[$this->domain]['SSL'] == 'no' ? 0 : 1);

		$webDomain = ($sslEnabled ? "https://" : "http://") . $this->domain . "/";

		$this->appcontext->runUser('v-copy-fs-directory',[
			$this->getDocRoot($this->extractsubdir . "/dokuwiki-release_stable_2020-07-29/."),
			$this->getDocRoot()], $status);

		// enable htaccess
		$this->appcontext->runUser('v-move-fs-file', [$this->getDocRoot(".htaccess.dist"), $this->getDocRoot(".htaccess")], $status);

		$installUrl = $webDomain . "install.php";

		$cmd = "curl --request POST "
		  . ($sslEnabled ? "" : "--insecure " )


    private function setColumnOption(&$column, string $name, string $key, bool $isWidget, bool $allowEmpty)
    {
        $newValue = $this->request->request->get($name . '-' . $key);
        if ($isWidget) {
            if (!empty($newValue) || $allowEmpty) {
                $column['children'][0][$key] = $newValue;
            }
            return;
        }

        if (!empty($newValue) || $allowEmpty) {
            $column[$key] = $newValue;
        }
    }


	public function update_version() {
	    // get the current version
	    $hv = new help_version();
	    $current_version = $hv->find('first', 'is_current=1');

	    // check to see if the we have a new current version and unset the old current version.
	    if (!empty($this->params['is_current'])) {
//	        $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');
            help_version::clearHelpVersion();
	    }
	    expSession::un_set('help-version');

	    // save the version
	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $version = new help_version();
	    // if we don't have a current version yet so we will force this one to be it
	    if (empty($current_version->id)) $this->params['is_current'] = 1;
	    $version->update($this->params);

	    // if this is a new version we need to copy over docs
	    if (empty($id)) {
	        self::copydocs($current_version->id, $version->id);
	    }
        // let's update the search index to reflect the current help version
        searchController::spider();

	    flash('message', gt('Saved help version').' '.$version->version);
	    expHistory::back();
	}


	function unlockTables() {
        $sql = "UNLOCK TABLES";

        $res = mysqli_query($this->connection, $sql);
        return $res;
    }


  public function AddBCC($address, $name = '') {
    return $this->AddAnAddress('bcc', $address, $name);
  }


    protected function renderImageByGD($code)
    {
        $image = imagecreatetruecolor($this->width, $this->height);

        $backColor = imagecolorallocate(
            $image,
            (int) ($this->backColor % 0x1000000 / 0x10000),
            (int) ($this->backColor % 0x10000 / 0x100),
            $this->backColor % 0x100
        );
        imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
        imagecolordeallocate($image, $backColor);

        if ($this->transparent) {
            imagecolortransparent($image, $backColor);
        }

        $foreColor = imagecolorallocate(
            $image,
            (int) ($this->foreColor % 0x1000000 / 0x10000),
            (int) ($this->foreColor % 0x10000 / 0x100),
            $this->foreColor % 0x100
        );

        $length = strlen($code);
        $box = imagettfbbox(30, 0, $this->fontFile, $code);
        $w = $box[4] - $box[0] + $this->offset * ($length - 1);
        $h = $box[1] - $box[5];
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);
            $angle = mt_rand(-10, 10);
            $letter = $code[$i];
            $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
            $x = $box[2] + $this->offset;
        }

        imagecolordeallocate($image, $foreColor);

        ob_start();
        imagepng($image);
        imagedestroy($image);

        return ob_get_clean();
    }


	static public function addCategory($_category = null, $_admin = 1, $_order = 1) {

		if ($_category != null
			&& $_category != ''
		) {
			if ($_order < 1) {
				$_order = 1;
			}

			$ins_stmt = Database::prepare("
				INSERT INTO `" . TABLE_PANEL_TICKET_CATS . "` SET
					`name` = :name,
					`adminid` = :adminid,
					`logicalorder` = :lo"
			);
			$ins_data = array(
				'name' => $_category,
				'adminid' => $_admin,
				'lo' => $_order
			);
			Database::pexecute($ins_stmt, $ins_data);
			return true;
		}
		return false;
	}


	public function formatTemplateArg( $arg, $s, $argNr, $firstCall, $maxLength, Article $article ) {
		$tableFormat = $this->getParameters()->getParameter( 'tablerow' );
		// we could try to format fields differently within the first call of a template
		// currently we do not make such a difference

		// if the result starts with a '-' we add a leading space; thus we avoid a misinterpretation of |- as
		// a start of a new row (wiki table syntax)
		if ( array_key_exists( "$s.$argNr", $tableFormat ) ) {
			$n = -1;
			if ( $s >= 1 && $argNr == 0 && !$firstCall ) {
				$n = strpos( $tableFormat["$s.$argNr"], '|' );
				if ( $n === false || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '{' ) === false ) || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '[' ) === false ) ) {
					$n = -1;
				}
			}
			$result = str_replace( '%%', $arg, substr( $tableFormat["$s.$argNr"], $n + 1 ) );
			$result = str_replace( '%PAGE%', $article->mTitle->getPrefixedText(), $result );
			$result = str_replace( '%IMAGE%', $this->parseImageUrlWithPath( $arg ), $result ); //@TODO: This just blindly passes the argument through hoping it is an image.  --Alexia
			$result = $this->cutAt( $maxLength, $result );
			if ( strlen( $result ) > 0 && $result[0] == '-' ) {
				return ' ' . $result;
			} else {
				return $result;
			}
		}
		$result = $this->cutAt( $maxLength, $arg );
		if ( strlen( $result ) > 0 && $result[0] == '-' ) {
			return ' ' . $result;
		} else {
			return $result;
		}
	}


   static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,
                                   $onlyglobal = 0, $used = []) {
      global $CFG_GLPI;

      $rand     = mt_rand();

      $field_id = Html::cleanId("dropdown_".$myname.$rand);
      $param    = [
         'entity_restrict' => $entity_restrict,
         'fromtype'        => $fromtype,
         'itemtype'        => $itemtype,
         'onlyglobal'      => $onlyglobal,
         'used'            => $used,
         '_idor_token'     => Session::getNewIDORToken($itemtype),
      ];

      echo Html::jsAjaxDropdown($myname, $field_id,
                                $CFG_GLPI['root_doc']."/ajax/getDropdownConnect.php",
                                $param);

      return $rand;
   }


    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'])));
    }


		if(!is_array($sections)) $sections = array();
		foreach($sections as $section)
		{
			if(!empty($section['width']) && !in_array($section['width'], $widths))
				array_push($widths, $section['width']);
		}
	}

	return $widths;
}


function getUserPartForHeader() {
    global $i18n;
    if (!$this->id) return null;

    $user_part = htmlspecialchars($this->name);
    $user_part .= ' - '.htmlspecialchars($this->role_name);
    if ($this->behalf_id) {
      $user_part .= ' '.$i18n->get('label.on_behalf').' '.htmlspecialchars($this->behalf_name).'';
    }
    if ($this->behalf_group_id) {
      $user_part .= ',  '.htmlspecialchars($this->behalf_group_name).'';
    } else {
      if ($this->group_name) // Note: we did not require group names in the past.
        $user_part .= ', '.$this->group_name;
    }
    return $user_part;
  }


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


    function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {

        if ($is_revisioned) {
            $object->revision_id++;
            //if ($table=="text") eDebug($object);
            $res = $this->insertObject($object, $table);
            //if ($table=="text") eDebug($object,true);
            $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);
            return $res;
        }
        $sql = "UPDATE " . $this->prefix . "$table SET ";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            //if($is_revisioned && $var=='revision_id') $val++;
            if ($var{0} != '_') {
                if (is_array($val) || is_object($val)) {
                    $val = serialize($val);
                    $sql .= "`$var`='".$val."',";
                } else {
                    $sql .= "`$var`='" . $this->escapeString($val) . "',";
                }
            }
        }
        $sql = substr($sql, 0, -1) . " WHERE ";
        if ($where != null)
            $sql .= $this->injectProof($where);
        else
            $sql .= "`" . $identifier . "`=" . $object->$identifier;
        //if ($table == 'text') eDebug($sql,true);
        $res = (@mysqli_query($this->connection, $sql) != false);
        return $res;
    }


$contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('zones.php', 'page=' . $_GET['page']), null, null, 'btn-light')];


    public static function getSName($zdb, $id, $wid = false, $wnick = false)
    {
        try {
            $select = $zdb->select(self::TABLE);
            $select->where(self::PK . ' = ' . $id);

            $results = $zdb->execute($select);
            $row = $results->current();
            return self::getNameWithCase(
                $row->nom_adh,
                $row->prenom_adh,
                false,
                ($wid === true ? $row->id_adh : false),
                ($wnick === true ? $row->pseudo_adh : false)
            );
        } catch (Throwable $e) {
            Analog::log(
                'Cannot get formatted name for member form id `' . $id . '` | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


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


    public function actionEditDropdown() {
        $model = new Dropdowns;

        if (isset($_POST['Dropdowns'])) {
            $model = Dropdowns::model()->findByPk(
                    $_POST['Dropdowns']['id']);
            if ($model->id == Actions::COLORS_DROPDOWN_ID) {
                if (AuxLib::issetIsArray($_POST['Dropdowns']['values']) &&
                        AuxLib::issetIsArray($_POST['Dropdowns']['labels']) &&
                        count($_POST['Dropdowns']['values']) ===
                        count($_POST['Dropdowns']['labels'])) {

                    if (AuxLib::issetIsArray($_POST['Admin']) &&
                            isset($_POST['Admin']['enableColorDropdownLegend'])) {

                        Yii::app()->settings->enableColorDropdownLegend =
                            $_POST['Admin']['enableColorDropdownLegend'];
                        Yii::app()->settings->save();
                    }

                    $options = array_combine(
                            $_POST['Dropdowns']['values'], $_POST['Dropdowns']['labels']);
                    $temp = array();
                    foreach ($options as $value => $label) {
                        if ($value != "")
                            $temp[$value] = $label;
                    }
                    $model->options = json_encode($temp);
                    $model->save();
                }
            } else {
                $model->attributes = $_POST['Dropdowns'];
                $temp = array();
                if (is_array($model->options) && count($model->options) > 0) {
                    foreach ($model->options as $option) {
                        if ($option != "")
                            $temp[$option] = $option;
                    }
                    $model->options = json_encode($temp);
                    if ($model->save()) {

                    }
                }
            }
        }
        $this->redirect(
                'manageDropDowns'
        );
    }


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

        if ($this->swimlaneModel->disable($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 showall() {
        expHistory::set('viewable', $this->params);
        $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
        if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {
            $limit = '0';
        }
        $order = isset($this->config['order']) ? $this->config['order'] : "rank";
        $page = new expPaginator(array(
            'model'=>'photo',
            'where'=>$this->aggregateWhereClause(),
            'limit'=>$limit,
            'order'=>$order,
            'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],
            'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),
            'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),
            'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title'
            ),
        ));

        assign_to_template(array(
            'page'=>$page,
            'params'=>$this->params,
        ));
    }


    public function upload() {
        if (!AuthUser::hasPermission('file_manager_upload')) {
            Flash::set('error', __('You do not have sufficient permissions to upload a file.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $mask = Plugin::getSetting('umask', 'file_manager');
        umask(octdec($mask));

        $data = $_POST['upload'];
        $path = str_replace('..', '', $data['path']);
        $overwrite = isset($data['overwrite']) ? true : false;

        // Clean filenames
        $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);
        $filename = preg_replace('/[^a-z0-9_\-\.]/i', '', $filename);

        if (isset($_FILES)) {
            $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);

            if ($file === false)
                Flash::set('error', __('File has not been uploaded!'));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }


    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 download_selected($dir)
{
    $dir = get_abs_dir($dir);
    global $site_name;
    require_once("_include/fun_archive.php");
    $items = qxpage_selected_items();

    // check if user selected any items to download
    switch (count($items))
    {
        case 0:
            show_error($GLOBALS["error_msg"]["miscselitems"]);
        case 1:
            if (is_file($items[0]))
            {
                download_item( $dir, $items[0] );
                break;
            }
            // nobreak, downloading a directory is done
            // with the zip file
        default:
            zip_download( $dir, $items );
    }
}


	protected function _restoreDb($data)
	{

		if (empty($data['Tool']['backup']['tmp_name'])) {
			return false;
		}

		$tmpPath = TMP . 'schemas' . DS;
		$targetPath = $tmpPath . $data['Tool']['backup']['name'];

		if (!move_uploaded_file($data['Tool']['backup']['tmp_name'], $targetPath)) {
			return false;
		}

		/* ZIPファイルを解凍する */
		$Simplezip = new Simplezip();
		if (!$Simplezip->unzip($targetPath, $tmpPath)) {
			return false;
		}
		@unlink($targetPath);

		$result = true;
		$db = ConnectionManager::getDataSource('default');
		$db->begin();
		if (!$this->_loadBackup($tmpPath . 'core' . DS, $data['Tool']['encoding'])) {
			$result = false;
		}
		if (!$this->_loadBackup($tmpPath . 'plugin' . DS, $data['Tool']['encoding'])) {
			$result = false;
		}
		if ($result) {
			$db->commit();
		} else {
			$db->rollback();
		}
		$this->_resetTmpSchemaFolder();
		clearAllCache();

		return $result;
	}


	 protected function curl_get_contents( &$url, $timeout, $redirect_max, $ua, $outfp ){
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_HEADER, false );
		if ($outfp) {
			curl_setopt( $ch, CURLOPT_FILE, $outfp );
		} else {
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
		}
		curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 1 );
		curl_setopt( $ch, CURLOPT_LOW_SPEED_TIME, $timeout );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt( $ch, CURLOPT_MAXREDIRS, $redirect_max);
		curl_setopt( $ch, CURLOPT_USERAGENT, $ua);
		$result = curl_exec( $ch );
		$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
		curl_close( $ch );
		return $outfp? $outfp : $result;
	}


public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
        //echo "1
"; eDebug($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("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\t", " ", $str);
        $str = str_replace(",", "\,", $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);

        if (!$isHTML) {
            $str = str_replace('\"', """, $str);
            $str = str_replace('"', """, $str);
        } else {
            $str = str_replace('"', '""', $str);
        }

        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
        $str = trim(str_replace("�", "™", $str));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


    public static function gZip () {

        #ob_start(ob_gzhandler);
        ob_start();
        ob_implicit_flush(0);

    }


    function edit_section() {
        global $db, $user;

        $parent = new section($this->params['parent']);
        if (empty($parent->id)) $parent->id = 0;
        assign_to_template(array(
            'haveStandalone'  => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),
            'parent'          => $parent,
            'isAdministrator' => $user->isAdmin(),
        ));
    }


	public function setPageTextMatchRegex( array $pageTextMatchRegex = [] ) {
		$this->pageTextMatchRegex = (array)$pageTextMatchRegex;
	}


            $evs = $this->event->find('all', "id=" . $edate->event_id . $featuresql);
            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }
            if (count($events) < 500) {  // magic number to not crash loop?
                $events = array_merge($events, $evs);
            } else {
//                $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');
//                $events = array_merge($events, $evs);
                flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));
                break; // keep from breaking system by too much data
            }
        }


			$cols = explode( '}:', $label );
			if ( count( $cols ) <= 1 ) {
				if ( array_key_exists( $t, $_tableRow ) ) {
					$tableRow[$groupNr] = $_tableRow[$t];
				}
			} else {
				$n     = count( explode( ':', $cols[1] ) );
				$colNr = -1;
				$t--;
				for ( $i = 1; $i <= $n; $i++ ) {
					$colNr++;
					$t++;
					if ( array_key_exists( $t, $_tableRow ) ) {
						$tableRow[$groupNr . '.' . $colNr] = $_tableRow[$t];
					}
				}
			}
		}
		return $tableRow;
	}


    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();
    }


    public function index($id)
    {

        //check permissions
        $template = $this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), false);
        if (!$this->_isSiteAdmin() && !$template) {
            throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to see it.');
        }

        $templateElements = $this->TemplateElement->find('all', array(
            'conditions' => array(
                'template_id' => $id,
            ),
            'contain' => array(
                'TemplateElementAttribute',
                'TemplateElementText',
                'TemplateElementFile'
            ),
            'order' => array('TemplateElement.position ASC')
        ));
        $this->loadModel('Attribute');
        $this->set('validTypeGroups', $this->Attribute->validTypeGroups);
        $this->set('id', $id);
        $this->layout = 'ajaxTemplate';
        $this->set('elements', $templateElements);
        $mayModify = false;
        if ($this->_isSiteAdmin() || $template['Template']['org'] == $this->Auth->user('Organisation')['name']) {
            $mayModify = true;
        }
        $this->set('mayModify', $mayModify);
        $this->render('ajax/ajaxIndex');
    }


    public function manage() {
        expHistory::set('viewable', $this->params);

        $page = new expPaginator(array(
			'model'=>'order_status',
			'where'=>1,
            'limit'=>10,
			'order'=>'rank',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            //'columns'=>array('Name'=>'title')
        ));

		assign_to_template(array(
            'page'=>$page
        ));
    }


    public static function restoreX2AuthManager () {
        if (isset (self::$_oldAuthManagerComponent)) {
            Yii::app()->setComponent ('authManager', self::$_oldAuthManagerComponent);
        } else {
            throw new CException ('X2AuthManager component could not be restored');
        }
    }


   static function testLDAPConnection($auths_id, $replicate_id = -1) {

      $config_ldap = new self();
      $res         = $config_ldap->getFromDB($auths_id);

      // we prevent some delay...
      if (!$res) {
         return false;
      }

      //Test connection to a replicate
      if ($replicate_id != -1) {
         $replicate = new AuthLdapReplicate();
         $replicate->getFromDB($replicate_id);
         $host = $replicate->fields["host"];
         $port = $replicate->fields["port"];

      } else {
         //Test connection to a master ldap server
         $host = $config_ldap->fields['host'];
         $port = $config_ldap->fields['port'];
      }
      $ds = self::connectToServer($host, $port, $config_ldap->fields['rootdn'],
                                  Toolbox::decrypt($config_ldap->fields['rootdn_passwd'], GLPIKEY),
                                  $config_ldap->fields['use_tls'],
                                  $config_ldap->fields['deref_option']);
      if ($ds) {
         return true;
      }
      return false;
   }


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


	public static function filesBySearch($text, $wid=NULL, $orderby="name ASC")
	{
		global $DB;
		global $website;

		if(empty($wid))
			$wid = $website->id;

		$DB->query('  SELECT * FROM nv_files
					   WHERE name LIKE '.protect('%'.$text.'%').'
					     AND website = '.$wid.'
					ORDER BY '.$orderby);

		return $DB->result();
	}


    function selectArraysBySql($sql) {
        $res = @mysqli_query($this->connection, $this->injectProof($sql));
        if ($res == null)
            return array();
        $arrays = array();
        for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)
            $arrays[] = mysqli_fetch_assoc($res);
        return $arrays;
    }


    public function backup($type='json')
    {
        global $DB;
        global $website;

        $out = array();

        $DB->query('
            SELECT * FROM nv_notes
            WHERE website = '.protect($website->id),
            'object'
        );
        $out = $DB->result();

        if($type='json')
            $out = json_encode($out);

        return $out;
    }


	public function update($key, $qty) {
		if ((int)$qty && ((int)$qty > 0)) {
			$this->session->data['cart'][$key] = (int)$qty;
		} else {
			$this->remove($key);
		}

		$this->data = array();
	}


    public function testNotRemoveAuthorizationHeaderOnRedirect()
    {
        $mock = new MockHandler([
            new Response(302, ['Location' => 'http://example.com/2']),
            static function (RequestInterface $request) {
                self::assertTrue($request->hasHeader('Authorization'));
                return new Response(200);
            }
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);
    }