    public static function cat($vars) {
        switch (SMART_URL) {
            case true:
                # code...
                $url = Options::get('siteurl')."/".$vars."/".Typo::slugify(Categories::name($vars));
                break;

            default:
                # code...
                $url = Options::get('siteurl')."/index.php?cat={$vars}";
                break;

        }

        return $url;
    }


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


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

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

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

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

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


public static function parseAndTrim($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);
        $str = str_replace('"', """, $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "™", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "™", $str)));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


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


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

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

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

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

    return array($rs, $total);
}


	public function actionView($id) {
		$model = CActiveRecord::model('Docs')->findByPk($id);
        if (!$this->checkPermissions($model, 'view')) $this->denied ();

		if(isset($model)){
			$permissions=explode(", ",$model->editPermissions);
			if(in_array(Yii::app()->user->getName(),$permissions))
				$editFlag=true;
			else
				$editFlag=false;
		}
		//echo $model->visibility;exit;
		if (!isset($model) ||
			   !(($model->visibility==1 ||
				($model->visibility==0 && $model->createdBy==Yii::app()->user->getName())) ||
				Yii::app()->params->isAdmin|| $editFlag))
			$this->redirect(array('/docs/docs/index'));

        // add doc to user's recent item list
        User::addRecentItem('d', $id, Yii::app()->user->getId());
        X2Flow::trigger('RecordViewTrigger',array('model'=>$model));
		$this->render('view', array(
			'model' => $model,
		));
	}


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

	return $widths;
}


	protected function GetRefs($refList, $type)
	{
		if (!$refList)
			return;

		if (empty($type))
			return;

		$args = array();
		$args[] = '--' . $type;
		$args[] = '--dereference';
		$ret = $this->exe->Execute($refList->GetProject()->GetPath(), GIT_SHOW_REF, $args);

		$lines = explode("\n", $ret);

		$refs = array();
		$commits = array();

		foreach ($lines as $line) {
			if (preg_match('/^([0-9a-fA-F]{40}) refs\/' . $type . '\/([^^]+)(\^{})?$/', $line, $regs)) {
				if (!empty($regs[3]) && ($regs[3] == '^{}')) {
					$commits[$regs[2]] = $regs[1];
				} else {
					$refs[$regs[2]] = $regs[1];
				}
			}
		}

		return array($refs, $commits);
	}


    public function rules()
    {
        $rules = [];
        $inputs = $this->all();

        $validateEmail = false;
        $validateUsername = false;

        if (!isset($inputs['username']) || !isset($inputs['email'])) {
            $validateUsername = true;
        }

        if (isset($inputs['email']) && !isset($inputs['username'])) {
            $validateUsername = false;
            $validateEmail = true;
        }

        if (isset($inputs['email']) && isset($inputs['username'])) {
            $validateUsername = true;
            $validateEmail = true;
        }

        if ($validateEmail) {
            $rules['email'] = 'email|string|min:3|required|string|max:255|unique:users';
        }

        if ($validateUsername) {
            $rules['username'] = 'alpha_dash|string|min:1|required|string|max:255|unique:users';
        }
        if (isset($inputs['confirm_password'])) {
            $rules['confirm_password'] = 'required|min:1|same:password';
        }

        if (get_option('captcha_disabled', 'users') !== 'y') {
            $rules['captcha'] = 'captcha';
        }

        if (isset($inputs['email']) && $inputs['email'] != false && ((get_option('disable_registration_with_temporary_email', 'users') == 'y'))) {
            $rules['email'] = $rules['email'] . '|temporary_email_check';
        }

        if (get_option('require_terms', 'users') == 'y') {
            $rules['terms'] = 'terms:terms_user';
            if (isset($inputs['newsletter_subscribe']) and $inputs['newsletter_subscribe']) {
                $rules['terms'] = $rules['terms'] . ', terms_newsletter';
            }
        }
        $rules['password'] = 'required|min:1';

        return $rules;
    }


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


	protected function parseRaw($raw, $base, $nameOnly = false) {
		$info = preg_split("/\s+/", $raw, 9);
		$stat = array();

		if (!isset($this->ftpOsUnix)) {
			$this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
		}
		if (!$this->ftpOsUnix) {
			$info = $this->normalizeRawWindows($raw);
		}

		if (count($info) < 9 || $info[8] == '.' || $info[8] == '..') {
			return false;
		}

		$name = $info[8];

		if (preg_match('|(.+)\-\>(.+)|', $name, $m)) {
			$name   = trim($m[1]);
			// check recursive processing
			if ($this->cacheDirTarget && $this->_joinPath($base, $name) !== $this->cacheDirTarget) {
				return array();
			}
			if (!$nameOnly) {
				$target = trim($m[2]);
				if (substr($target, 0, 1) !== $this->separator) {
					$target = $this->getFullPath($target, $base);
				}
				$target = $this->_normpath($target);
				$stat['name']   = $name;
				$stat['target'] = $target;
				return $stat;
			}
		}

		if ($nameOnly) {
			return array('name' => $name);
		}

		if (is_numeric($info[5]) && !$info[6] && !$info[7]) {
			// by normalizeRawWindows()
			$stat['ts'] = $info[5];
		} else {
			$stat['ts'] = strtotime($info[5].' '.$info[6].' '.$info[7]);
			if (empty($stat['ts'])) {
				$stat['ts'] = strtotime($info[6].' '.$info[5].' '.$info[7]);
			}
		}

		$stat['owner'] = '';
		if ($this->options['statOwner']) {
			$stat['owner'] = $info[2];
			$stat['group'] = $info[3];
			$stat['perm']  = substr($info[0], 1);
			$stat['isowner'] = $stat['owner']? ($stat['owner'] == $this->options['user']) : $this->options['owner'];
		}

		$perm = $this->parsePermissions($info[0], $stat['owner']);
		$stat['name']  = $name;
		$stat['mime']  = substr(strtolower($info[0]), 0, 1) == 'd' ? 'directory' : $this->mimetype($stat['name']);
		$stat['size']  = $stat['mime'] == 'directory' ? 0 : $info[4];
		$stat['read']  = $perm['read'];
		$stat['write'] = $perm['write'];

		return $stat;
	}


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


    public static function run () {

        $m = self::match();
        // print_r($m);
        if (is_array($m)) {
            # code...

            $val = self::extract($m[0], $m[1]);

            if (isset($val) && $val != null ) {

                return $val;

            }else{
                $val = ['error'];
                return $val;

            }

        }else{

            $val = ['error'];
            return $val;

        }
    }


name: l.attr('data-name'),
                        realname: l.attr('data-realname'),
                        firstname: l.attr('data-firstname')
                    });
                    l.append(`

                        ${member_item}
                        ${l.attr('data-name') || `${member_itemtype} (${member_items_id})`}

                     <button type="button" name="delete" class="btn btn-ghost-danger">

                     </button>
                  `);
                });
            });

            $(self.element).on('click', '.item-details-panel ul.team-list button[name="delete"]', (e) => {
                const list_item = $(e.target).closest('li');
                const member_itemtype = list_item.attr('data-itemtype');
                const member_items_id = list_item.attr('data-items_id');
                const panel = $(e.target).closest('.item-details-panel');
                const itemtype = panel.attr('data-itemtype');
                const items_id = panel.attr('data-items_id');
                const role = list_item.closest('.list-group').attr('data-role');

                if (itemtype && items_id) {
                    removeTeamMember(itemtype, items_id, member_itemtype, member_items_id, role);
                    list_item.remove();
                }
            });
        };


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

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


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


function delete_bp($bp,$bdd){
    $sql = "delete from bp where name = '" . $bp . "'";
    $bdd->exec($sql);

	$sql = "delete from bp_services where bp_name = '" . $bp . "'";
    $bdd->exec($sql);

	$sql = "delete from bp_links where bp_name = '" . $bp . "'";
	$bdd->exec($sql);

	$sql = "delete from bp_links where bp_link = '" . $bp . "'";
	$bdd->exec($sql);
}


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

        $values = $this->request->getValues();
        list($valid, $errors) = $this->swimlaneValidator->validateModification($values);

        if ($valid) {
            if ($this->swimlaneModel->update($values['id'], $values)) {
                $this->flash->success(t('Swimlane updated successfully.'));
                return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
            } else {
                $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));
            }
        }

        return $this->edit($values, $errors);
    }


    public function load($id)
    {
        try {
            $select = $this->zdb->select(self::TABLE, 't');
            $select->where(self::PK . ' = ' . $id);
            $select->join(
                array('a' => PREFIX_DB . Adherent::TABLE),
                't.' . Adherent::PK . '=a.' . Adherent::PK,
                array()
            );

            //restrict query on current member id if he's not admin nor staff member
            if (!$this->login->isAdmin() && !$this->login->isStaff() && !$this->login->isGroupManager()) {
                if (!$this->login->isLogged()) {
                    Analog::log(
                        'Non-logged-in users cannot load transaction id `' . $id,
                        Analog::ERROR
                    );
                    return false;
                }
                $select->where
                    ->nest()
                        ->equalTo('a.' . Adherent::PK, $this->login->id)
                        ->or
                        ->equalTo('a.parent_id', $this->login->id)
                    ->unnest()
                    ->and
                    ->equalTo('t.' . self::PK, $id)
                ;
            } else {
                $select->where->equalTo(self::PK, $id);
            }

            $results = $this->zdb->execute($select);
            $result = $results->current();
            if ($result) {
                $this->loadFromRS($result);
                return true;
            } else {
                Analog::log(
                    'Transaction id `' . $id . '` does not exists',
                    Analog::WARNING
                );
                return false;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Cannot load transaction form id `' . $id . '` | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    public function testNewInstanceWhenRemovingHeader()
    {
        $r = new Response(200, ['Foo' => 'Bar']);
        $r2 = $r->withoutHeader('Foo');
        $this->assertNotSame($r, $r2);
        $this->assertFalse($r2->hasHeader('foo'));
    }


function functions_list()
{
	$navibars = new navibars();
	$navitable = new navitable("functions_list");

	$navibars->title(t(244, 'Menus'));

	$navibars->add_actions(	array(	' '.t(38, 'Create').'',
									' '.t(39, 'List').'',
									'search_form' ));

	if($_REQUEST['quicksearch']=='true')
    {
        $navitable->setInitialURL("?fid=".$_REQUEST['fid'].'&act=json&_search=true&quicksearch='.$_REQUEST['navigate-quicksearch']);
    }

	$navitable->setURL('?fid='.$_REQUEST['fid'].'&act=json');
	$navitable->sortBy('id');
	$navitable->setDataIndex('id');
	$navitable->setEditUrl('id', '?fid='.$_REQUEST['fid'].'&act=edit&id=');

	$navitable->addCol("ID", 'id', "80", "true", "left");
	$navitable->addCol(t(237, 'Code'), 'codename', "100", "true", "left");
	$navitable->addCol(t(242, 'Icon'), 'icon', "50", "true", "center");
	$navitable->addCol(t(67, 'Title'), 'lid', "200", "true", "left");
	$navitable->addCol(t(65, 'Enabled'), 'enabled', "80", "true", "center");

	$navibars->add_content($navitable->generate());

	return $navibars->generate();

}


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


  public function getError() {
    return $this->error;
  }


	public function authenticate($website, $username, $password)
	{
		global $DB;
        global $events;

		$username = trim($username);
		$username = mb_strtolower($username);

		$A1 = md5($username.':'.APP_REALM.':'.$password);

        $website_check = '';
		if($website > 0)
			$website_check = 'AND website  = '.protect($website);

		if($DB->query('SELECT *
						 FROM nv_webusers
						WHERE ( access = 0 OR
						 		(access = 2 AND
						 			(access_begin = 0 OR access_begin < '.time().') AND
						 			(access_end = 0 OR access_end > '.time().')
					            )
					           )
						  '.$website_check.'
						  AND LOWER(username) = '.protect($username))
		)
		{
			$data = $DB->result();

			if(!empty($data))
			{
				if($data[0]->password==$A1)
				{
					$this->load_from_resultset($data);

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

					return true;
				}
			}
		}

		return false;
	}


	public function editspeed() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        assign_to_template(array(
            'calculator'=>$calc
        ));

    }


    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 static function filesBySearch($text, $wid=NULL, $orderby="name ASC")
	{
		global $DB;
		global $website;

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

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

		return $DB->result();
	}


    protected function getNewShopUrl(Request $request, Shop $newShop)
    {
        // Remove baseUrl from request url
        $url = $request->getRequestUri();

        $repository = $this->get(ModelManager::class)->getRepository(Shop::class);
        $requestShop = $repository->getActiveShopByRequestAsArray($request);
        if ($requestShop && strpos($url, $requestShop['base_url']) === 0) {
            $url = substr($url, \strlen($requestShop['base_url']));
        }

        $baseUrl = $request->getBaseUrl();
        if (strpos($url, $baseUrl . '/') === 0) {
            $url = substr($url, \strlen($baseUrl));
        }

        $basePath = (string) $newShop->getBasePath();
        if (strpos($url, $basePath) === 0) {
            $url = substr($url, \strlen($basePath));
        }

        $host = $newShop->getHost();
        $baseUrl = $newShop->getBaseUrl() ?: $request->getBasePath();

        if ($request->isSecure()) {
            if ($newShop->getBaseUrl()) {
                $baseUrl = $newShop->getBaseUrl();
            } else {
                $baseUrl = $request->getBaseUrl();
            }
        }

        $host = trim($host, '/');
        $baseUrl = trim($baseUrl, '/');
        if (!empty($baseUrl)) {
            $baseUrl = '/' . $baseUrl;
        }

        $url = ltrim($url, '/');
        if (!empty($url)) {
            $url = '/' . $url;
        }

        //build full redirect url to allow host switches
        return sprintf(
            '%s://%s%s%s',
            $request->getScheme(),
            $host,
            $baseUrl,
            $url
        );
    }


    function render($mode, &$renderer, $data) {
        if($mode == 'xhtml') {
            global $conf;
            $id = $data[0];
            $name = $data[1];

            //prepare for formating
            $link['target'] = $conf['target']['wiki'];
            $link['style']  = '';
            $link['pre']    = '';
            $link['suf']    = '';
            $link['more']   = '';
            $link['class']  = 'internallink';
            $link['url']    = DOKU_INTERNAL_LINK . $id;
            $link['name']   = ($name) ? $name : $id;
            $link['title']  = ($name) ? $name : $id;
            //add search string
            if($search){
                ($conf['userewrite']) ? $link['url'].='?s=' : $link['url'].='&s=';
                $link['url'] .= urlencode($search);
            }

            //output formatted
            $renderer->doc .= $renderer->_formatLink($link);
        }
        return true;
    }


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


	public 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 update() {

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

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


    function update_option_master() {
        global $db;

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

        $opt->update($this->params);

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $opt->title) {

        }$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);

        expHistory::back();
    }


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

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

        return $subtask;
    }


    function searchName() {
        return gt("Calendar Event");
    }


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


	protected function get_remote_contents( &$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null ) {
		$method = (function_exists('curl_exec') && !ini_get('safe_mode'))? 'curl_get_contents' : 'fsock_get_contents';
		return $this->$method( $url, $timeout, $redirect_max, $ua, $fp );
	}


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

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


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


    private function filterPath($path)
    {
        return preg_replace_callback(
            '/(?:[^' . self::$charUnreserved . self::$charSubDelims . ':@\/%]+|%(?![A-Fa-f0-9]{2}))/',
            [$this, 'rawurlencodeMatchZero'],
            $path
        );
    }


    public function renew2FaSecretAction(Request $request)
    {
        $this->checkCsrfToken($request);

        $user = $this->getAdminUser();
        $proxyUser = $this->getAdminUser(true);

        $twoFactorService = $this->get('scheb_two_factor.security.google_authenticator');
        $newSecret = $twoFactorService->generateSecret();
        $user->setTwoFactorAuthentication('enabled', true);
        $user->setTwoFactorAuthentication('type', 'google');
        $user->setTwoFactorAuthentication('secret', $newSecret);
        $user->save();

        Tool\Session::useSession(function (AttributeBagInterface $adminSession) {
            Tool\Session::regenerateId();
            $adminSession->set('2fa_required', true);
        });

        $twoFactorService = $this->get('scheb_two_factor.security.google_authenticator');
        $url = $twoFactorService->getQRContent($proxyUser);

        $code = new \Endroid\QrCode\QrCode;
        $code->setWriterByName('png');
        $code->setText($url);
        $code->setSize(200);

        $qrCodeFile = PIMCORE_PRIVATE_VAR . '/qr-code-' . uniqid() . '.png';
        $code->writeFile($qrCodeFile);

        $response = new BinaryFileResponse($qrCodeFile);

        return $response;
    }


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


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


    private function load($id)
    {
        try {
            $select = $this->zdb->select(self::TABLE);
            $select->limit(1)->where(self::PK . ' = ' . $id);
            if ($this->login->isSuperAdmin()) {
                $select->where(Adherent::PK . ' IS NULL');
            } else {
                $select->where(Adherent::PK . ' = ' . (int)$this->login->id);
            }

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

            $this->loadFromRs($res);
        } catch (Throwable $e) {


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

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


public 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 timeToNext()
    {
        $currentTime = microtime(true);
        $nextTime = PHP_INT_MAX;
        foreach ($this->delays as $time) {
            if ($time < $nextTime) {
                $nextTime = $time;
            }
        }

        return max(0, $currentTime - $nextTime);
    }


    function configure() {
        expHistory::set('editable', $this->params);
        // little bit of trickery so that that categories can have their own configs

        $this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
        $this->config = $config->config;
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);
        $views = expTemplate::get_config_templates($this, $this->loc);

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

        $gr = new geoRegion();
        $regions = $gr->find('all');

        assign_to_template(array(
            'config'=>$this->config,
            'pullable_modules'=>$pullable_modules,
            'views'=>$views,
            'countries'=>$countries,
            'regions'=>$regions,
            'title'=>static::displayname()
        ));
    }


    function update_option_master() {
        global $db;

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

        $opt->update($this->params);

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $opt->title) {

        }$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);

        expHistory::back();
    }


	public function LoadContainingTag($commit)
	{
		if (!$commit)
			return;

		$args = array();
		$args[] = '--tags';
		$args[] = $commit->GetHash();
		$revs = explode("\n", $this->exe->Execute($commit->GetProject()->GetPath(), GIT_NAME_REV, $args));

		foreach ($revs as $revline) {
			if (preg_match('/^([0-9a-fA-F]{40})\s+tags\/(.+)(\^[0-9]+|\~[0-9]+)$/', $revline, $regs)) {
				if ($regs[1] == $commit->GetHash()) {
					return $regs[2];
				}
			}
		}
	}


    public function save($filename)
    {
        $json = [];
        foreach ($this as $cookie) {
            /** @var SetCookie $cookie */
            if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
                $json[] = $cookie->toArray();
            }
        }

        if (false === file_put_contents($filename, json_encode($json))) {
            throw new \RuntimeException("Unable to save file {$filename}");
        }
    }


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


    public function testConstruct()
    {
        $handler = new NativeSessionHandler();

        // note for PHPUnit optimisers - the use of assertTrue/False
        // here is deliberate since the tests do not require the classes to exist - drak
        if (PHP_VERSION_ID < 50400) {
            $this->assertFalse($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        } else {
            $this->assertTrue($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        }
    }


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


    public function comments_count()
    {
        global $DB;

        if(empty($this->_comments_count))
        {
            $DB->query('
                SELECT COUNT(*) as total
                      FROM nv_comments
                     WHERE website = ' . protect($this->website) . '
                       AND object_type = "product"
                       AND object_id = ' . protect($this->id) . '
                       AND status = 0'
            );

            $out = $DB->result('total');
            $this->_comments_count = $out[0];
        }

        return $this->_comments_count;
    }


	public function getList($location, $features, $etag, $mediatypes) {
		$featuresArray = explode(';', $features);
		$mediaTypesArray = explode(';', $mediatypes);
		try {
			return $this->getFilesAndAlbums($location, $featuresArray, $etag, $mediaTypesArray);
		} catch (\Exception $exception) {
			return $this->jsonError($exception);
		}
	}


	protected function _copy($source, $targetDir, $name) {
		$ret = copy($source, $this->_joinPath($targetDir, $name));
		$ret && clearstatcache();
		return $ret;
	}


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

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

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

        $simplenote = new expSimpleNote($this->params['id']);
        assign_to_template(array(
            'simplenote'=>$simplenote,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'tab'=>$this->params['tab']
        ));
    }


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

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

        return $category;
    }


    public function testDoesNotAddPortWhenNoPort()
    {
        $this->assertEquals('bar', new Uri('//bar'));
        $this->assertEquals('bar', (new Uri('//bar'))->getHost());
    }


    public function lists($column, $key = null)
    {
        $select = is_null($key) ? [$column] : [$column, $key];

        if (!is_null($this->cacheMinutes)) {
            $results = $this->getCached($select);
        }
        else {
            $results = $this->getFresh($select);
        }

        $collection = new Collection($results);

        return $collection->lists($column, $key);
    }


    public static function get($vars) {
        $op = Db::result("SELECT `value` FROM `options` WHERE `name` = '{$vars}' LIMIT 1");
        if(Db::$num_rows > 0){
            return $op[0]->value;
        }else{
            return false;
        }
    }


    public function session() {
        // Test if logged in, log in if not, log in.
        try {
            $this->assertElementPresent('css=ul#user-menu');
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            /* If this isn't the first time we've logged in, we have a problem;
             * the user should have been logged in throughout the life of the
             * test case class. Append t
             */
            if (!$this->firstLogin)
                array_push($this->verificationErrors, $e->toString());
            $this->firstLogin = false;
            $this->login();
            return 0;
        }
        try {
            $this->assertCorrectUser();
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            /**
             * The browser is logged in but not as the correct user.
             */
            $this->logout();
            $this->login();
            $this->firstLogin = false;
            return 0;
        }
        // Indicator of whether the session was already initialized properly
        return 1;
    }


function get_filedisplay_views() {
    expTemplate::get_filedisplay_views();

    $paths = array(
        BASE.'framework/modules/common/views/file/',
        BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',
    );

    $views = array();
    foreach ($paths as $path) {
        if (is_readable($path)) {
            $dh = opendir($path);
            while (($file = readdir($dh)) !== false) {
                if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {
                    $filename = substr($file, 0, -4);
                    $views[$filename] = gt($filename);
                }
            }
        }
    }

    return $views;
}


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


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


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

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

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


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

	switch ($DatabaseType) {
		case 'mysqli':
			$connection = new ConnectDBOpensis();
			if ($connection->auto_init == true) {
				$connection = $connection->init($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);
				mysqli_set_charset($connection, "utf8");
			}
			break;
	}

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


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


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


    public function testRemovesPreviouslyAddedHeaderOfDifferentCase()
    {
        $r = new Response(200, ['Foo' => 'Bar']);
        $r2 = $r->withHeader('foo', 'Bam');
        $this->assertNotSame($r, $r2);
        $this->assertEquals('Bam', $r2->getHeaderLine('Foo'));
    }


    public function getPLaying(){
        $url = "http://api.themoviedb.org/3/movie/now_playing?api_key=".$this->apikey;
        $now_playing = $this->curl($url);
        return $now_playing;
    }


	public function __construct()
	{
		parent::__construct();
		$this->exposeMethod('getOwners');
		$this->exposeMethod('getReference');
		$this->exposeMethod('getUserRole');
		$this->exposeMethod('verifyPhoneNumber');
		$this->exposeMethod('findAddress');
		$this->exposeMethod('verifyIsHolidayDate');
		$this->exposeMethod('changeFavoriteOwner');
	}


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


    public function saveconfig() {
        global $db;

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


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

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


    public function testDestroy()
    {
        $collection = $this->createMongoCollectionMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $collection->expects($this->once())
            ->method('remove')
            ->with(array($this->options['id_field'] => 'foo'));

        $this->assertTrue($this->storage->destroy('foo'));
    }


    public function edit(Request $request, $id) {

        return $this->view('product::admin.product.edit', [
            'content_id'=>$id
        ]);
    }


  public function Turn() {
    $this->error = array("error" => "This method, TURN, of the SMTP ".
                                    "is not implemented");
    if($this->do_debug >= 1) {
      $this->edebug("SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />');
    }
    return false;
  }


    public function read($sessionId)
    {
        $dbData = $this->getCollection()->findOne(array(
            $this->options['id_field'] => $sessionId,
            $this->options['expiry_field'] => array('$gte' => new \MongoDate()),
        ));

        return null === $dbData ? '' : $dbData[$this->options['data_field']]->bin;
    }


    public function contactInformationSave(Request $request) {

        session_append_array('checkout_v2', [
            'first_name'=> $request->get('first_name'),
            'last_name'=> $request->get('last_name'),
            'email'=> $request->get('email'),
            'phone'=> $request->get('phone')
        ]);

        $validate = $this->_validateContactInformation($request->all());
        if ($validate['valid'] == false) {
            session_set('errors', $validate['errors']);
            return redirect(route('checkout.contact_information'));
        }

        // Success
        return redirect(route('checkout.shipping_method'));
    }


function db_case($array)
{
    global $DatabaseType;

    $counter = 0;
    if ($DatabaseType == 'mysqli') {
        $array_count = count($array);
        $string = " CASE WHEN $array[0] =";
        $counter++;
        $arr_count = count($array);
        for ($i = 1; $i < $arr_count; $i++) {
            $value = $array[$i];

            if ($value == "''" && substr($string, -1) == '=') {
                $value = ' IS NULL';
                $string = substr($string, 0, -1);
            }

            $string .= "$value";
            if ($counter == ($array_count - 2) && $array_count % 2 == 0)
                $string .= " ELSE ";
            elseif ($counter == ($array_count - 1))
                $string .= " END ";
            elseif ($counter % 2 == 0)
                $string .= " WHEN $array[0]=";
            elseif ($counter % 2 == 1)
                $string .= " THEN ";

            $counter++;
        }
    }

    return $string;
}


    public static function isExist($token){
        $json = Options::v('tokens');
        $tokens = json_decode($json, true);
        if(!is_array($tokens) || $tokens == ""){
            $tokens = array();
        }
        if(array_key_exists($token, $tokens)){
            $call = true;
        }else{
            $call = false;
        }
        return $call;
    }


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

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

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

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


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

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

        return $subtask;
    }


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


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


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


    public function getZipFile($path) {
        $filename = basename($path);

        // echo "<pre>";
        // echo $path."\n";
        // echo $filename."\n";
        // echo "isFile => ".is_file($path) ? 'isFile' : 'isNoFile'."\n";
        // echo "</pre>";
        if (is_file($path) || true) {
            // Send the file for download!
            header("Expires: 0");
            header("Cache-Control: must-revalidate");
            header("Content-Type: application/force-download");
            header("Content-Disposition: attachment; filename=$filename");
            header("Content-Description: File Transfer");

            @readfile($path);

            // Delete the temporary file
            unlink($path);
        }
    }


    function update_optiongroup_master() {
        global $db;

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

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

        expHistory::back();
    }


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


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

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

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


            $q = self::query($sql);
        }
        return true;

    }


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

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

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

        return $comment;
    }


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


    protected function assertNoPHPErrors () {
		$this->assertElementNotPresent('css=.xdebug-error');
		$this->assertElementNotPresent('css=#x2-php-error');
    }


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

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

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


function draw_vdef_preview($vdef_id) {
	?>

vdef=<?php print get_vdef($vdef_id, true);?>

	<?php
}


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

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

        return $swimlane;
    }


function db_case($array)
{
	global $DatabaseType;

	$counter = 0;
	if ($DatabaseType == 'mysqli') {
		$array_count = count($array);
		$string = " CASE WHEN $array[0] =";
		$counter++;
		$arr_count = count($array);
		for ($i = 1; $i < $arr_count; $i++) {
			$value = $array[$i];

			if ($value == "''" && substr($string, -1) == '=') {
				$value = ' IS NULL';
				$string = substr($string, 0, -1);
			}

			$string .= "$value";
			if ($counter == ($array_count - 2) && $array_count % 2 == 0)
				$string .= " ELSE ";
			elseif ($counter == ($array_count - 1))
				$string .= " END ";
			elseif ($counter % 2 == 0)
				$string .= " WHEN $array[0]=";
			elseif ($counter % 2 == 1)
				$string .= " THEN ";

			$counter++;
		}
	}

	return $string;
}


    public function testUriEncodesPathProperly($input, $output)
    {
        $uri = new Uri($input);
        $this->assertEquals((string) $uri, $output);
    }


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

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

        return $category;
    }


	public function delete() {
	    global $db;

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

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

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

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

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


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


static function isSearchable() { return true; }


function add_application($uniq_name_orig,$uniq_name,$process_name,$display,$url,$command,$type,$min_value,$bdd){
	if($type != 'MIN'){
		$min_value = "";
	}
	$sql = "select count(*) from bp where name = '" . $uniq_name . "';";
	$req = $bdd->query($sql);
	$bp_exist = $req->fetch();

	// add
	if($bp_exist[0] == 0 and empty($uniq_name_orig)){
		$sql = "insert into bp (name,description,priority,type,command,url,min_value) values('" . $uniq_name ."','" . $process_name ."','" . $display . "','" . $type . "','" . $command . "','" . $url . "','" . $min_value . "')";
		$bdd->exec($sql);
	}
	// uniq name modification
	elseif($uniq_name_orig != $uniq_name) {
		if($bp_exist[0] != 0){
			// TODO QUENTIN
		} else {
			$sql = "update bp set name = '" . $uniq_name . "',description = '" . $process_name . "',priority = '" . $display . "',type = '" . $type . "',command = '" . $command . "',url = '" . $url . "',min_value = '" . $min_value . "' where name = '" . $uniq_name_orig . "'";
			$bdd->exec($sql);
			$sql = "update bp_links set bp_name = '" . $uniq_name . "' where bp_name = '" . $uniq_name_orig . "'";
			$bdd->exec($sql);
			$sql = "update bp_links set bp_link = '" . $uniq_name . "' where bp_link = '" . $uniq_name_orig . "'";
			$bdd->exec($sql);
			$sql = "update bp_services set bp_name = '" . $uniq_name . "' where bp_name = '" . $uniq_name_orig . "'";
			$bdd->exec($sql);
		}
	}
	// modification
	else{
		$sql = "update bp set name = '" . $uniq_name . "',description = '" . $process_name . "',priority = '" . $display . "',type = '" . $type . "',command = '" . $command . "',url = '" . $url . "',min_value = '" . $min_value . "' where name = '" . $uniq_name . "'";
		$bdd->exec($sql);
	}
}


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


	function manage_vendors () {
	    expHistory::set('viewable', $this->params);
		$vendor = new vendor();

		$vendors = $vendor->find('all');
		assign_to_template(array(
            'vendors'=>$vendors
        ));
	}


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


public function SendAndMail($from) {
    $this->error = null; // so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
          "error" => "Called SendAndMail() without being connected");
      return false;
    }

    fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);

    $rply = $this->get_lines();
    $code = substr($rply,0,3);

    if($this->do_debug >= 2) {
      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
');
    }

    if($code != 250) {
      $this->error =
        array("error" => "SAML not accepted from server",
              "smtp_code" => $code,
              "smtp_msg" => substr($rply,4));
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
');
      }
      return false;
    }
    return true;
  }


    public static function getDueDate(Db $zdb, $member_id)
    {
        if (!$member_id) {
            return '';
        }
        try {
            $select = $zdb->select(self::TABLE, 'c');
            $select->columns(
                array(
                    'max_date' => new Expression('MAX(date_fin_cotis)')
                )
            )->join(
                array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
                'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
                array()
            )->where(
                Adherent::PK . ' = ' . $member_id
            )->where(
                array('cotis_extension' => new Expression('true'))
            );

            $results = $zdb->execute($select);
            $result = $results->current();
            $due_date = $result->max_date;

            //avoid bad dates in postgres and bad mysql return from zenddb
            if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
                $due_date = '';
            }
            return $due_date;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred trying to retrieve member\'s due date',
                Analog::ERROR
            );
            throw $e;
        }
    }


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


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


    public function update($id, $label, $extra)
    {
        $ret = $this->get($id);
        if (!$ret) {
            /* get() already logged and set $this->error. */
            return self::ID_NOT_EXITS;
        }

        $class = get_class($this);

        try {
            $oldlabel = $ret->{$this->flabel};
            $this->zdb->connection->beginTransaction();
            $values = array(
                $this->flabel  => $label,
                $this->fthird  => $extra
            );

            $update = $this->zdb->update($this->table);
            $update->set($values);
            $update->where($this->fpk . ' = ' . $id);

            $ret = $this->zdb->execute($update);

            if ($oldlabel != $label) {
                $this->deleteTranslation($oldlabel);
                $this->addTranslation($label);
            }

            Analog::log(
                $this->getType() . ' #' . $id . ' updated successfully.',
                Analog::INFO
            );
            $this->zdb->connection->commit();
            return true;
        } catch (Throwable $e) {
            $this->zdb->connection->rollBack();
            Analog::log(
                'Unable to update ' . $this->getType() . ' #' . $id . ' | ' .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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


    protected function getFullPath($path, $base)
    {
        $separator = $this->separator;
        $systemroot = $this->systemRoot;
        $base = (string)$base;

        if ($base[0] === $separator && substr($base, 0, strlen($systemroot)) !== $systemroot) {
            $base = $systemroot . substr($base, 1);
        }
        if ($base !== $systemroot) {
            $base = rtrim($base, $separator);
        }

        // 'Here'
        if ($path === '' || $path === '.' . $separator) return $base;

        $sepquoted = preg_quote($separator, '#');

        if (substr($path, 0, 3) === '..' . $separator) {
            $path = $base . $separator . $path;
        }
        // normalize `/../`
        $normreg = '#(' . $sepquoted . ')[^' . $sepquoted . ']+' . $sepquoted . '\.\.' . $sepquoted . '#'; // '#(/)[^\/]+/\.\./#'
        while (preg_match($normreg, $path)) {
            $path = preg_replace($normreg, '$1', $path, 1);
        }
        if ($path !== $systemroot) {
            $path = rtrim($path, $separator);
        }

        // Absolute path
        if ($path[0] === $separator || strpos($path, $systemroot) === 0) {
            return $path;
        }

        $preg_separator = '#' . $sepquoted . '#';

        // Relative path from 'Here'
        if (substr($path, 0, 2) === '.' . $separator || $path[0] !== '.') {
            $arrn = preg_split($preg_separator, $path, -1, PREG_SPLIT_NO_EMPTY);
            if ($arrn[0] !== '.') {
                array_unshift($arrn, '.');
            }
            $arrn[0] = rtrim($base, $separator);
            return join($separator, $arrn);
        }

        return $path;
    }


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

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

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


                        $body = str_replace(array("\n"), "<br />", $body);
                    } else {
                        // It's going elsewhere (doesn't like quoted-printable)
                        $body = str_replace(array("\n"), " -- ", $body);
                    }
                    $title = $items[$i]->title;

                    $msg .= "BEGIN:VEVENT\n";
                    $msg .= $dtstart . $dtend;
                    $msg .= "UID:" . $items[$i]->date_id . "\n";
                    $msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
                    if ($title) {
                        $msg .= "SUMMARY:$title\n";
                    }
                    if ($body) {
                        $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
                    }
                    //	if($link_url) { $msg .= "URL: $link_url\n";}
                    if (!empty($this->config['usecategories'])) {
                        if (!empty($items[$i]->expCat[0]->title)) {
                            $msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
                        } else {
                            $msg .= "CATEGORIES:".$this->config['uncat']."\n";
                        }
                    }
                    $msg .= "END:VEVENT\n";
                }


function generate_key($size)
{
  if (
    is_callable('openssl_random_pseudo_bytes')
    and !(version_compare(PHP_VERSION, '5.3.4') < 0 and defined('PHP_WINDOWS_VERSION_MAJOR'))
    )
  {
    return substr(
      str_replace(
        array('+', '/'),
        '',
        base64_encode(openssl_random_pseudo_bytes($size+10))
        ),
      0,
      $size
      );
  }
  else
  {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $l = strlen($alphabet)-1;
    $key = '';
    for ($i=0; $i<$size; $i++)
    {
      $key.= $alphabet[mt_rand(0, $l)];
    }
    return $key;
  }
}


	public function __construct() {

		//ini_set('memory_limit', '128M');
		@ include_once 'Dropbox/autoload.php';
		$this->dropbox_phpFound = in_array('Dropbox_autoload', spl_autoload_functions());

		$opts = array(
			'consumerKey'       => '',
			'consumerSecret'    => '',
			'accessToken'       => '',
			'accessTokenSecret' => '',
			'dropboxUid'        => '',
			'root'              => 'dropbox',
			'path'              => '/',
			'separator'         => '/',
			'PDO_DSN'           => '', // if empty use 'sqlite:(metaCachePath|tmbPath)/elFinder_dropbox_db_(hash:dropboxUid+consumerSecret)'
			'PDO_User'          => '',
			'PDO_Pass'          => '',
			'PDO_Options'       => array(),
			'PDO_DBName'        => 'dropbox',
			'treeDeep'          => 0,
			'tmbPath'           => '',
			'tmbURL'            => '',
			'tmpPath'           => '',
			'getTmbSize'        => 'large', // small: 32x32, medium or s: 64x64, large or m: 128x128, l: 640x480, xl: 1024x768
			'metaCachePath'     => '',
			'metaCacheTime'     => '600', // 10m
			'acceptedName'      => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
			'rootCssClass'      => 'elfinder-navbar-root-dropbox'
		);
		$this->options = array_merge($this->options, $opts);
		$this->options['mimeDetect'] = 'internal';
	}


    public function __construct() {
    }


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

        $values = $this->request->getValues();
        list($valid, $errors) = $this->swimlaneValidator->validateModification($values);

        if ($valid) {
            if ($this->swimlaneModel->update($values['id'], $values)) {
                $this->flash->success(t('Swimlane updated successfully.'));
                return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
            } else {
                $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));
            }
        }

        return $this->edit($values, $errors);
    }


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

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

		$DB->query('SELECT node_id, text
					  FROM nv_webdictionary
					 WHERE node_type = "structure"
					   AND subtype = "title"
					   AND lang = '.protect($current['lang']).'
					   AND website = '.$website->id);

		$data = $DB->result();

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

		foreach($data as $item)
		{
			$structure['dictionary'][$item->node_id] = $item->text;
		}
	}
}


    static function displayname() {
        return "Events";
    }


private function get_lines() {
    $data = "";
    $endtime = 0;
    /* If for some reason the fp is bad, don't inf loop */
    if (!is_resource($this->smtp_conn)) {
      return $data;
    }
    stream_set_timeout($this->smtp_conn, $this->Timeout);
    if ($this->Timelimit > 0) {
      $endtime = time() + $this->Timelimit;
    }
    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
      $str = @fgets($this->smtp_conn,515);
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
');
        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
');
      }
      $data .= $str;
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
');
      }
      // if 4th character is a space, we are done reading, break the loop
      if(substr($str,3,1) == " ") { break; }
      // Timed-out? Log and break
      $info = stream_get_meta_data($this->smtp_conn);
      if ($info['timed_out']) {
        if($this->do_debug >= 4) {
          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds)
");
        }
        break;
      }
      // Now check if reads took too long
      if ($endtime) {
        if (time() > $endtime) {
          if($this->do_debug >= 4) {
            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds)
");
          }
          break;
        }
      }
    }
    return $data;
  }


    public function showall() {
        global $user, $sectionObj, $sections;

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


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

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

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


    public function setBanner($banner)
    {
        $return = $this->setOneToOne($banner, Banner::class, 'banner', 'container');
        $this->setType('ctBanner');

        return $return;
    }


    public function __construct() {
        global $GLOBALS;
    }


            $src = substr($ref->source, strlen($prefix)) . $section->id;
            if (call_user_func(array($ref->module, 'hasContent'))) {
                $oloc = expCore::makeLocation($ref->module, $ref->source);
                $nloc = expCore::makeLocation($ref->module, $src);
                if ($ref->module != "container") {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);
                } else {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);
                }
            }
        }


	public static function client()
	{
		if (is_null(self::$client)) new CertificateAuthenticate();
		return self::$client;
	}


    public function subscriptions() {
        global $db;

        expHistory::set('manageable', $this->params);
        // make sure we have what we need.
        if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));

        // verify the id/key pair
        $sub = new subscribers($this->params['id']);
        if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // get this users subscriptions
        $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);

        // get a list of all available E-Alerts
        $ealerts = new expeAlerts();
        assign_to_template(array(
            'subscriber'=>$sub,
            'subscriptions'=>$subscriptions,
            'ealerts'=>$ealerts->find('all')
        ));
    }


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

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

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


public static function render_page_process($PATH)
	{
		$search_query = $_REQUEST['search'];

		$main = null;

		if(strlen($search_query) < 4)
		{
			$main = '
Search Failed
';
			$main .= '
Search Queries Must Be At Least Four Characters.
';
		}
		else
		{
			$main .= '
Search Results For: ' . $search_query . '
';
			$category_matches = 0;

			$tests = self::search_test_profiles($search_query);
			if($tests != null)
			{
				$category_matches++;
				$main .= '
Test Profile Matches
' . $tests . '
';
			}

			$local_suites = self::search_local_test_suites($search_query);
			if($local_suites != null)
			{
				$category_matches++;
				$main .= '
Local Test Suite Matches
' . $local_suites . '
';
			}

			$test_schedules = self::search_test_schedules($search_query);
			if($test_schedules != null)
			{
				$category_matches++;
				$main .= '
Test Schedule Matches
' . $test_schedules . '
';
			}

			$test_results = self::search_test_results($search_query);
			if($test_results != null)
			{
				$category_matches++;
				$main .= '
Test Result Matches
' . $test_results . '
';
			}

			$test_systems = self::search_test_systems($search_query);
			if($test_systems != null)
			{
				$category_matches++;
				$main .= '
Test System Matches
' . $test_systems . '
';
			}

			if($category_matches == 0)
			{
				$main .= '
No Matches Found
';
			}
		}

		echo phoromatic_webui_header_logged_in();
		echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());
		echo phoromatic_webui_footer();
	}


                $chrootPath = realpath($chrootPath);
                if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                    $chrootValid = true;
                    break;
                }
            }
            if ($chrootValid !== true) {
                throw new Exception("Permission denied on $file. The file could not be found under the paths specified by Options::chroot.");
            }

            $ext = strtolower(pathinfo($realfile, PATHINFO_EXTENSION));
            if (!in_array($ext, $this->allowedLocalFileExtensions)) {
                throw new Exception("Permission denied on $file. This file extension is forbidden");
            }

            if (!$realfile) {
                throw new Exception("File '$file' not found.");
            }

            $uri = $realfile;
        }

        [$contents, $http_response_header] = Helpers::getFileContent($uri, $this->options->getHttpContext());
        if ($contents === null) {
            throw new Exception("File '$file' not found.");
        }

        // See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
        if (isset($http_response_header)) {
            foreach ($http_response_header as $_header) {
                if (preg_match("@Content-Type:\s*[\w/]+;\s*?charset=([^\s]+)@i", $_header, $matches)) {
                    $encoding = strtoupper($matches[1]);
                    break;
                }
            }
        }

        $this->restorePhpConfig();

        $this->loadHtml($contents, $encoding);
    }


	public function delete() {
	    global $db;

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

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

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

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

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


	protected function _unpack($path, $arc) {
		die('Not yet implemented. (_unpack)');
		return false;
	}


    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        if ($input->getOption('semver')) {
            $io->writeln(Constants::VERSION . '-' . Constants::STATUS);

            return 0;
        }

        if ($input->getOption('short')) {
            $io->writeln(Constants::VERSION);

            return 0;
        }

        if ($input->getOption('name')) {
            $io->writeln(Constants::NAME);

            return 0;
        }

        if ($input->getOption('candidate')) {
            $io->writeln(Constants::STATUS);

            return 0;
        }

        $io->writeln(Constants::SOFTWARE . ' - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.');

        return 0;
    }


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


    public static function find($type, $property, $value)
    {
        global $DB;
        global $website;

        $DB->query('
            SELECT * FROM nv_properties_items
            WHERE website = '.protect($website->id).'
              AND property_id = '.protect($property).'
              AND value = '.protect($value),
            'object');

        return $DB->result();
    }


    public function showall_tags() {
        $images = $this->image->find('all');
        $used_tags = array();
        foreach ($images as $image) {
            foreach($image->expTag as $tag) {
                if (isset($used_tags[$tag->id])) {
                    $used_tags[$tag->id]->count++;
                } else {
                    $exptag = new expTag($tag->id);
                    $used_tags[$tag->id] = $exptag;
                    $used_tags[$tag->id]->count = 1;
                }

            }
        }

        assign_to_template(array(
            'tags'=>$used_tags
        ));
    }


    public function testConvertsResponsesToStrings()
    {
        $response = new Psr7\Response(200, [
            'Baz' => 'bar',
            'Qux' => ' ipsum'
        ], 'hello', '1.0', 'FOO');
        $this->assertEquals(
            "HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
            Psr7\str($response)
        );
    }


	function lockTable($table,$lockType="WRITE") {
        $sql = "LOCK TABLES `" . $this->prefix . "$table` $lockType";

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


    public function testPhpSession54()
    {
        $storage = $this->getStorage();

        $this->assertFalse($storage->getSaveHandler()->isActive());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        // in PHP 5.4 we can reliably detect a session started
        $this->assertTrue($storage->getSaveHandler()->isActive());
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
        $this->assertTrue(isset($_SESSION[$key]));
    }


    public function testResource()
    {
        $stream = Psr7\stream_for('foo');
        $handle = StreamWrapper::getResource($stream);
        $this->assertSame('foo', fread($handle, 3));
        $this->assertSame(3, ftell($handle));
        $this->assertSame(3, fwrite($handle, 'bar'));
        $this->assertSame(0, fseek($handle, 0));
        $this->assertSame('foobar', fread($handle, 6));
        $this->assertSame('', fread($handle, 1));
        $this->assertTrue(feof($handle));

        // This fails on HHVM for some reason
        if (!defined('HHVM_VERSION')) {
            $this->assertEquals([
                'dev'     => 0,
                'ino'     => 0,
                'mode'    => 33206,
                'nlink'   => 0,
                'uid'     => 0,
                'gid'     => 0,
                'rdev'    => 0,
                'size'    => 6,
                'atime'   => 0,
                'mtime'   => 0,
                'ctime'   => 0,
                'blksize' => 0,
                'blocks'  => 0,
                0         => 0,
                1         => 0,
                2         => 33206,
                3         => 0,
                4         => 0,
                5         => 0,
                6         => 0,
                7         => 6,
                8         => 0,
                9         => 0,
                10        => 0,
                11        => 0,
                12        => 0,
            ], fstat($handle));
        }

        $this->assertTrue(fclose($handle));
        $this->assertSame('foobar', (string) $stream);
    }


    public function setAutoLogin()
    {
        // create object and set current session data to AutoLogin
        $this->mAutoLogin = new AutoLogin($this->db);
        $this->mAutoLogin->setValue('atl_session_id', $this->getValue('ses_session_id'));
        $this->mAutoLogin->setValue('atl_org_id', (int) $this->getValue('ses_org_id'));
        $this->mAutoLogin->setValue('atl_usr_id', (int) $this->getValue('ses_usr_id'));

        // set new auto_login_id and save data
        $this->mAutoLogin->setValue('atl_auto_login_id', $this->mAutoLogin->generateAutoLoginId((int) $this->getValue('ses_usr_id')));
        $this->mAutoLogin->save();

        // save cookie for autologin
        $currDateTime = new \DateTime();
        $oneYearDateInterval = new \DateInterval('P1Y');
        $oneYearAfterDateTime = $currDateTime->add($oneYearDateInterval);
        $timestampExpired = $oneYearAfterDateTime->getTimestamp();

        self::setCookie($this->cookieAutoLoginId, $this->mAutoLogin->getValue('atl_auto_login_id'), $timestampExpired);
    }