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


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

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

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


    public function testDoesNotTouchClosureListeners()
    {
        $this->getServer()->flush();
        $this->getServer()->enqueue(array(
            "HTTP/1.1 200 OK\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" .
            "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Content-Length: 2\r\n\r\nhi",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
            "HTTP/1.0 304 Not Modified\r\n" .
            "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" .
            "Age: 6302\r\n\r\n",
        ));
        $client = new Client($this->getServer()->getUrl());
        $client->addSubscriber(new CachePlugin());
        $client->getEventDispatcher()->addListener('command.after_send', function(){});
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
        $this->assertEquals(200, $client->get()->send()->getStatusCode());
    }


    function selectObjectBySql($sql) {
        //$logFile = "C:\\xampp\\htdocs\\supserg\\tmp\\queryLog.txt";
        //$lfh = fopen($logFile, 'a');
        //fwrite($lfh, $sql . "\n");
        //fclose($lfh);
        $res = @mysqli_query($this->connection, $this->injectProof($sql));
        if ($res == null)
            return null;
        return mysqli_fetch_object($res);
    }


	public function register()
	{
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

		// Get the application
		$app = JFactory::getApplication();

		// Get the form data.
		$data = $this->input->post->get('user', array(), 'array');

		// Get the model and validate the data.
		$model  = $this->getModel('Registration', 'UsersModel');

		$form = $model->getForm();

		if (!$form)
		{
			JError::raiseError(500, $model->getError());

			return false;
		}

		$return = $model->validate($form, $data);

		// Check for errors.
		if ($return === false)
		{
			// Get the validation messages.
			$errors = $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if ($errors[$i] instanceof Exception)
				{
					$app->enqueueMessage($errors[$i]->getMessage(), 'notice');

					continue;
				}

				$app->enqueueMessage($errors[$i], 'notice');
			}

			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$this->setRedirect('index.php?option=com_users&view=registration');

			return false;
		}

		// Finish the registration.
		$return = $model->register($data);

		// Check for errors.
		if ($return === false)
		{
			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());
			$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');

			return false;
		}

		// Flush the data from the session.
		$app->setUserState('users.registration.form.data', null);

		return true;
	}


        foreach($course_RET as $period_date)
        {
            // $period_days_append_sql .="(sp.start_time<='$period_date[END_TIME]' AND '$period_date[START_TIME]'<=sp.end_time AND IF(course_period_date IS NULL, course_period_date='$period_date[COURSE_PERIOD_DATE]',DAYS LIKE '%$period_date[DAYS]%')) OR ";
              $period_days_append_sql .="(sp.start_time<='$period_date[END_TIME]' AND '$period_date[START_TIME]'<=sp.end_time AND (cpv.course_period_date IS NULL OR cpv.course_period_date='$period_date[COURSE_PERIOD_DATE]') AND cpv.DAYS LIKE '%$period_date[DAYS]%') OR ";

        }


    public function toolbar() {
//        global $user;

        $menu = array();
		$dirs = array(
			BASE.'framework/modules/administration/menus',
			BASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'
		);

		foreach ($dirs as $dir) {
		    if (is_readable($dir)) {
			    $dh = opendir($dir);
			    while (($file = readdir($dh)) !== false) {
				    if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {
					    $menu[substr($file,0,-4)] = include($dir.'/'.$file);
                        if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);
				    }
			    }
		    }
		}

        // sort the top level menus alphabetically by filename
		ksort($menu);
		$sorted = array();
		foreach($menu as $m) $sorted[] = $m;

        // slingbar position
        if (isset($_COOKIE['slingbar-top'])){
            $top = $_COOKIE['slingbar-top'];
        } else {
            $top = SLINGBAR_TOP;
        }

		assign_to_template(array(
            'menu'=>(bs3()) ? $sorted : json_encode($sorted),
            "top"=>$top
        ));
    }


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


		form_end_row();
		$i++;
	}

	html_end_box(false);

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

}


                }elseif($k == "error"){

                    self::error($v);

                }elseif(!in_array($k, $arr) && $k != 'paging'){


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

        if (! $this->userSession->isAdmin()) {
            if (isset($values['role'])) {
                unset($values['role']);
            }
        }

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

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

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


    public static function handler($vars) {
            self::$vars();
    }


            return new Response($emailLog->getHtmlLog());
        } elseif ($request->get('type') == 'params') {


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


	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 save(){
        $cat_name = I("cat_name");
        $s_number = I("s_number/d") ? I("s_number/d") : 99 ;
        $cat_id = I("cat_id/d")? I("cat_id/d") : 0;
        $parent_cat_id = I("parent_cat_id/d")? I("parent_cat_id/d") : 0;
        $item_id =  I("item_id/d");

        $login_user = $this->checkLogin();
        if (!$this->checkItemPermn($login_user['uid'] , $item_id)) {
            $this->sendError(10103);
            return;
        }
        //禁止空目录的生成
        if (!$cat_name) {
            return;
        }

        if ($parent_cat_id &&  $parent_cat_id == $cat_id) {
            $this->sendError(10101,"上级目录不能选择自身");
            return;
        }

        $data['cat_name'] = $cat_name ;
        $data['s_number'] = $s_number ;
        $data['item_id'] = $item_id ;
        $data['parent_cat_id'] = $parent_cat_id ;
        if ($parent_cat_id > 0 ) {
            $row = D("Catalog")->where(" cat_id = '$parent_cat_id' ")->find() ;
            $data['level'] = $row['level'] +1 ;
        }else{
            $data['level'] = 2;
        }

        if ($cat_id > 0 ) {

            //如果一个目录已经是别的目录的父目录，那么它将无法再转为level4目录
            if (D("Catalog")->where(" parent_cat_id = '$cat_id' ")->find() && $data['level'] == 4 ) {
                $this->sendError(10101,"该目录含有子目录，不允许转为底层目录。");
                return;
            }

            $ret = D("Catalog")->where(" cat_id = '$cat_id' ")->save($data);
            $return = D("Catalog")->where(" cat_id = '$cat_id' ")->find();

        }else{
            $data['addtime'] = time();
            $cat_id = D("Catalog")->add($data);
            $return = D("Catalog")->where(" cat_id = '$cat_id' ")->find();

        }
        if (!$return) {
            $return['error_code'] = 10103 ;
            $return['error_message'] = 'request  fail' ;
        }
        $this->sendResult($return);

    }


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

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


    public function testRemoveAuthorizationHeaderOnRedirect()
    {
        $mock = new MockHandler([
            new Response(302, ['Location' => 'http://test.com']),
            static function (RequestInterface $request) {
                self::assertFalse($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']]);
    }


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

        $out = array();

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

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

        return $out;
    }


    public function take($value)
    {
        return $this->limit($value);
    }


    public function validate() {
        global $db;
        // check for an sef url field.  If it exists make sure it's valid and not a duplicate
        //this needs to check for SEF URLS being turned on also: TODO

        if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {
            if (empty($this->sef_url)) $this->makeSefUrl();
            if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();
            if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url']         = array();
        }

        // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router
        // mapped view and src hasn't been passed in via link to the form
        if (isset($this->id) && empty($this->location_data)) {
            $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);
            if (!empty($loc)) $this->location_data = $loc;
        }

        // run the validation as defined in the models
        if (!isset($this->validates)) return true;
        $messages = array();
        $post     = empty($_POST) ? array() : expString::sanitize($_POST);
        foreach ($this->validates as $validation=> $field) {
            foreach ($field as $key=> $value) {
                $fieldname = is_numeric($key) ? $value : $key;
                $opts      = is_numeric($key) ? array() : $value;
                $ret       = expValidator::$validation($fieldname, $this, $opts);
                if (!is_bool($ret)) {
                    $messages[] = $ret;
                    expValidator::setErrorField($fieldname);
                    unset($post[$fieldname]);
                }
            }
        }

        if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);
    }


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


    public static function decode($jwt, $key = null, $verify = true)
    {
        $tks = explode('.', $jwt);

        if (count($tks) != 3) {
            throw new Exception('Wrong number of segments');
        }

        list($headb64, $payloadb64, $cryptob64) = $tks;

        if (null === ($header = json_decode(JWT::urlsafeB64Decode($headb64)))) {
            throw new Exception('Invalid segment encoding');
        }

        if (null === $payload = json_decode(JWT::urlsafeB64Decode($payloadb64))) {
            throw new Exception('Invalid segment encoding');
        }

        $sig = JWT::urlsafeB64Decode($cryptob64);

        if ($verify) {
            if (empty($header->alg)) {
                throw new DomainException('Empty algorithm');
            }

            if (!JWT::verifySignature($sig, "$headb64.$payloadb64", $key, $header->alg)) {
                throw new UnexpectedValueException('Signature verification failed');
            }
        }

        return $payload;
    }


    function getFontSize()
    {
        $fs = $GLOBALS['PMA_Config']->get('fontsize');
        if (!is_null($fs)) {
            return $fs;
        }
        if (isset($_COOKIE['pma_fontsize'])) {
            return $_COOKIE['pma_fontsize'];
        }
        return '82%';
    }


    public function testInvalidRequests($requestRange)
    {
        $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag();

        // prepare a request for a range of the testing file
        $request = Request::create('/');
        $request->headers->set('Range', $requestRange);

        $response = clone $response;
        $response->prepare($request);
        $response->sendContent();

        $this->assertEquals(416, $response->getStatusCode());
        #$this->assertEquals('', $response->headers->get('Content-Range'));
    }


    public function __construct(AuthManager $auth, Repository $config)
    {
        $this->lockoutTime = $config->get('auth.lockout.time');
        $this->maxLoginAttempts = $config->get('auth.lockout.attempts');

        $this->auth = $auth;
        $this->config = $config;
    }


    function reset_stats() {
//        global $db;

        // reset the counters
//        $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');
        banner::resetImpressions();
//        $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');
        banner::resetClicks();

        // let the user know we did stuff.
        flash('message', gt("Banner statistics reset."));
        expHistory::back();
    }


    public static function meta($cont_title='', $cont_desc='', $pre =''){
        global $data;
        //print_r($data);
        //if(empty($data['posts'][0]->title)){

        if(is_array($data) && isset($data['posts'][0]->title)){

            $sitenamelength = strlen(Options::get('sitename'));
            $limit = 70-$sitenamelength-6;
            $cont_title = substr(Typo::Xclean(Typo::strip($data['posts'][0]->title)),0,$limit);
            $titlelength = strlen($data['posts'][0]->title);
            if($titlelength > $limit+3) { $dotted = "...";} else {$dotted = "";}
            $cont_title = "{$pre} {$cont_title}{$dotted} - ";
        }else{
            $cont_title = "";
        }
        if(is_array($data)  && isset($data['posts'][0]->content)){
            $desc = Typo::strip($data['posts'][0]->content);
        }else{
            $desc = "";
        }

        $meta = "
    <!--// Start Meta: Generated Automaticaly by GeniXCMS -->
    <!-- SEO: Title stripped 70chars for SEO Purpose -->
    <title>{$cont_title}".Options::get('sitename')."</title>
    <meta name=\"Keyword\" content=\"".Options::get('sitekeywords')."\">
    <!-- SEO: Description stripped 150chars for SEO Purpose -->
    <meta name=\"Description\" content=\"".self::desc($desc)."\">
    <meta name=\"Author\" content=\"Puguh Wijayanto | MetalGenix IT Solutions - www.metalgenix.com\">
    <meta name=\"Generator\" content=\"GeniXCMS\">
    <meta name=\"robots\" content=\"".Options::get('robots')."\">
    <meta name=\"revisit-after\" content=\" days\">
    <link rel=\"shortcut icon\" href=\"".Options::get('siteicon')."\" />
        ";

        $meta .= "
    <!-- Generated Automaticaly by GeniXCMS :End Meta //-->";
        echo $meta;
    }


	public function formatItem( Article $article, $pageText = null ) {
		$item = $article->mTitle;

		if ( $pageText !== null ) {
			//Include parsed/processed wiki markup content after each item before the closing tag.
			$item .= $pageText;
		}

		$item = $this->getItemStart() . $item . $this->itemEnd;

		$item = $this->replaceTagParameters( $item, $article );

		return $item;
	}


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

		// grab the error-type from the parameters
		$errorType = $this->getParameter('type');

		// set correct headers
		switch($errorType)
		{
			case 'module-not-allowed':
			case 'action-not-allowed':
				SpoonHTTP::setHeadersByCode(403);
				break;

			case 'not-found':
				SpoonHTTP::setHeadersByCode(404);
				break;
		}

		// querystring provided?
		if($this->getParameter('querystring') !== null)
		{
			// split into file and parameters
			$chunks = explode('?', $this->getParameter('querystring'));

			// get extension
			$extension = SpoonFile::getExtension($chunks[0]);

			// if the file has an extension it is a non-existing-file
			if($extension != '' && $extension != $chunks[0])
			{
				// set correct headers
				SpoonHTTP::setHeadersByCode(404);

				// give a nice error, so we can detect which file is missing
				echo 'Requested file (' . implode('?', $chunks) . ') not found.';

				// stop script execution
				exit;
			}
		}

		// assign the correct message into the template
		$this->tpl->assign('message', BL::err(SpoonFilter::toCamelCase($errorType, '-')));
	}


    public static function returnChildrenAsJSON() {
        global $db;

        //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));
        $id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        $nav        = $db->selectObjects('section', 'parent=' . $id, 'rank');
        //FIXME $manage_all is moot w/ cascading perms now?
        $manage_all = false;
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {
            $manage_all = true;
        }
        //FIXME recode to use foreach $key=>$value
        $navcount = count($nav);
        for ($i = 0; $i < $navcount; $i++) {
            if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {
                $nav[$i]->manage = 1;
                $view = true;
            } else {
                $nav[$i]->manage = 0;
                $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));
            }
            $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);
            if (!$view) unset($nav[$i]);
        }
        $nav= array_values($nav);
//        $nav[$navcount - 1]->last = true;
        if (count($nav)) $nav[count($nav) - 1]->last = true;
//        echo expJavascript::ajaxReply(201, '', $nav);
        $ar = new expAjaxReply(201, '', $nav);
        $ar->send();
    }


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

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

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


    public function approve_submit() {
        global $history;

        if (empty($this->params['id'])) {
            flash('error', gt('No ID supplied for comment to approve'));
            $lastUrl = expHistory::getLast('editable');
        }

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

        $simplenote = new expSimpleNote($this->params['id']);
        //FIXME here is where we might sanitize the note before approving it
        $simplenote->body = $this->params['body'];
        $simplenote->approved = $this->params['approved'];
        $simplenote->save();

        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    function manage() {
        expHistory::set('viewable', $this->params);
        //         $category = new storeCategory();
        //         $categories = $category->getFullTree();
        //
        //         // foreach($categories as $i=>$val){
        //         //  if (!empty($this->values) && in_array($val->id,$this->values)) {
        //         //      $this->tags[$i]->value = true;
        //         //  } else {
        //         //      $this->tags[$i]->value = false;
        //         //  }
        //         //  $this->tags[$i]->draggable = $this->draggable;
        //         //  $this->tags[$i]->checkable = $this->checkable;
        //         // }
        //
        // $obj = json_encode($categories);
    }


	private function _hiddencategories( $option ) {
		//@TODO: Unfinished functionality!  Never implemented by original author.
	}


    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }


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


        $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 static function makeConfig ($file) {
        $config = "<?php if(!defined('GX_LIB')) die(\"Direct Access Not Allowed!\");
/**
* GeniXCMS - Content Management System
*
* PHP Based Content Management System and Framework
*
* @package GeniXCMS
* @since 0.0.1 build date 20140925
* @version 0.0.1
* @link https://github.com/semplon/GeniXCMS
* @author Puguh Wijayanto (www.metalgenix.com)
* @copyright 2014-2015 Puguh Wijayanto
* @license http://www.opensource.org/licenses/mit-license.php MIT
*
*/

// DB CONFIG
define('DB_HOST', '".Session::val('dbhost')."');
define('DB_NAME', '".Session::val('dbname')."');
define('DB_PASS', '".Session::val('dbpass')."');
define('DB_USER', '".Session::val('dbuser')."');
define('DB_DRIVER', 'mysqli');

define('THEME', 'default');
define('GX_LANG', 'english');
define('SMART_URL', false); //set 'true' if you want use SMART URL (SEO Friendly URL)
define('GX_URL_PREFIX', '.html');
define('SECURITY', '".Typo::getToken(200)."'); // for security purpose, will be used for creating password

        ";
        try{
            $f = fopen($file, "w");
            $c = fwrite($f, $config);
            fclose($f);
        }catch (Exception $e) {
            echo $e->getMessage();
        }

        return $config;
    }


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

    switch ($DatabaseType) {
        case 'mysqli':
            $connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);
            break;
    }

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


	public function &storeFromDefaultForm($created_success_msg, $modified_success_msg, $redirect_page=false, $debug=false, $x_param = false) {
		$objectid = ( isset($_POST[$this->handler->keyName]) )
				? (int) $_POST[$this->handler->keyName]
				: 0;
		if ($debug) {
			if ($x_param) {
				$icmsObj = $this->handler->getD($objectid, true,  $x_param);
			} else {
				$icmsObj = $this->handler->getD($objectid);
			}

		} else {
			if ($x_param) {
				$icmsObj = $this->handler->get($objectid, true, false, false, $x_param);
			} else {
				$icmsObj = $this->handler->get($objectid);
			}
		}

		/**
		 * @todo multilanguage persistable handler is not fully implemented yet
		 */

		// if handler is the Multilanguage handler, we will need to treat this for multilanguage
		if (is_subclass_of($this->handler, 'icmspersistablemlobjecthandler')) {

			if ($icmsObj->isNew()) {
				// This is a new object. We need to store the meta data and then the language data
				// First, we will get rid of the multilanguage data to only store the meta data
				$icmsObj->stripMultilanguageFields();
				$newObject =& $this->doStoreFromDefaultForm($icmsObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
				/**
				 * @todo we need to trap potential errors here
				 */

				// ok, the meta daa is stored. Let's recreate the object and then
				// get rid of anything not multilanguage
				unset($icmsObj);
				$icmsObj = $this->handler->get($objectid);
				$icmsObj->stripNonMultilanguageFields();

				$icmsObj->setVar($this->handler->keyName, $newObject->getVar($this->handler->keyName));
				$this->handler->changeTableNameForML();
				$ret =& $this->doStoreFromDefaultForm($icmsObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);

				return $ret;
			}
		} else {
			return $this->doStoreFromDefaultForm($icmsObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
		}
	}


    protected function tearDown()
    {
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->originalTrustedHeaderName);
    }


        function scan_page($parent_id) {
            global $db;

            $sections = $db->selectObjects('section','parent=' . $parent_id);
            $ret = '';
            foreach ($sections as $page) {
                $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));
                $ret .= scan_container($cLoc, $page->id);
                $ret .= scan_page($page->id);
            }
            return $ret;
        }


    public static function hasChildren($i) {
        global $sections;

        if (($i + 1) >= count($sections)) return false;
        return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;
    }


function current_user_get_bug_filter( $p_project_id = null ) {
	$f_filter_string = gpc_get_string( 'filter', '' );
	$t_filter = '';

	if( !is_blank( $f_filter_string ) ) {
		if( is_numeric( $f_filter_string ) ) {
			$t_token = token_get_value( TOKEN_FILTER );
			if( null != $t_token ) {
				$t_filter = json_decode( $t_token, true );
			}
		} else {
			$t_filter = json_decode( $f_filter_string, true );
		}
		$t_filter = filter_ensure_valid_filter( $t_filter );
	} else if( !filter_is_cookie_valid() ) {
		$t_filter = filter_get_default();
	} else {
		$t_user_id = auth_get_current_user_id();
		$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );
	}

	return $t_filter;
}


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


                       AND lang = '.protect($lang).'
                       AND subtype IN ('.implode(",", array_map(function($k){ return protect($k);}, $subtypes)).')'
                );


    public static function error ($vars="") {
        if( isset($vars) && $vars != "" ) {
            include(GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php');
        }else{
            include(GX_PATH.'/inc/lib/Control/Error/404.control.php');
        }
    }


    public function save_change_password() {
        global $user;

        $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;

        if (!$user->isAdmin() && !$isuser) {
            flash('error', gt('You do not have permissions to change this users password.'));
            expHistory::back();
        }

        if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {
            flash('error', gt('The current password you entered is not correct.'));
            expHistory::returnTo('editable');
        }
        //eDebug($user);
        $u = new user($this->params['uid']);

        $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);
        //eDebug($u, true);
        if (is_string($ret)) {
            flash('error', $ret);
            expHistory::returnTo('editable');
        } else {
            $params = array();
            $params['is_admin'] = !empty($u->is_admin);
            $params['is_acting_admin'] = !empty($u->is_acting_admin);
            $u->update($params);
        }

        if (!$isuser) {
            flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));
        } else {
            $user->password = $u->password;
            flash('message', gt('Your password has been changed.'));
        }
        expHistory::back();
    }


$contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_DELETE, 'fas fa-trash', null, 'primary', null, 'btn-danger xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('testimonials.php', 'page=' . $_GET['page'] . '&tID=' . $tInfo->testimonials_id), null, null, 'btn-light')];


public function column_title( $post ) {
		list( $mime ) = explode( '/', $post->post_mime_type );

		$title = _draft_or_post_title();
		$thumb = wp_get_attachment_image( $post->ID, array( 60, 60 ), true, array( 'alt' => '' ) );
		$link_start = $link_end = '';

		if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {
			$link_start = sprintf(
				'',
				get_edit_post_link( $post->ID ),
				/* translators: %s: attachment title */
				esc_attr( sprintf( __( '“%s” (Edit)' ), $title ) )
			);
			$link_end = '';
		}

		$class = $thumb ? ' class="has-media-icon"' : '';
		?>
		<strong<?php echo $class; ?>>
			<?php
			echo $link_start;
			if ( $thumb ) : ?>
				<span class="media-icon <?php echo sanitize_html_class( $mime . '-icon' ); ?>"><?php echo $thumb; ?>
			<?php endif;
			echo $title . $link_end;
			_media_states( $post );
			?>

			<?php _e( 'File name:' ); ?>
			<?php
			$file = get_attached_file( $post->ID );
			echo wp_basename( $file );
			?>

		<?php
	}


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


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

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

        return $subtask;
    }


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


	function edit() {
	    if (empty($this->params['content_id'])) {
	        flash('message',gt('An error occurred: No content id set.'));
            expHistory::back();
	    }
        /* The global constants can be overridden 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'];

	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $comment = new expComment($id);
        //FIXME here is where we might sanitize the comment before displaying/editing it
		assign_to_template(array(
		    'content_id'=>$this->params['content_id'],
            'content_type'=>$this->params['content_type'],
		    'comment'=>$comment
		));
	}


    private function mailPassthru($to, $subject, $body, $header, $params)
    {
        //Check overloading of mail function to avoid double-encoding
        if (ini_get('mbstring.func_overload') & 1) {
            $subject = $this->secureHeader($subject);
        } else {
            $subject = $this->encodeHeader($this->secureHeader($subject));
        }
        if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
            $result = @mail($to, $subject, $body, $header);
        } else {
            $result = @mail($to, $subject, $body, $header, $params);
        }
        return $result;
    }


    function ac_sigleme($str, $name, $id) {
        global $cms_db, $sess;

        $sess->gc( true );
	    if( $id >= 1 && $this->session_enabled ) {
            $this->db->query(sprintf("delete from %s where name = '%s' and sid != '%s' and user_id = '%s'",
                $cms_db[sessions],
                addslashes($name),
                $str,
                $id));
        }
    }


    public static function url() {
        return Site::$url.'/inc/lib/Vendor';
    }


    public function validateReference()
    {
        $docElem = $this->sigNode->ownerDocument->documentElement;
        if (! $docElem->isSameNode($this->sigNode)) {
            if ($this->sigNode->parentNode != null) {
                $this->sigNode->parentNode->removeChild($this->sigNode);
            }
        }
        $xpath = $this->getXPathObj();
        $query = "./secdsig:SignedInfo/secdsig:Reference";
        $nodeset = $xpath->query($query, $this->sigNode);
        if ($nodeset->length == 0) {
            throw new Exception("Reference nodes not found");
        }

        /* Initialize/reset the list of validated nodes. */
        $this->validatedNodes = array();

        foreach ($nodeset AS $refNode) {
            if (! $this->processRefNode($refNode)) {
                /* Clear the list of validated nodes. */
                $this->validatedNodes = null;
                throw new Exception("Reference validation failed");
            }
        }
        return true;
    }


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


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

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


function PMA_Process_formset(FormDisplay $form_display)
{
    if (filter_input(INPUT_GET, 'mode') == 'revert') {
        // revert erroneous fields to their default values
        $form_display->fixErrors();
        PMA_generateHeader303();
    }

    if (!$form_display->process(false)) {
        // handle form view and failed POST
        $form_display->display(true, true);
        return;
    }

    // check for form errors
    if (!$form_display->hasErrors()) {
        PMA_generateHeader303();
        return;
    }

    // form has errors, show warning
    $separator = PMA_URL_getArgSeparator('html');
    $page = filter_input(INPUT_GET, 'page');
    $formset = filter_input(INPUT_GET, 'formset');
    $formset = $formset ? "{$separator}formset=$formset" : '';
    $formId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($formId === null && $page == 'servers') {
        // we've just added a new server, get its id
        $formId = $form_display->getConfigFile()->getServerCount();
    }
    $formId = $formId ? "{$separator}id=$formId" : '';
    ?>

<?php echo __('Warning') ?>

        <?php echo __('Submitted form contains errors') ?>

        <a href="?page=<?php echo $page . $formset . $formId . $separator ?>mode=revert">
            <?php echo __('Try to revert erroneous fields to their default values')
            ?>

    <?php $form_display->displayErrors() ?>
    <?php echo __('Ignore errors') ?>

    <a class="btn" href="?page=<?php echo $page . $formset . $formId
        . $separator ?>mode=edit"><?php echo __('Show form') ?>
    <?php
}


			$this->_writeCsv($plugin, $tmpDir . $plugin . DS);
		}
		/* site_configsの編集 (email / google_analytics_id / version) */
		$targets = ['email', 'google_analytics_id', 'version'];
		$path = $tmpDir . 'site_configs.csv';
		$fp = fopen($path, 'a+');
		$records = [];
		while(($record = fgetcsvReg($fp, 10240)) !== false) {
			if (in_array($record[1], $targets)) {
				$record[2] = '';
			}
			$records[] = '"' . implode('","', $record) . '"';
		}
		ftruncate($fp, 0);
		fwrite($fp, implode("\n", $records));
		/* ZIPに固めてダウンロード */
		$fileName = 'default';
		$Simplezip = new Simplezip();
		$Simplezip->addFolder($tmpDir);
		$Simplezip->download($fileName);
		emptyFolder($tmpDir);
		exit();
	}


    public function __construct()
    {
        $this->options['alias'] = '';              // alias to replace root dir name
        $this->options['dirMode'] = 0755;            // new dirs mode
        $this->options['fileMode'] = 0644;            // new files mode
        $this->options['quarantine'] = '.quarantine'; // quarantine folder name - required to check archive (must be hidden)
        $this->options['rootCssClass'] = 'elfinder-navbar-root-local';
        $this->options['followSymLinks'] = true;
        $this->options['detectDirIcon'] = '';         // file name that is detected as a folder icon e.g. '.diricon.png'
        $this->options['keepTimestamp'] = array('copy', 'move'); // keep timestamp at inner filesystem allowed 'copy', 'move' and 'upload'
        $this->options['substituteImg'] = true;       // support substitute image with dim command
        $this->options['statCorrector'] = null;       // callable to correct stat data `function(&$stat, $path, $statOwner, $volumeDriveInstance){}`
    }


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


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

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

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


    public static function Zipped () {

        global $HTTP_ACCEPT_ENCODING;

        if( headers_sent() ){

            $encoding = false;

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

            $encoding = 'x-gzip';

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

            $encoding = 'gzip';

        }else{

            $encoding = false;

        }

        if( $encoding ){

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

        }else{

            ob_end_flush();
            exit();

        }
    }


foreach ($fields as $field => $title) {
                if($i==0 && $j==0){
                    echo '
';
                }elseif($i==0 && $j>0){
                    echo '

';
                }
                echo '
<INPUT type=checkbox onclick="addHTML(\'
' . $title . '
\',\'names_div\',false);addHTML(\'<INPUT type=hidden name=fields[' . $field . '] value=Y>\',\'fields_div\',false);addHTML(\'\',\'names_div_none\',true);this.disabled=true">' . $title . '
';

                /*if ($i % 2 == 0)
                    echo '

';*/
                $i++;
                if($i==2){
                    $i = 0;
                }
                $j++;
            }


		function uninstallPage()
		{
			$id = $this->getId();

			if(empty($_POST['uninstall_confirm']))
			{

				$plug_vars = e107::getPlug()->load($id)->getMeta();

				$name = e107::getPlug()->getName();
				$this->addTitle(EPL_ADLAN_63);
				$this->addTitle($name);

				return $this->pluginConfirmUninstall($plug_vars);
			}

			$post = e107::getParser()->filter($_POST);

		//	$id = e107::getPlugin

			$text = e107::getPlugin()->uninstall($id, $post);

			e107::getMessage()->add($text, E_MESSAGE_SUCCESS);
			$log = e107::getPlugin()->getLog();
			e107::getDebug()->log($log);

			$this->redirectAction('list');
		}


	private static function listFilesInDirectory($dir, $omitSymlinks, $prefix = '')
	{
		if (!is_dir($dir)) {
			return false;
		}
		$excludes = array(".","..");
		$result = array();
		$files = self::localScandir($dir);
		if(!$files) {
			return array();
		}
		foreach($files as $file) {
			if(!in_array($file, $excludes)) {
				$path = $dir.DIRECTORY_SEPARATOR.$file;
				if(is_link($path)) {
					if($omitSymlinks) {
						continue;
					} else {
						$result[] = $prefix.$file;
					}
				} else if(is_dir($path)) {
					$result[] = $prefix.$file.DIRECTORY_SEPARATOR;
					$subs = elFinderVolumeFTP::listFilesInDirectory($path, $omitSymlinks, $prefix.$file.DIRECTORY_SEPARATOR);
					if($subs) {
						$result = array_merge($result, $subs);
					}

				} else {
					$result[] = $prefix.$file;
				}
			}
		}
		return $result;
	}


            call_user_func($listener, $event, $eventName, $this);
            if ($event->isPropagationStopped()) {
                break;
            }
        }
    }


	function _real_escape( $string ) {
		if ( $this->dbh ) {
			if ( $this->use_mysqli ) {
				return mysqli_real_escape_string( $this->dbh, $string );
			} else {
				return mysql_real_escape_string( $string, $this->dbh );
			}
		}

		$class = get_class( $this );
		if ( function_exists( '__' ) ) {
			/* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
			_doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
		} else {
			_doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
		}
		return addslashes( $string );
	}


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


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

		//This will make sure that only the country or region that given a rate value will be saved in the db
		$upcharge = array();
		foreach($this->params['upcharge'] as $key => $item) {
			if(!empty($item)) {
				$upcharge[$key] = $item;
			}
		}
		$this->config['upcharge'] = $upcharge;

        $config->update(array('config'=>$this->config));
        flash('message', gt('Configuration updated'));
        expHistory::back();
    }


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


	public function testPages () {
        $this->visitPages ( $this->allPages );
	}


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

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


	public function handleObjectDeletion($confirm_msg = false, $op='del', $userSide=false) {
		global $impresscms;

		$objectid = (isset($_REQUEST[$this->handler->keyName])) ? (int) $_REQUEST[$this->handler->keyName] : 0;
		$icmsObj = $this->handler->get($objectid);

		if ($icmsObj->isNew()) {
			redirect_header("javascript:history.go(-1)", 3, _CO_ICMS_NOT_SELECTED);
			exit();
		}

		$confirm = ( isset($_POST['confirm']) ) ? $_POST['confirm'] : 0;
		if ($confirm) {
			if (!$this->handler->delete($icmsObj)) {
				redirect_header($_POST['redirect_page'], 3, _CO_ICMS_DELETE_ERROR . $icmsObj->getHtmlErrors());
				exit;
			}

			redirect_header($_POST['redirect_page'], 3, _CO_ICMS_DELETE_SUCCESS);
			exit();
		} else {
			// no confirm: show deletion condition

			icms_cp_header();

			if (!$confirm_msg) {
				$confirm_msg = _CO_ICMS_DELETE_CONFIRM;
			}

			$hiddens = array(
						'op' => $op,
						$this->handler->keyName => $icmsObj->getVar($this->handler->keyName),
						'confirm' => 1,
						'redirect_page' => $impresscms->urls['previouspage']
			);
			if ($this->handler->_moduleName == 'system') {
				$hiddens['fct'] = isset($_GET['fct']) ? $_GET['fct'] : false;
			}
			icms_core_Message::confirm($hiddens, xoops_getenv('SCRIPT_NAME'), sprintf($confirm_msg , $icmsObj->getVar($this->handler->identifierName)), _CO_ICMS_DELETE);

			icms_cp_footer();

		}
		exit();
	}


			foreach($paths as $path)
			{
				// Convert wild-cards to RegEx
				$path = str_replace(array(':any', '*'), '.*', str_replace(':num', '[0-9]+', $path));

				// Does the RegEx match?
				if (!empty($_SERVER['HTTP_HOST']) AND preg_match('#^'.$path.'$#', $_SERVER['HTTP_HOST']))
				{
					define('ENVIRONMENT', $env);
					break 2;
				}
			}


    public function beforeSave() {
        if(strpos($this->tag,self::DELIM) !== false) {
            $this->tag = strtr($this->tag,array(self::DELIM => ''));
        }
        return true;
    }


		    $controller = new $ctlname();
		    if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {
//			    $mods[$controller->name()] = $controller->addContentToSearch();
                $mods[$controller->searchName()] = $controller->addContentToSearch();
		    }
	    }

	    uksort($mods,'strnatcasecmp');
	    assign_to_template(array(
            'mods'=>$mods
        ));
    }


	public function setListAttributes( $attributes ) {
		$this->listAttributes = \Sanitizer::fixTagAttributes( $attributes, 'ul' );
	}


    public function routeDeleteProvider()
    {
        return [
            ['/api/articles/',    1, 'articles', 'batchDelete', false, 200],
            ['/api/v1/articles/', 1, 'articles', 'batchDelete', false, 200],
            ['/api/v2/articles/', 2, 'articles', 'batchDelete', false, 200],

            ['/api/articles/5',    1, 'articles', 'delete', 5, 200],
            ['/api/v1/articles/5', 1, 'articles', 'delete', 5, 200],
            ['/api/v2/articles/5', 2, 'articles', 'delete', 5, 200],
        ];
    }


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

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


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

        $this->checkPermission($project, $filter);

        if ($this->customFilterModel->remove($filter['id'])) {
            $this->flash->success(t('Custom filter removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this custom filter.'));
        }

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


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

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


	private function convertTimestamp( $inputDate ) {
		$timestamp = $inputDate;
		switch ( $inputDate ) {
			case 'today':
				$timestamp = date( 'YmdHis' );
				break;
			case 'last hour':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1H' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last day':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1D' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last week':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P7D' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last month':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1M' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last year':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1Y' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
		}

		if ( is_numeric( $timestamp ) ) {
			return $this->DB->addQuotes( $timestamp );
		}
		return 0;
	}


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

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


	protected function _mkdir($path, $name) {
		$path = $this->_joinPath($path, $name);

		if (@mkdir($path)) {
			@chmod($path, $this->options['dirMode']);
			clearstatcache();
			return $path;
		}

		return false;
	}


function createWhereClause($owner, $filter, $search, $daterange, $ok, $warning, $critical, $unknown)
{
	$where_clause = "";

	// owner
	if($owner == "owned"){ $where_clause .= " AND owner != ''"; }
	elseif($owner == "not owned"){ $where_clause .= " AND owner = ''"; }

	// advanced search (with *)
	if($search != ""){
		$like = "";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}

		$where_clause .= " AND $filter LIKE '$like'";
	}

	// daterange
	if($daterange != ""){
		$daterange_parts = explode(" - ", $daterange);
		$start = $daterange_parts[0];
		$end = $daterange_parts[1];

		// modify start and end timestamp (1 Jan 1970 = -3600).
		// perhaps a little bug from DateRangePicker
		$start = strtotime($start);
		$start += 3600;
		$end = strtotime($end);
		$end += 86400 + 3600;
		$where_clause .= " AND o_sec > $start AND o_sec < $end";
	}

	// states
	$states_list = "";
	if($ok != "")		{ $states_list .= "0,"; }
	if($warning != "")	{ $states_list .= "1,"; }
	if($critical != "")	{ $states_list .= "2,"; }
	if($unknown != "")	{ $states_list .= "3,"; }
	$states_list = trim($states_list, ",");

	if($states_list != ""){
		$where_clause .= " AND state IN ($states_list)";
	}

	$where_clause .= " ORDER BY o_sec DESC LIMIT 500";
	return $where_clause;
}


    public static function webuser_comments_count($webuser_id)
    {
        global $DB;
        global $website;

        $DB->query('
            SELECT COUNT(*) AS total
            FROM nv_comments
            WHERE website = '.protect($website->id).'
            AND user = '.protect($webuser_id).'
            AND status = 0'
        );

        $out = $DB->result('total');
        if(is_array($out))
            $out = $out[0];

        return $out;
    }


    public static function delete($id) {
        $id = Typo::int($id);
        try
        {
            $vars1 = array(
                        'table' => 'posts',
                        'where' => array(
                                    'id' => $id
                                    )
                        );
            $d = Db::delete($vars1);

            $vars2 = array(
                        'table' => 'posts_param',
                        'where' => array(
                                    'post_id' => $id
                                    )
                        );
            $d = Db::delete($vars2);
            Hooks::run('post_sqldel_action', $id);
            return true;
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }

    }


function teampass_whitelist() {
    $bdd = teampass_connect();
	$apiip_pool = teampass_get_ips();
	if (count($apiip_pool) > 0 && !array_search($_SERVER['REMOTE_ADDR'], $apiip_pool)) {
		rest_error('IPWHITELIST');
	}
}


function process_user(){
    #'''Call /delta for the given user ID and process any changes.'''
// creation d'un client dropbox
    include("lib/dropboxAPI.php");
    $myCustomClient = new dbx\Client($accessToken, $clientIdentifier);

    //Articles
    $pathPrefix="/Chargements appareil photo/ArticleTdm";
    $cursortxt = "lib/cursor.txt";
    $url="url";
    delta($myCustomClient ,$cursortxt, $url, $pathPrefix);

    //Challenge
    $pathPrefix="/Chargements appareil photo/ChallengeTdm";
    $cursortxt = "lib/cursorC.txt";
    $url="challenge_update";
    delta($myCustomClient , $cursortxt, $url, $pathPrefix);
}


    function update() {
        parent::update();
        expSession::clearAllUsersSessionCache('navigation');
    }


function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
{
	// List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
	// Char '>' '<' '|' '$' and ';' are special chars for shells.
	// Char '/' and '\' are file delimiters.
	$filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
	return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
}


            self::$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            return self::$mysqli;
        }
    }


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

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

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

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

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

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


function phoromatic_account_id_to_group_name($account_id)
{
	// XXX deprecated
	return phoromatic_server::account_id_to_group_name($account_id);
}


    public function validate() {
        global $db;
        // check for an sef url field.  If it exists make sure it's valid and not a duplicate
        //this needs to check for SEF URLS being turned on also: TODO

        if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {
            if (empty($this->sef_url)) $this->makeSefUrl();
            if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();
            if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url']         = array();
        }

        // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router
        // mapped view and src hasn't been passed in via link to the form
        if (isset($this->id) && empty($this->location_data)) {
            $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);
            if (!empty($loc)) $this->location_data = $loc;
        }

        // run the validation as defined in the models
        if (!isset($this->validates)) return true;
        $messages = array();
        $post     = empty($_POST) ? array() : expString::sanitize($_POST);
        foreach ($this->validates as $validation=> $field) {
            foreach ($field as $key=> $value) {
                $fieldname = is_numeric($key) ? $value : $key;
                $opts      = is_numeric($key) ? array() : $value;
                $ret       = expValidator::$validation($fieldname, $this, $opts);
                if (!is_bool($ret)) {
                    $messages[] = $ret;
                    expValidator::setErrorField($fieldname);
                    unset($post[$fieldname]);
                }
            }
        }

        if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);
    }


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

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

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

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

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

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

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

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

		return $where;
	}


	public static function sessionDataDecode(&$var, $checkIs = null) {
		if (self::$base64encodeSessionData) {
			$data = @unserialize(@base64_decode($var));
		} else {
			$data = $var;
		}
		$chk = true;
		if ($checkIs) {
			switch ($checkIs) {
				case 'array':
					$chk = is_array($data);
					break;
				case 'string':
					$chk = is_string($data);
					break;
				case 'object':
					$chk = is_object($data);
					break;
				case 'int':
					$chk = is_int($data);
					break;
			}
		}
		if (!$chk) {
			unset($var);
			return false;
		}
		return $data;
	}


    public function load($id)
    {
        try {
            $select = $this->zdb->select($this->table);
            $select->where($this->fpk . ' = ' . $id);

            $results = $this->zdb->execute($select);
            if ($results->count() > 0) {
                $result = $results->current();
                $this->loadFromRS($result);

                return true;
            } else {
                Analog::log(
                    'Unknown ID ' . $id,
                    Analog::ERROR
                );
                return false;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Cannot load ' . $this->getType() . ' from id `' . $id . '` | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    public static function getHelpVersion($version_id) {
        global $db;

        return $db->selectValue('help_version', 'version', 'id="'.$version_id.'"');
    }


    public function saveConfig() {
        if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {
            if ($this->params['order'] == 'rank ASC') {
                expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);
            }
        }

        parent::saveConfig();
    }


	function edit() {
	    if (empty($this->params['content_id'])) {
	        flash('message',gt('An error occurred: No content id set.'));
            expHistory::back();
	    }
        /* The global constants can be overridden 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'];

	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $comment = new expComment($id);
        //FIXME here is where we might sanitize the comment before displaying/editing it
		assign_to_template(array(
		    'content_id'=>$this->params['content_id'],
            'content_type'=>$this->params['content_type'],
		    'comment'=>$comment
		));
	}


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

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			assign_to_template(array(
                'vendor'=>$vendor
            ));
		}
	}


    public function index(Request $request)
    {

        $contents = $this->getComments($request);

        return $this->view('comment::admin.comments.index', ['contents' => $contents]);
    }


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


    private function getMergeSql()
    {
        switch ($this->driver) {
            case 'mysql':
                return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
                    "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
            case 'oci':
                // DUAL is Oracle specific dummy table
                return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) ".
                    "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
                    "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time";
            case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
                // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
                // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
                return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) ".
                    "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
                    "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time;";
            case 'sqlite':
                return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
        }
    }


    public function delete($id) {
        $this->auth->checkIfOperationIsAllowed('delete_user');
        //Test if user exists
        $data['users_item'] = $this->users_model->getUsers($id);
        if (empty($data['users_item'])) {
            redirect('notfound');
        } else {
            $this->users_model->deleteUser($id);
        }
        log_message('error', 'User #' . $id . ' has been deleted by user #' . $this->session->userdata('id'));
        $this->session->set_flashdata('msg', lang('users_delete_flash_msg_success'));
        redirect('users');
    }


	protected function canCreateTmb($path, $stat, $checkTmbPath = true) {
		return (!$checkTmbPath || $this->tmbPathWritable)
			&& (!$this->tmbPath || strpos($path, $this->tmbPath) === false) // do not create thumnbnail for thumnbnail
			&& $this->imgLib
			&& strpos($stat['mime'], 'image') === 0
			&& ($this->imgLib == 'gd' ? in_array($stat['mime'], array('image/jpeg', 'image/png', 'image/gif', 'image/x-ms-bmp')) : true);
	}


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


	public function localFileSystemInotify($path, $standby, $compare) {
		if (isset($this->sessionCache['localFileSystemInotify_disable'])) {
			return false;
		}
		$path = realpath($path);
		$mtime = filemtime($path);
		if ($mtime != $compare) {
			return $mtime;
		}
		$inotifywait = defined('ELFINER_INOTIFYWAIT_PATH')? ELFINER_INOTIFYWAIT_PATH : 'inotifywait';
		$path = escapeshellarg($path);
		$standby = max(1, intval($standby));
		$cmd = $inotifywait.' '.$path.' -t '.$standby.' -e moved_to,moved_from,move,close_write,delete,delete_self';
		$this->procExec($cmd , $o, $r);
		if ($r === 0) {
			// changed
			clearstatcache();
			$mtime = @filemtime($path); // error on busy?
			return $mtime? $mtime : time();
		} else if ($r === 2) {
			// not changed (timeout)
			return $compare;
		}
		// error
		// cache to $_SESSION
		$this->sessionCache['localFileSystemInotify_disable'] = true;
		$this->session->set($this->id, $this->sessionCache, true);
		return false;
	}


	public static function login() {
		user::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));
		if (!isset($_SESSION[SYS_SESSION_KEY]['user'])) {  // didn't successfully log in
			flash('error', gt('Invalid Username / Password'));
			if (expSession::is_set('redirecturl_error')) {
				$url = expSession::get('redirecturl_error');
				expSession::un_set('redirecturl_error');
				header("Location: ".$url);
			} else {
				expHistory::back();
			}
		} else {  // we're logged in
			global $user;

            if (expSession::get('customer-login')) expSession::un_set('customer-login');
			if (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));
            if ($user->isAdmin()) {
                expHistory::back();
            } else {
                foreach ($user->groups as $g) {
                    if (!empty($g->redirect)) {
                        $url = URL_FULL.$g->redirect;
                        break;
                    }
                }
                if (isset($url)) {
                    header("Location: ".$url);
                } else {
                    expHistory::back();
                }
            }
		}
	}


    public function __construct() {

        self::map();

    }


        $module_views[$key]['name'] = gt($value['name']);
    }

    // look for a config form for this module's current view
//    $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);
    //check to see if hcview was passed along, indicating a hard-coded module
//    if (!empty($controller->params['hcview'])) {
//        $viewname = $controller->params['hcview'];
//    } else {
//        $viewname = $db->selectValue('container', 'view', "internal='".serialize($controller->loc)."'");
//    }
//    $viewconfig = $viewname.'.config';
//    foreach ($modpaths as $path) {
//        if (file_exists($path.'/'.$viewconfig)) {
//            $fileparts = explode('_', $viewname);
//            if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);
//            $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');
//            $module_views[$viewname]['file'] =$path.'/'.$viewconfig;
//        }
//    }

    // sort the views highest to lowest by filename
    // we are reverse sorting now so our array merge
    // will overwrite property..we will run array_reverse
    // when we're finished to get them back in the right order
    krsort($common_views);
    krsort($module_views);

    if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);
    $views = array_merge($common_views, $module_views);
    $views = array_reverse($views);

    return $views;
}


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

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


    public function submit(Request $request)
    {
        return logout();
    }


  public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {
    $this->host = $host;

    //  If no port value is passed, retrieve it
    if ($port == false) {
      $this->port = $this->POP3_PORT;
    } else {
      $this->port = $port;
    }

    //  If no port value is passed, retrieve it
    if ($tval == false) {
      $this->tval = $this->POP3_TIMEOUT;
    } else {
      $this->tval = $tval;
    }

    $this->do_debug = $debug_level;
    $this->username = $username;
    $this->password = $password;

    //  Refresh the error log
    $this->error = null;

    //  Connect
    $result = $this->Connect($this->host, $this->port, $this->tval);

    if ($result) {
      $login_result = $this->Login($this->username, $this->password);

      if ($login_result) {
        $this->Disconnect();

        return true;
      }

    }

    //  We need to disconnect regardless if the login succeeded
    $this->Disconnect();

    return false;
  }


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


	function access($attr, $path, $data, $volume) {
		return strpos(basename($path), '.') === 0       // if file/folder begins with '.' (dot)
			? !($attr == 'read' || $attr == 'write')    // set read+write to false, other (locked+hidden) set to true
			:  null;                                    // else elFinder decide it itself
	}


function nvweb_menu_load_actions()
{
	global $DB;
	global $structure;
	global $current;
	global $website;

	if(empty($structure['actions']))
	{
		$structure['actions'] = array();

		$DB->query('
            SELECT node_id, subtype, text
			  FROM nv_webdictionary
			 WHERE node_type = "structure"
			   AND lang = '.protect($current['lang']).'
			   AND subtype IN("action-type", "action-jump-item", "action-jump-branch", "action-new-window")
			   AND website = '.$website->id
        );

		$data = $DB->result();

		if(!is_array($data))
		    $data = array();

		foreach($data as $row)
		{
			$structure['actions'][$row->node_id][$row->subtype] = $row->text;
		}
	}
}


    public static function activate($id){
        $act = Db::query(
            sprintf("UPDATE `user` SET `status` = '1' WHERE `id` = '%d'",
                Typo::int($id)
                )
            );
        if($act){
            return true;
        }else{
            return false;
        }
    }


            $sloc = expCore::makeLocation('navigation', null, $section->id);
            // remove any manage permissions for this page and it's children
            // $db->delete('userpermission', "module='navigationController' AND internal=".$section->id);
            // $db->delete('grouppermission', "module='navigationController' AND internal=".$section->id);
            foreach ($allusers as $uid) {
                $u = user::getUserById($uid);
                expPermissions::grant($u, 'manage', $sloc);
            }
            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }
        }
    }


		\CsrfMagic\Csrf::$callback = function ($tokens) {
			throw new \App\Exceptions\AppException('Invalid request - Response For Illegal Access', 403);
		};


    static function activate($uid, $karmalevel = 'pear.dev')
    {
        require_once 'Damblan/Karma.php';

        global $dbh, $auth_user;

        $karma = new Damblan_Karma($dbh);

        $user = user::info($uid, null, 0);
        if (!isset($user['registered'])) {
            return false;
        }
        @$arr = unserialize($user['userinfo']);

        include_once 'pear-database-note.php';
        note::removeAll($uid);

        $data = array();
        $data['registered'] = 1;
        $data['active']     = 1;
        /* $data['ppp_only'] = 0; */
        if (is_array($arr)) {
            $data['userinfo'] = $arr[1];
        }
        $data['created']   = gmdate('Y-m-d H:i');
        $data['createdby'] = $auth_user->handle;
        $data['handle']    = $user['handle'];

        user::update($data, true);

        $karma->grant($user['handle'], $karmalevel);
        if ($karma->has($user['handle'], 'pear.dev')) {
            include_once 'pear-rest.php';
            $pear_rest = new pearweb_Channel_REST_Generator(PEAR_REST_PATH, $dbh);
            $pear_rest->saveMaintainerREST($user['handle']);
            $pear_rest->saveAllMaintainersREST();
        }

        include_once 'pear-database-note.php';
        note::add($uid, "Account opened");
        $msg = "Your PEAR account request has been opened.\n".
             "To log in, go to http://" . PEAR_CHANNELNAME . "/ and click on \"login\" in\n".
             "the top-right menu.\n";
        $xhdr = 'From: ' . $auth_user->handle . '@php.net';
        if (!DEVBOX) {
            mail($user['email'], "Your PEAR Account Request", $msg, $xhdr, '-f ' . PEAR_BOUNCE_EMAIL);
        }
        return true;
    }


    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 withoutHeader($header)
    {
        if (!$this->hasHeader($header)) {
            return $this;
        }

        $new = clone $this;
        $name = strtolower($header);
        unset($new->headers[$name]);

        foreach (array_keys($new->headerLines) as $key) {
            if (strtolower($key) === $name) {
                unset($new->headerLines[$key]);
            }
        }

        return $new;
    }


    function reparent_standalone() {
        $standalone = $this->section->find($this->params['page']);
        if ($standalone) {
            $standalone->parent = $this->params['parent'];
            $standalone->update();
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }


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

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

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

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

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

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


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


    public static function navtojson() {
        return json_encode(self::navhierarchy());
    }


function VerifyVariableSchedule($columns)
{
//    $teacher=$columns['TEACHER_ID'];
//    $secteacher=$columns['SECONDARY_TEACHER_ID'];
//     if($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!='')
//     $all_teacher=$teacher.($secteacher!=''?','.$secteacher:'');
//    else
//        $all_teacher=($secteacher!=''?$secteacher:'');

    $teacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']:$columns['TEACHER_ID']);
    $secteacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']:$columns['SECONDARY_TEACHER_ID']);
    //    $secteacher=$qr_teachers[1]['SECONDARY_TEACHER_ID'];

    if($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!='')
    $all_teacher=$teacher.($secteacher!=''?','.$secteacher:'');


$backup = ['sys' => $GLOBALS['TYPO3_CONF_VARS']['SYS'], 'server' => $_SERVER];


    public function actionGetItems(){
        $sql =
            'SELECT id, name as value
            FROM x2_templates
            WHERE name
            LIKE :qterm
            ORDER BY name ASC';

        $command = Yii::app()->db->createCommand($sql);
        $qterm = $_GET['term'].'%';
        $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
        $result = $command->queryAll();
        echo CJSON::encode($result); exit;
    }


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


    public function __construct(Image $image, File $file, ImageRepo $imageRepo)
    {
        $this->image = $image;
        $this->file = $file;
        $this->imageRepo = $imageRepo;
    }


    public function confirm()
    {
        $task = $this->getTask();
        $link_id = $this->request->getIntegerParam('link_id');
        $link = $this->taskExternalLinkModel->getById($link_id);

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

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


    public static function get_param($key = NULL) {
        $info = [
            'stype'        => htmlentities(self::$search_type),
            'stext'        => htmlentities(self::$search_text),
            'method'       => htmlentities(self::$search_method),
            'datelimit'    => self::$search_date_limit,
            'fields'       => self::$search_fields,
            'sort'         => self::$search_sort,
            'chars'        => htmlentities(self::$search_chars),
            'order'        => self::$search_order,
            'forum_id'     => self::$forum_id,
            'memory_limit' => self::$memory_limit,
            'composevars'  => self::$composevars,
            'rowstart'     => self::$rowstart,
            'search_param' => self::$search_param,
        ];

        return $key === NULL ? $info : (isset($info[$key]) ? $info[$key] : NULL);
    }


                foreach ($value as $k => $val) {
                    if ($k != 'LAST_UPDATED') {
                        if ($k != 'UPDATED_BY') {
                            if ($k == 'ID')
                                $data['data'][$i]['SCHOOL_ID'] = $val;
                            else if ($k == 'SYEAR')
                                $data['data'][$i]['SCHOOL_YEAR'] = $val;
                            else if ($k == 'TITLE')
                                $data['data'][$i]['SCHOOL_NAME'] = $val;
                            else if ($k == 'WWW_ADDRESS')
                                $data['data'][$i]['URL'] = $val;
                            else
                                $data['data'][$i][$k] = $val;
                        }
                    }
                }


function exception_for($reason)
{
    return $reason instanceof \Exception
        ? $reason
        : new RejectionException($reason);
}


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

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

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

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

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

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


    function addDiscountToCart() {
//        global $user, $order;
        global $order;
        //lookup discount to see if it's real and valid, and not already in our cart
        //this will change once we allow more than one coupon code

        $discount = new discounts();
        $discount = $discount->getCouponByName($this->params['coupon_code']);

        if (empty($discount)) {
            flash('error', gt("This discount code you entered does not exist."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
            expHistory::back();
        }

        //check to see if it's in our cart already
        if ($this->isDiscountInCart($discount->id)) {
            flash('error', gt("This discount code is already in your cart."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
            expHistory::back();
        }

        //this should really be reworked, as it shoudn't redirect directly and not return
        $validateDiscountMessage = $discount->validateDiscount();
        if ($validateDiscountMessage == "") {
            //if all good, add to cart, otherwise it will have redirected
            $od               = new order_discounts();
            $od->orders_id    = $order->id;
            $od->discounts_id = $discount->id;
            $od->coupon_code  = $discount->coupon_code;
            $od->title        = $discount->title;
            $od->body         = $discount->body;
            $od->save();
            // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;
            flash('message', gt("The discount code has been applied to your cart."));
        } else {
            flash('error', $validateDiscountMessage);
        }
        //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
        expHistory::back();
    }


				$this->paths[substr($key, strlen('path-'))] = $value;
		}


						$rqv = strip_tags($rqv);
					}
					$v = implode(',', $_REQUEST[$var]);
				}
				else
				{
					// TODO add more validation handling checks... then again, PTS client has its own validation of the env vars
					$v = strip_tags($_REQUEST[$var]);
				}
				if(!empty($v) && $v !== 0)
				{
					$posted[$var] = $v;
				}
			}
		}
		return $posted;
	}


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


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


    public function testRedirectLinkGeneration () {
        Yii::app()->controller = new MarketingController (
            'campaign', new MarketingModule ('campaign', null));
        $_SERVER['SERVER_NAME'] = 'localhost';
        $cmb = $this->instantiate();
        $contact = $this->contacts('testUser_unsent');
        $campaign = $this->campaign('redirectLinkGeneration');
        $url = preg_replace ('/^[^"]*"([^"]*)".*$/', '$1', $campaign->content);
        list($subject,$message,$uniqueId) = $cmb->prepareEmail(
            $this->campaign('redirectLinkGeneration'),
            $contact,$this->listItem('testUser_unsent')->emailAddress);
        $this->assertRegExp ('/'.preg_quote (urlencode ($url)).'/', $message);

    }