    public static function rss() {
        switch (SMART_URL) {
            case true:
                # code...
                $url = Options::get('siteurl')."/rss".GX_URL_PREFIX;
                break;

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

        }

        return $url;
    }


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

		$vendor->update($this->params['vendor']);
        expHistory::back();
    }


	public function __construct($handler) {
		$this->handler=$handler;
	}


            $schedules[$scheduleCode] = $this->model->createScheduleItem($scheduleCode);
        }

        return $this->schedulesCache = $schedules;
    }


    public function getQuerySelect()
    {
    }


function verify(){
	echo $_GET['challenge'];
}


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

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

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

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

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


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


    public function execute(&$params){
        $options = &$this->config['options'];

        $event = new Events;
        $notif = new Notification;

        $user = $this->parseOption('user', $params);

        $type = $this->parseOption('type', $params);

        if($type === 'auto'){
            if(!isset($params['model']))
                return array (false, '');
            $notif->modelType = get_class($params['model']);
            $notif->modelId = $params['model']->id;
            $notif->type = $this->getNotifType();

            $event->associationType = get_class($params['model']);
            $event->associationId = $params['model']->id;
            $event->type = $this->getEventType();
            if($params['model']->hasAttribute('visibility'))
                $event->visibility = $params['model']->visibility;
            // $event->user = $this->parseOption('user',$params);
        } else{
            $text = $this->parseOption('text', $params);

            $notif->type = 'custom';
            $notif->text = $text;

            $event->type = 'feed';
            $event->subtype = $type;
            $event->text = $text;
            if($user == 'auto' && isset($params['model']) &&
                $params['model']->hasAttribute('assignedTo') &&
                !empty($params['model']->assignedTo)){

                $event->user = $params['model']->assignedTo;
            }elseif(!empty($user)){
                $event->user = $user;
            }else{
                $event->user = 'admin';
            }
        }
        if(!$this->parseOption('createNotif', $params)) {
            if (!$notif->save()) {
                return array(false, array_shift($notif->getErrors()));
            }
        }

        if ($event->save()) {
            return array (true, "");
        } else {
            return array(false, array_shift($event->getErrors()));
        }

    }


    public static function regdate($id){
        $usr = Db::result(
            sprintf("SELECT * FROM `user` WHERE `id` = '%d' OR `userid` = '%s' LIMIT 1",
                Typo::int($id),
                Typo::cleanX($id)
                )
            );
        return $usr[0]->join_date;
    }


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

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


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


    function columnUpdate($table, $col, $val, $where=1) {
        $res = @mysqli_query($this->connection, "UPDATE `" . $this->prefix . "$table` SET `$col`='" . $val . "' WHERE $where");
        /*if ($res == null)
            return array();
        $objects = array();
        for ($i = 0; $i < mysqli_num_rows($res); $i++)
            $objects[] = mysqli_fetch_object($res);*/
        //return $objects;
    }


    public function confirm() {
        global $db;

        // 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
        $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash="'.$this->params['key'].'"');
        if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // activate this users pending subscriptions
        $sub = new stdClass();
        $sub->enabled = 1;
        $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);

        // find the users active subscriptions
        $ealerts = expeAlerts::getBySubscriber($id);
        assign_to_template(array(
            'ealerts'=>$ealerts
        ));
    }


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

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

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

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


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

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

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

        return $out;
    }


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


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


			$ok = $DB->execute('
 				INSERT INTO nv_paths
				(id, website, type, object_id, lang, path, cache_file, cache_expires, views)
				VALUES
				( 0, :website, :type, :object_id, :lang, :path, "", 0, :views )
				',
				array(
					':website' => $website_id,
					':type' => $type,
					':object_id' => $object_id,
					':lang' => $lang,
					':path' => $path,
                    ':views' => 0,
				)
			);

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


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

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

        return $this->response->html($this->template->render('action_creation/event', array(
            'values' => $values,
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


$val = self::escape($val);
                $set .= "'{$val}',";
                $k .= "`{$key}`,";
            }

            $set = substr($set, 0,-1);
            $k = substr($k, 0,-1);

            $sql = sprintf("INSERT INTO `%s` (%s) VALUES (%s) ", $vars['table'], $k, $set) ;
        }else{
            $sql = $vars;
        }
        if(DB_DRIVER == 'mysql') {
            mysql_query('SET CHARACTER SET utf8');
            $q = mysql_query($sql) or die(mysql_error());
            self::$last_id = mysql_insert_id();
        }elseif(DB_DRIVER == 'mysqli'){
            try {
                if(!self::query($sql)){
                    // printf("
Errormessage: %s
\n", self::$mysqli->error);
                    //Control::error('db',self::$mysqli->error);
                    return false;
                }else{
                    self::$last_id = self::$mysqli->insert_id;
                    return true;
                }

            } catch (exception $e) {
                echo $e->getMessage();
            }

        }

        //return true;
    }


$arcs['create']['application/x-rar'] = array('cmd' => ELFINDER_RAR_PATH, 'argc' => 'a -inul' . (defined('ELFINDER_RAR_MA4') && ELFINDER_RAR_MA4? ' -ma4' : ''), 'ext' => 'rar');


    private function userAuth()
    {
        $user = new User();
        $nick = $this->request->request->get('fsNick', '');
        if ($nick === '') {
            return $this->cookieAuth($user);
        }

        if ($user->loadFromCode($nick) && $user->enabled) {
            if ($user->verifyPassword($this->request->request->get('fsPassword'))) {
                // Execute actions from User model extensions
                $user->pipe('login');

                $this->updateCookies($user, true);
                ToolBox::ipFilter()->clear();
                ToolBox::i18nLog()->debug('login-ok', ['%nick%' => $user->nick]);
                ToolBox::log()::setContext('nick', $user->nick);
                return $user;
            }

            $this->ipWarning();
            ToolBox::i18nLog()->warning('login-password-fail');
            return false;
        }

        $this->ipWarning();
        ToolBox::i18nLog()->warning('login-user-not-found', ['%nick%' => $nick]);
        return false;
    }


function html_escape_request_var($string) {
	return htmlspecialchars(get_request_var($string), ENT_QUOTES, 'UTF-8');
}


	protected function _stat($path) {
		$sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime AS ts, f.mime, f.read, f.write, f.locked, f.hidden, f.width, f.height, IF(ch.id, 1, 0) AS dirs
				FROM '.$this->tbf.' AS f
				LEFT JOIN '.$this->tbf.' AS p ON p.id=f.parent_id
				LEFT JOIN '.$this->tbf.' AS ch ON ch.parent_id=f.id AND ch.mime="directory"
				WHERE f.id="'.$path.'"
				GROUP BY f.id';

		$res = $this->query($sql);

		if ($res) {
			$stat = $res->fetch_assoc();
			if ($stat['parent_id']) {
				$stat['phash'] = $this->encode($stat['parent_id']);
			}
			if ($stat['mime'] == 'directory') {
				unset($stat['width']);
				unset($stat['height']);
			} else {
				unset($stat['dirs']);
			}
			unset($stat['id']);
			unset($stat['parent_id']);
			return $stat;

		}
		return array();
	}


    function delete_option_master() {
        global $db;

        $masteroption = new option_master($this->params['id']);

        // delete any implementations of this option master
        $db->delete('option', 'option_master_id='.$masteroption->id);
        $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);
        //eDebug($masteroption);
        expHistory::back();
    }


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

        $this->response->html($this->helper->layout->project('action/remove', array(
            'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),
            'available_events' => $this->eventManager->getAll(),
            'available_actions' => $this->actionManager->getAvailableActions(),
            'project' => $project,
            'title' => t('Remove an action')
        )));
    }


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

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

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


    public function theme_switch() {
        if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) {  // we can't write to the config.php file
            flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));
        }
    	expSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);
	    expSession::set('display_theme',$this->params['theme']);
	    $sv = isset($this->params['sv'])?$this->params['sv']:'';
	    if (strtolower($sv)=='default') {
	       $sv = '';
	    }
	    expSettings::change('THEME_STYLE_REAL',$sv);
	    expSession::set('theme_style',$sv);
	    expDatabase::install_dbtables();  // update tables to include any custom definitions in the new theme

        // $message = (MINIFY != 1) ? "Exponent is now minifying Javascript and CSS" : "Exponent is no longer minifying Javascript and CSS" ;
        // flash('message',$message);
	    $message = gt("You have selected the")." '".$this->params['theme']."' ".gt("theme");
	    if ($sv != '') {
		    $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');
	    }
	    flash('message',$message);
//        expSession::un_set('framework');
        expSession::set('force_less_compile', 1);
//        expTheme::removeSmartyCache();
        expSession::clearAllUsersSessionCache();
    	expHistory::returnTo('manageable');
    }


		elseif ( $columns['TITLE'] )
		{
			$id_new = DBSeqNextID( 'school_marking_periods_marking_period_id_seq' );

			$sql = "INSERT INTO SCHOOL_MARKING_PERIODS ";

			$fields = "MARKING_PERIOD_ID,MP,SYEAR,SCHOOL_ID,";

			$values = "'" . $id_new . "','" . $_REQUEST['mp_term'] . "','" . UserSyear() . "','" . UserSchool() . "',";

			switch ( $_REQUEST['mp_term'] )
			{
				case 'SEM':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['year_id'] . "',";
					break;

				case 'QTR':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['semester_id'] . "',";
					break;

				case 'PRO':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['quarter_id'] . "',";
					break;
			}

			$go = false;

			foreach ( (array) $columns as $column => $value )
			{
				if ( $column === 'START_DATE'
					|| $column === 'END_DATE'
					|| $column === 'POST_START_DATE'
					|| $column === 'POST_END_DATE' )
				{
					//FJ fix SQL bug START_DATE or END_DATE is null

					if ( ! VerifyDate( $value )
						&& $value !== ''
						|| ( ( $column === 'START_DATE'
							|| $column === 'END_DATE' )
							&& $value === '' ) )
					{
						$error[] = _( 'Not all of the dates were entered correctly.' );

						break 2;
					}

					//FJ verify END_DATE > START_DATE

					if (  ( $column === 'END_DATE'
						&& date_create( $value ) <= date_create( $columns['START_DATE'] ) )
						|| ( $column === 'POST_START_DATE'
							&& $columns['POST_END_DATE'] !== ''
							&& date_create( $value ) > date_create( $columns['POST_END_DATE'] ) ) )
					{
						$error[] = _( 'Start date must be anterior to end date.' );

						break 2;
					}
				}

				if ( ! empty( $value )
					|| $value === '0' )
				{
					$fields .= $column . ',';

					$values .= "'" . $value . "',";

					$go = true;
				}
			}

			$sql .= '(' . mb_substr( $fields, 0, -1 ) . ') values(' . mb_substr( $values, 0, -1 ) . ')';
		}


            $db->insertObject($obj, 'expeAlerts_subscribers');
        }

        $count = count($this->params['ealerts']);

        if ($count > 0) {
            flash('message', gt("Your subscriptions have been updated.  You are now subscriber to")." ".$count.' '.gt('E-Alerts.'));
        } else {
            flash('error', gt("You have been unsubscribed from all E-Alerts."));
        }

        expHistory::back();
    }


	function RemoveXSSchars(&$val)
	{
		static $patterns = NULL;
		static $replacements = NULL;
		$val_before = $val;
		$found = true;

		if ( $patterns == NULL ) {
			$patterns = array();
			$replacements = array();

			// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are
			// allowed this prevents some character re-spacing such as <java\0script>
			// note that you have to handle splits with \n, \r, and \t later since they
			// *are* allowed in some inputs
			$patterns[] = '/([\x00-\x08\x0b-\x0c\x0e-\x19])/';
			$replacements[] = '';

			// straight replacements, the user should never need these since they're
			// normal characters this prevents like
			// <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
			// Calculate the search and replace patterns only once
			$search = 'abcdefghijklmnopqrstuvwxyz';
			$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$search .= '1234567890!@#$%^&*()';
			$search .= '~`";:?+/={}[]-_|\'\\';
			for ($i = 0, $istrlen_search = strlen($search); $i < $istrlen_search; $i++) {
				// ;? matches the ;, which is optional
				// 0{0,8} matches any padded zeros,
				// which are optional and go up to 8 chars
				// &#x0040 @ search for the hex values
				$patterns[] = '/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i';
				$replacements[] = $search[$i];
				// &#00064 @ 0{0,8} matches '0' zero to eight times
				// with a ;
				$patterns[] = '/(&#0{0,8}'.ord($search[$i]).';?)/';
				$replacements[] = $search[$i];
			}
		}
		$val = preg_replace($patterns, $replacements, $val);
		if ($val_before == $val) {
			// no replacements were made, so exit the loop
			$found = false;
		}
		return $found;
	}


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

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


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

        }


	private function _finishUp($callFrom = '') {

        $this->logger->setLogInfo('Call from: ' . $callFrom);

		if (function_exists('mw_post_update')) {
			mw_post_update();
		}

        $this->logger->setLogInfo('Cleaning up system cache');

		mw()->cache_manager->clear();

        $zipReader = new ZipReader();
        $zipReader->clearCache();

        $this->logger->setLogInfo('Done!');
	}


	public function update_groupdiscounts() {
	    global $db;

	    if (empty($this->params['id'])) {
	        // look for existing discounts for the same group
	        $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);
	        if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));
	    }

        $gd = new groupdiscounts();
	    $gd->update($this->params);
	    expHistory::back();
	}


    protected function _tempdir($dir, $prefix = '', $mode = 0700)
    {
        if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
            $dir .= DIRECTORY_SEPARATOR;
        }

        do {
            $path = $dir.$prefix.mt_rand(0, 9999999);
        } while (!mkdir($path, $mode));

        return $path;
    }


    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 updatePassword(Db $zdb, $id_adh, $pass)
    {
        try {
            $cpass = password_hash($pass, PASSWORD_BCRYPT);

            $update = $zdb->update(self::TABLE);
            $update->set(
                array('mdp_adh' => $cpass)
            )->where(self::PK . ' = ' . $id_adh);
            $zdb->execute($update);
            Analog::log(
                'Password for `' . $id_adh . '` has been updated.',
                Analog::DEBUG
            );
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred while updating password for `' . $id_adh .
                '` | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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


    public function delete($fileName = null)
    {
        $this->validateFileName();

        list($name, $extension) = $this->model->getFileNameParts();

        return $this->datasource->delete(
            $this->model->getObjectTypeDirName(),
            $name,
            $extension
        );
    }


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


				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques",
					"lang='" . $GLOBALS['spip_lang'] . "' AND id_parent=$id_parent");
				if ($row_rub) {
					$row['id_rubrique'] = $row_rub['id_rubrique'];
				}
			}
		}
	}

	return $row;
}


$link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));


            return getenv('REMOTE_ADDR');
        } else {
            return false;
        }
    }


$res = @unserialize ( base64_decode (str_replace ( array ( "|02" , "|01" ) , array ( "/" , "|" ) , $str ) ) ) ;


public static function html() {
        new Xaptcha();
        $html = "

            ";
        if (self::isEnable()) {
            return $html;
        }else{
            return '';
        }
    }


    protected function _move($source, $targetDir, $name)
    {
        $target = $this->_joinPath($targetDir, $name);
        return $this->connect->rename($source, $target) ? $target : false;
    }


    public function update($data)
    {
        if ($this->securityController->isWikiHibernated()) {
            throw new \Exception(_t('WIKI_IN_HIBERNATION'));
        }
        return $this->dbService->query('UPDATE' . $this->dbService->prefixTable('nature') . 'SET '
            . '`bn_label_nature`="' . addslashes(_convert($data['bn_label_nature'], YW_CHARSET, true)) . '" ,'
            . '`bn_template`="' . addslashes(_convert($data['bn_template'], YW_CHARSET, true)) . '" ,'
            . '`bn_description`="' . addslashes(_convert($data['bn_description'], YW_CHARSET, true)) . '" ,'
            . '`bn_sem_context`="' . addslashes(_convert($data['bn_sem_context'], YW_CHARSET, true)) . '" ,'
            . '`bn_sem_type`="' . addslashes(_convert($data['bn_sem_type'], YW_CHARSET, true)) . '" ,'
            . '`bn_sem_use_template`=' . (isset($data['bn_sem_use_template']) ? '1' : '0') . ' ,'
            . '`bn_condition`="' . addslashes(_convert($data['bn_condition'], YW_CHARSET, true)) . '"'
            . ' WHERE `bn_id_nature`=' . $data['bn_id_nature']);


	public function approve_toggle() {
	    if (empty($this->params['id'])) return;

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

	    $comment = new expComment($this->params['id']);
	    $comment->approved = $comment->approved == 1 ? 0 : 1;
	    if ($comment->approved) {
		    $this->sendApprovalNotification($comment,$this->params);
	    }
	    $comment->save();
	    expHistory::back();
	}


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


	public function read($source) {
		$source = $this->escapePath($source);
		// close the single quote, open a double quote where we put the single quote...
		$source = str_replace('\'', '\'"\'"\'', $source);
		// since returned stream is closed by the caller we need to create a new instance
		// since we can't re-use the same file descriptor over multiple calls
		$command = sprintf('%s --authentication-file=/proc/self/fd/3 //%s/%s -c \'get %s /proc/self/fd/5\'',
			Server::CLIENT,
			$this->server->getHost(),
			$this->name,
			$source
		);
		$connection = new Connection($command);
		$connection->writeAuthentication($this->server->getUser(), $this->server->getPassword());
		$fh = $connection->getFileOutputStream();
		stream_context_set_option($fh, 'file', 'connection', $connection);
		return $fh;
	}


    public function pending() {
//        global $db;

        // make sure we have what we need.
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));

        // find the subscriber and their pending subscriptions
        $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);
        $subscriber = new subscribers($this->params['id']);

        // render the template
        assign_to_template(array(
            'subscriber'=>$subscriber,
            'ealerts'=>$ealerts
        ));
    }


	function token($str) {
		$fw=$this->fw;
		$str=trim(preg_replace('/\{\{(.+?)\}\}/s',trim('\1'),
			$fw->compile($str)));
		if (preg_match('/^(.+)(?<!\|)\|((?:\h*\w+(?:\h*[,;]?))+)$/s',
			$str,$parts)) {
			$str=trim($parts[1]);
			foreach ($fw->split(trim($parts[2],"\xC2\xA0")) as $func)
				$str=((empty($this->filter[$cmd=$func]) &&
					function_exists($cmd)) ||
					is_string($cmd=$this->filter($func)))?
					$cmd.'('.$str.')':
					'Base::instance()->'.
						'call($this->filter(\''.$func.'\'),['.$str.'])';
		}
		return $str;
	}


function draw_vdef_preview($vdef_id) {
	?>

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

	<?php
}


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

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


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

        return $sink;
    }


    public function destroy(Appointment $appointment)
    {
        if (!auth()->user()->can("appointment-create")) {
            return response("Access denied", 403);
        }

        $deleted = $appointment->delete();
        if ($deleted) {
            return response("Success");
        }
        return response("Error", 503);
    }


    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() {
        global $user;

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

        if (empty($this->params['formtitle']))
        {
            if (empty($this->params['id']))
            {
                $formtitle = gt("Add New Note");
            }
            else
            {
                $formtitle = gt("Edit Note");
            }
        }
        else
        {
            $formtitle = $this->params['formtitle'];
        }

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

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


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

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


    static function lookupByUsername($username) {
        if (strpos($username, '@') !== false)
            $user = static::lookup(array('user__emails__address'=>$username));
        else
            $user = static::lookup(array('username'=>$username));

        return $user;
    }


    public static function canView($section) {
        global $db;

        if ($section == null) {
            return false;
        }
        if ($section->public == 0) {
            // Not a public section.  Check permissions.
            return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));
        } else { // Is public.  check parents.
            if ($section->parent <= 0) {
                // Out of parents, and since we are still checking, we haven't hit a private section.
                return true;
            } else {
                $s = $db->selectObject('section', 'id=' . $section->parent);
                return self::canView($s);
            }
        }
    }


    public function confirm() {
        global $db;

        // 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
        $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash="'.$this->params['key'].'"');
        if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // activate this users pending subscriptions
        $sub = new stdClass();
        $sub->enabled = 1;
        $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);

        // find the users active subscriptions
        $ealerts = expeAlerts::getBySubscriber($id);
        assign_to_template(array(
            'ealerts'=>$ealerts
        ));
    }


			foreach($fields as $field)
			{
				if(substr($key, 0, strlen($field.'-'))==$field.'-')
					$this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;
			}


public function convertQuotes($string) {
			$string = str_ireplace('[QUOTE]', '
', $string);
			$string = str_ireplace('[/QUOTE]', '
', $string);
			$string = preg_replace('%\[event\]\s*(\d*)\s*\[/event\]%isU', ' Event $1', $string);
			$string = preg_replace('%\[thread\]\s*(\d*)\s*\[/thread\]%isU', ' Thread $1', $string);
			$string = preg_replace('%\[link\]\s*(http|https|ftp|git|ftps)(.*)\s*\[/link\]%isU', '$1$2', $string);
			$string = preg_replace('%\[code\](.*)\[/code\]%isU', '
$1
', $string);

			return $string;
		}


    public function actionGetLists() {
        if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {
            $condition = ' AND (visibility="1" OR assignedTo="Anyone"  OR assignedTo="' . Yii::app()->user->getName() . '"';
            /* x2temp */
            $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();
            if (!empty($groupLinks))
                $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';

            $condition .= ' OR (visibility=2 AND assignedTo IN
                (SELECT username FROM x2_group_to_user WHERE groupId IN
                (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . '))))';
        } else {
            $condition = '';
        }
        // Optional search parameter for autocomplete
        $qterm = isset($_GET['term']) ? $_GET['term'] . '%' : '';
        $result = Yii::app()->db->createCommand()
                ->select('id,name as value')
                ->from('x2_lists')
                ->where('modelName="Contacts" AND type!="campaign" AND name LIKE :qterm' . $condition, array(':qterm' => $qterm))
                ->order('name ASC')
                ->queryAll();
        echo CJSON::encode($result);
    }


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

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

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


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


    static function isSearchable() {
        return true;
    }


    public function upload() {

        // upload the file, but don't save the record yet...
        if ($this->params['resize'] != 'false') {
            $maxwidth = $this->params['max_width'];
        } else {
            $maxwidth = null;
        }
        $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);
        // since most likely this function will only get hit via flash in YUI Uploader
        // and since Flash can't pass cookies, we lose the knowledge of our $user
        // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,
        // and then assign $user->id to $file->poster so we have an audit trail for the upload

        if (is_object($file)) {
            $resized = !empty($file->resized) ? true : false;
            $user = new user($this->params['usrid']);
            $file->poster = $user->id;
            $file->posted = $file->last_accessed = time();
            $file->save();
            if (!empty($this->params['cat'])) {
                $expcat = new expCat($this->params['cat']);
                $params['expCat'][0] = $expcat->id;
                $file->update($params);
            }

            // a echo so YUI Uploader is notified of the function's completion
            if ($resized) {
                echo gt('File resized and then saved');
            } else {
                echo gt('File saved');
            }
        } else {
            echo gt('File was NOT uploaded!');
//            flash('error',gt('File was not uploaded!'));
        }
    }


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

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

        return $category;
    }


	public function delete() {
	    global $user;

        $count = $this->address->find('count', 'user_id=' . $user->id);
        if($count > 1)
        {
            $address = new address($this->params['id']);
	        if ($user->isAdmin() || ($user->id == $address->user_id)) {
                if ($address->is_billing)
                {
                    $billAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $billAddress->is_billing = true;
                    $billAddress->save();
                }
                if ($address->is_shipping)
                {
                    $shipAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $shipAddress->is_shipping = true;
                    $shipAddress->save();
                }
	            parent::delete();
	        }
        }
        else
        {
            flash("error", gt("You must have at least one address."));
        }
	    expHistory::back();
	}


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

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


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

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

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


function NewSectionPrompt(){
		global $langmessage;

		ob_start();
		echo '
';
		echo '<form method="post" action="'.common::GetUrl($this->title).'">';
		echo '
'.$langmessage['new_section_about'].'
';

		echo '
';
		echo '
'.$langmessage['New Section'].'
';

		echo '
';
		echo $langmessage['Content Type'];
		echo '	';
		editing_page::SectionTypes();
		echo '
';

		echo '
';
		echo $langmessage['Insert Location'];
		echo '	';
		echo '<input type="radio" name="insert" value="before" /> ';
		echo $langmessage['insert_before'];
		echo '';
		echo '<input type="radio" name="insert" value="after" checked="checked" /> ';
		echo $langmessage['insert_after'];
		echo '';
		echo '
';

		echo '
';

		echo '
';
		echo '<input type="hidden" name="last_mod" value="'.$this->fileModTime.'" />';
		echo '<input type="hidden" name="section" value="'.$_GET['section'].'" />';
		echo '<input type="hidden" name="cmd" value="add_section" />';
		echo '<input type="submit" name="" value="'.$langmessage['save'].'" class="gpsubmit"/>';
		echo ' <input type="button" name="" value="'.$langmessage['cancel'].'" class="admin_box_close gpcancel" />';
		echo '
';

		echo '</form>';
		echo '
';
		$this->contentBuffer = ob_get_clean();

	}


$incident_title = strip_tags(html_entity_decode(html_entity_decode($this->data->item_title, ENT_QUOTES)));


    public function breadcrumb() {
        global $sectionObj;

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


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

        $str = str_replace("�", "’", $str);
        $str = str_replace("�", "‘", $str);
        $str = str_replace("�", "®", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "—", $str);
        $str = str_replace("�", "”", $str);
        $str = str_replace("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\t", " ", $str);
        $str = str_replace(",", "\,", $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);

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

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


    protected function assetExtensions()
    {
        return [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'ico',
            'css',
            'js',
            'woff',
            'woff2',
            'svg',
            'ttf',
            'eot',
            'json',
            'md',
            'less',
            'sass',
            'scss',
            'xml'
        ];
    }


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

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


      print_r($single_error);
    }

    echo '</pre>';
  }


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

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

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

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

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


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

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

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

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


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

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


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


    public static function strValidCharacters($string, $checkType)
    {
        if (trim($string) === '') {
            return false;
        }

        switch ($checkType) {
            case 'noSpecialChar': // a simple e-mail address should still be possible (like username)
                $validRegex = '/^[\w.@+-]+$/i';
                break;
            case 'email':
                $validRegex = '/^[\wáàâåäæçéèêîñóòôöõøœúùûüß.@+-]+$/i';
                break;
            case 'file':
                $validRegex = '=^[^/?*;:~<>|\"\\\\]+\.[^/?*;:~<>|‚\"\\\\]+$=';
                break;
            case 'folder':
                $validRegex = '=^[^/?*;:~<>|\"\\\\]+$=';
                break;
            case 'url':
                $validRegex = '/^[\wáàâåäæçéèêîñóòôöõøœúùûüß$&!?() \/%=#:~.@+-]+$/i';
                break;
            case 'phone':
                $validRegex = '/^[\d() \/+-]+$/i';
                break;
            default:
                return false;
        }

        // check if string contains only valid characters
        if (!preg_match($validRegex, $string)) {
            return false;
        }

        switch ($checkType) {
            case 'email':
                return filter_var(trim($string), FILTER_VALIDATE_EMAIL) !== false;
            case 'url':
                return filter_var(trim($string), FILTER_VALIDATE_URL) !== false;
            default:
                return true;
        }
    }


        $period_days_append_sql=  substr($period_days_append_sql,0,-4).'))';
    }

    $exist_RET=  DBGet(DBQuery("SELECT s.ID FROM schedule s WHERE student_id=".  $student_id." AND s.syear='".UserSyear()."' {$mp_append_sql}{$period_days_append_sql} UNION SELECT s.ID FROM temp_schedule s WHERE student_id=".  $student_id."{$mp_append_sql}{$period_days_append_sql}"));
    if($exist_RET)
        return 'There is a Period Conflict ('.$course_RET[1]['CP_TITLE'].')';
    else
    {
        return true;
    }
}


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

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


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


    public static function getDefaultLang() {
        $def = Options::v('multilang_default');
        $lang = json_decode(Options::v('multilang_country'), true);
        $deflang = $lang[$def];
        return $deflang;
    }


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


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

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


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


    public function confirm()
    {
        $task = $this->getTask();
        $comment = $this->getComment();

        $this->response->html($this->template->render('comment/remove', array(
            'comment' => $comment,
            'task' => $task,
            'title' => t('Remove a comment')
        )));
    }


    public static function modList(){
        //$mod = '';
        $handle = dir(GX_MOD);
        while (false !== ($entry = $handle->read())) {
            if ($entry != "." && $entry != ".." ) {
                    $dir = GX_MOD.$entry;
                    if(is_dir($dir) == true){
                        $mod[] = basename($dir);
                    }
            }
        }

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


		function new_user() {
			global $db;
			$insert = $db->sql_query("INSERT INTO `mod_useronline` (`timestamp`, `ip`) VALUES ('mysql_real_escape_string($this->timestamp)', 'mysql_real_escape_string($this->ip)')");
			if (!$insert) {
				$this->error[$this->i] = "Unable to record new visitor\r\n";
				$this->i ++;
			}
		}


  protected function getUserzoneCookie()
  {
  	$cookie = $this->getContext()->getRequest()->getCookie('userzone');
  	$length = strlen($cookie);
  	if ($length <= 0)
  		return null;

  	$serialized_data = substr($cookie, 0, $length - 32);
  	$hash_signiture = substr($cookie, $length - 32);

  	// check the signiture
  	if (md5($serialized_data . $this->cookieSecret) != $hash_signiture)
  		return null;

  	$userzone_data = unserialize(base64_decode($serialized_data));

  	return array($userzone_data['id'], $userzone_data['email'], $userzone_data['screenname']);
  }


	public function insert()
	{
		global $DB;

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

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

		$this->id = $DB->get_last_id();

		return true;
	}


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

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

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


    public function getModel()
    {
        return $this->model;
    }


    public static function all_in_array()
    {
        global $DB;
        global $website;
        $out = array();

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

        $rs = $DB->result();

        foreach($rs as $row)
            $out[$row->id] = $row->name;

        return $out;
    }


    public static function thmList(){
        //$mod = '';
        $handle = dir(GX_THEME);
        while (false !== ($entry = $handle->read())) {
            if ($entry != "." && $entry != ".." ) {
                    $dir = GX_THEME.$entry;
                    if(is_dir($dir) == true){
                        $thm[] = basename($dir);
                    }
            }
        }

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


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


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

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

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


    public function testNameExceptionPhp53()
    {
        if (PHP_VERSION_ID >= 50400) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->proxy->setActive(true);
        $this->proxy->setName('foo');
    }


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

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

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

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


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


    public function getAlpha($key, $default = '', $deep = false)
    {
        return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default, $deep));
    }


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

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


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

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

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

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


                    $modelNames[ucfirst($module->name)] = self::getModelTitle($modelName);
            }
            asort ($modelNames);
            if ($criteria !== null) {
                return $modelNames;
            } else {
                self::$_modelNames = $modelNames;
            }
        }
        return self::$_modelNames;
    }


    protected function parseChunkedRequest(Request $request)
    {
        $index = $request->get('qqpartindex');
        $total = $request->get('qqtotalparts');
        $uuid = $request->get('qquuid');
        $orig = $request->get('qqfilename');
        $last = ((int) $total - 1) === (int) $index;

        return [$last, $uuid, $index, $orig];
    }


foreach ($elem[2] as $field) {
                    echo '

                           '.$field[1].' :

<input type="hidden" id="hid_field_'.$field[0].'" class="fields" />

';
        }


    public static function fixName($name) {
        $name = preg_replace('/[^A-Za-z0-9\.]/','_',$name);
        if ($name[0] == '.')
            $name[0] = '_';
        return $name;
//        return preg_replace('/[^A-Za-z0-9\.]/', '-', $name);
    }


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

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


    public static function exist($cat)
    {
        $cat = Typo::int($cat);
        $sql = "SELECT `id` FROM `cat` WHERE `id` = '{$cat}' AND `type` = 'post'";
        $q = Db::result($sql);
        // echo Db::$num_rows;
        if (Db::$num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }


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


	public function setting($name, $value=NULL)
    {
        global $DB;
        global $website;

        $DB->query(
            'SELECT *
             FROM nv_settings
             WHERE  type = "user" AND
                    user = '.protect($this->id).' AND
                    website = '.protect($website->id).' AND
                    name = '.protect($name)
        );

        $setting = $DB->first();

        if(!isset($value))
        {
            if(!empty($setting))
                $value = $setting->value;
        }
        else
        {
            // replace setting value
            if(empty($setting))
            {
                $DB->execute('
                    INSERT INTO nv_settings
                       (id, website, type, user, name, value)
                     VALUES
                      (:id, :website, :type, :user, :name, :value)
                ', array(
                    ':id' => 0,
                    ':website' => $website->id,
                    ':type' => "user",
                    ':user' => $this->id,
                    ':name' => $name,
                    ':value' => $value
                ));
            }
            else
            {
                $DB->execute('
                    UPDATE nv_settings
                       SET value = :value
                     WHERE id = :id
                ', array(
                    ':id' => $setting->id,
                    ':value' => $value
                ));
            }
        }

        return $value;
    }


    private function sub_resource_download()
    {
        if (empty($this->response->meta->sub_resource_id)) {
            $this->response->meta->sub_resource_id = 0;
        }
        $attachment = $this->m_devices->read_sub_resource($this->response->meta->id, $this->response->meta->sub_resource, $this->response->meta->sub_resource_id, '*', '', '', '');
        $this->load->helper('file');
        if (php_uname('s') === 'Windows NT') {
            $temp = explode('\\', $attachment[0]->attributes->filename);
        } else {
            $temp = explode('/', $attachment[0]->attributes->filename);
        }
        $filename = $temp[count($temp)-1];
        $filename = preg_replace('/'.$this->response->meta->id.'_/', '', $filename, 1);
        header('Content-Type: '.get_mime_by_extension($attachment[0]->attributes->filename));
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        readfile($attachment[0]->attributes->filename);
    }


    public function store($zdb)
    {
        $data = array(
            'short_label'   => $this->short,
            'long_label'    => $this->long
        );
        try {
            if ($this->id !== null && $this->id > 0) {
                $update = $zdb->update(self::TABLE);
                $update->set($data)->where(
                    self::PK . '=' . $this->id
                );
                $zdb->execute($update);
            } else {
                $insert = $zdb->insert(self::TABLE);
                $insert->values($data);
                $add = $zdb->execute($insert);
                if (!$add->count() > 0) {
                    Analog::log('Not stored!', Analog::ERROR);
                    return false;
                }

                $this->id = $zdb->getLastGeneratedValue($this);
            }
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred storing title: ' . $e->getMessage() .
                "\n" . print_r($data, true),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public static function getParent($id=''){
        $sql = sprintf("SELECT `parent` FROM `cat`
                        WHERE `id` = '%d'", $id);
        $cat = Db::result($sql);
        return $cat;
    }


            $ret[$key] = sprintf(
                $format,
                ++$i,
                $err[0],
                $err[1],
                $err[2],
                $err[3]
            );
        }

        return $ret;
    }


                        foreach ($value_arr['ENROLLMENT_INFO'] as $eid => $ed) {
                            echo '<ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                            echo '<SCHOOL_ID>' . htmlentities($ed['SCHOOL_ID']) . '</SCHOOL_ID>';
                            echo '<CALENDAR>' . htmlentities($ed['CALENDAR']) . '</CALENDAR>';
                            echo '<GRADE>' . htmlentities($ed['GRADE']) . '</GRADE>';
                            echo '<SECTION>' . htmlentities($ed['SECTION']) . '</SECTION>';
                            echo '<START_DATE>' . htmlentities($ed['START_DATE']) . '</START_DATE>';
                            echo '<DROP_DATE>' . htmlentities($ed['DROP_DATE']) . '</DROP_DATE>';
                            echo '<ENROLLMENT_CODE>' . htmlentities($ed['ENROLLMENT_CODE']) . '</ENROLLMENT_CODE>';
                            echo '<DROP_CODE>' . htmlentities($ed['DROP_CODE']) . '</DROP_CODE>';
                            echo '</ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                        }


    public function testEncodeFormulasWithSettingsPassedInContext()
    {
        $this->assertSame(<<<'CSV'
0
"	=2+3"

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

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

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

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

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

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

CSV
            , $this->encoder->encode(['@MyDataColumn'], 'csv', [
                CsvEncoder::ESCAPE_FORMULAS_KEY => true,
            ]));
    }


    public function getQueryOrderby()
    {
        $R1 = 'R1_' . $this->field->id;
        $R2 = 'R2_' . $this->field->id;
        return $this->is_rank_alpha ? "$R2.label" : "$R2.rank";
    }


    public static function install ($var) {
        include(GX_PATH.'/gxadmin/themes/install/'.$var.'.php');
    }


    public function activate_address()
    {
        global $db, $user;

        $object = new stdClass();
        $object->id = $this->params['id'];
        $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], "user_id=" . $user->id);
        flash("message", gt("Successfully updated address."));
        expHistory::back();
    }


            $regx = str_replace('/','\/', $k);

            if ( preg_match('/^'.$regx.'$/Usi', $uri, $m) ) {
                $result = [$v,$m];
                return $result;

            }

        }
    }


    static function description() {
        return gt("This module is for managing categories in your store.");
    }


    public function checkOverlap()
    {
        try {
            $select = $this->zdb->select(self::TABLE, 'c');
            $select->columns(
                array('date_debut_cotis', 'date_fin_cotis')
            )->join(
                array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
                'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
                array()
            )->where(Adherent::PK . ' = ' . $this->_member)
                ->where(array('cotis_extension' => new Expression('true')))
                ->where->nest->nest
                ->greaterThanOrEqualTo('date_debut_cotis', $this->_begin_date)
                ->lessThan('date_debut_cotis', $this->_end_date)
                ->unnest
                ->or->nest
                ->greaterThan('date_fin_cotis', $this->_begin_date)
                ->lessThanOrEqualTo('date_fin_cotis', $this->_end_date);

            if ($this->id != '') {
                $select->where(self::PK . ' != ' . $this->id);
            }

            $results = $this->zdb->execute($select);
            if ($results->count() > 0) {
                $result = $results->current();
                $d = new \DateTime($result->date_debut_cotis);

                return _T("- Membership period overlaps period starting at ") .
                    $d->format(__("Y-m-d"));
            }
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred checking overlapping fee. ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


	public function adminBodyEnd()
	{
		global $L;

		if (!in_array($GLOBALS['ADMIN_CONTROLLER'], $this->loadOnController)) {
			return false;
		}

		// Spell Checker
		$spellCheckerEnable = $this->getValue('spellChecker')?'true':'false';

		// Include plugin's Javascript files
		$html  = $this->includeJS('simplemde.min.js');
		$html .= '<script>'.PHP_EOL;
		$html .= 'var simplemde = null;'.PHP_EOL;

		// Include add content to the editor
		$html .= 'function addContentSimpleMDE(content) {
				var text = simplemde.value();
				simplemde.value(text + content + "\n");
				simplemde.codemirror.refresh();
			}'.PHP_EOL;

		// Returns the content of the editor
		// Function required for Bludit
		$html .= 'function editorGetContent(content) {
			return simplemde.value();
		}'.PHP_EOL;

		// Insert an image in the editor at the cursor position
		// Function required for Bludit
		$html .= 'function editorInsertMedia(filename) {
				addContentSimpleMDE("!['.$L->get('Image description').']("+filename+")");
			}'.PHP_EOL;

		$html .= '$(document).ready(function() { '.PHP_EOL;
		$html .= 'simplemde = new SimpleMDE({
				element: document.getElementById("jseditor"),
				status: false,
				toolbarTips: true,
				toolbarGuideIcon: true,
				autofocus: false,
				placeholder: "'.$L->get('content-here-supports-markdown-and-html-code').'",
				lineWrapping: true,
				autoDownloadFontAwesome: false,
				indentWithTabs: true,
				tabSize: '.$this->getValue('tabSize').',
				spellChecker: '.$spellCheckerEnable.',
				toolbar: ['.Sanitize::htmlDecode($this->getValue('toolbar')).',
					"|",
					{
					name: "pageBreak",
					action: function addPageBreak(editor){
						var cm = editor.codemirror;
						output = "\n'.PAGE_BREAK.'\n";
						cm.replaceSelection(output);
						},
					className: "oi oi-crop",
					title: "'.$L->get('Pagebreak').'",
					}]
		});';
		$html .= '}); </script>';
		return $html;
	}


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


    public function saveNewFromLink($name, $link, $page_id)
    {
        $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');
        return Attachment::forceCreate([
            'name' => $name,
            'path' => $link,
            'external' => true,
            'extension' => '',
            'uploaded_to' => $page_id,
            'created_by' => user()->id,
            'updated_by' => user()->id,
            'order' => $largestExistingOrder + 1
        ]);
    }


    public function store($zdb)
    {
        $data = array(
            'short_label'   => $this->short,
            'long_label'    => $this->long
        );
        try {
            if ($this->id !== null && $this->id > 0) {
                $update = $zdb->update(self::TABLE);
                $update->set($data)->where([self::PK => $this->id]);
                $zdb->execute($update);
            } else {
                $insert = $zdb->insert(self::TABLE);
                $insert->values($data);
                $add = $zdb->execute($insert);
                if (!$add->count() > 0) {
                    Analog::log('Not stored!', Analog::ERROR);
                    return false;
                }

                $this->id = $zdb->getLastGeneratedValue($this);
            }
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred storing title: ' . $e->getMessage() .
                "\n" . print_r($data, true),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public function install () {
        Session::start();
        System::gZip();
        Theme::install('header');
        Control::handler('install');
        Theme::install('footer');
        System::Zipped();
    }


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

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

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


    public function save()
    {
        session_write_close();

        if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
            // This condition matches only PHP 5.3 with internal save handlers
            $this->saveHandler->setActive(false);
        }

        $this->closed = true;
        $this->started = false;
    }


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


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


    function edit() {
        global $user;

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

        if (empty($this->params['formtitle']))
        {
            if (empty($this->params['id']))
            {
                $formtitle = gt("Add New Note");
            }
            else
            {
                $formtitle = gt("Edit Note");
            }
        }
        else
        {
            $formtitle = $this->params['formtitle'];
        }

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

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


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

        if ($tag['project_id'] != $project['id']) {
            throw new AccessForbiddenException();
        }

        if ($this->tagModel->remove($tag_id)) {
            $this->flash->success(t('Tag removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this tag.'));
        }

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


    public static function validateSignature(array $data, XMLSecurityKey $key)
    {
        assert('array_key_exists("Query", $data)');
        assert('array_key_exists("SigAlg", $data)');
        assert('array_key_exists("Signature", $data)');

        $query = $data['Query'];
        $sigAlg = $data['SigAlg'];
        $signature = $data['Signature'];

        $signature = base64_decode($signature);

        if ($key->type !== XMLSecurityKey::RSA_SHA1) {
            throw new \Exception('Invalid key type for validating signature on query string.');
        }
        if ($key->type !== $sigAlg) {
            $key = Utils::castKey($key, $sigAlg);
        }

        if (!$key->verifySignature($query, $signature)) {
            throw new \Exception('Unable to validate signature on query string.');
        }
    }


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

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

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

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

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

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


    public function testGetDeep()
    {
        $bag = new ParameterBag(array('foo' => array('bar' => array('moo' => 'boo'))));

        $this->assertEquals(array('moo' => 'boo'), $bag->get('foo[bar]', null, true));
        $this->assertEquals('boo', $bag->get('foo[bar][moo]', null, true));
        $this->assertEquals('default', $bag->get('foo[bar][foo]', 'default', true));
        $this->assertEquals('default', $bag->get('bar[moo][foo]', 'default', true));
    }


    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 function activate_address()
    {
        global $db, $user;

        $object = new stdClass();
        $object->id = $this->params['id'];
        $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], "user_id=" . $user->id);
        flash("message", gt("Successfully updated address."));
        expHistory::back();
    }


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


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

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


    public function testPortMustBeValid()
    {
        (new Uri(''))->withPort(100000);
    }


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

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


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


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

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

        return $category;
    }


    public function rules()
    {
        return [
            'sku' => ['required'],
            'name' => ['required', Rule::unique('products')->ignore($this->segment(3))],
            'quantity' => ['required', 'integer', 'min:0'],
            'price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric', 'min:0']
        ];
    }


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


	protected function filter($files) {
		foreach ($files as $i => $file) {
			if (!empty($file['hidden']) || !$this->default->mimeAccepted($file['mime'])) {
				unset($files[$i]);
			}
		}
		return array_merge($files, array());
	}


static function description() { return gt("Places navigation links/menus on the page."); }


	public static function recent_actions($function, $action, $limit=8)
	{
		global $DB;
		global $user;
		global $website;

		// last month only!
		$DB->query('
			SELECT DISTINCT nvul.website, nvul.function, nvul.item, nvul.date
			FROM nv_users_log nvul
			WHERE nvul.user = '.protect($user->id).'
			  AND nvul.function = '.protect($function).'
			  AND nvul.item > 0
			  AND nvul.action = '.protect($action).'
			  AND nvul.website = '.protect($website->id).'
			  AND nvul.date > '.( core_time() - 30 * 86400).'
			  AND nvul.date = (	SELECT MAX(nvulm.date)
			  					  FROM nv_users_log nvulm
			  					 WHERE nvulm.function = nvul.function
			  					   AND nvulm.item = nvul.item
			  					   AND nvulm.item_title = nvul.item_title
			  					   AND nvulm.website = '.protect($website->id).'
			  					   AND nvulm.user = '.protect($user->id).'
							   )
			ORDER BY nvul.date DESC
			LIMIT '.$limit
		);


	public function fetchFormFromTemplate($id) {

	}


    function process_subsections($parent_section, $subtpl) {
        global $db, $router;

        $section              = new stdClass();
        $section->parent      = $parent_section->id;
        $section->name        = $subtpl->name;
        $section->sef_name    = $router->encode($section->name);
        $section->subtheme    = $subtpl->subtheme;
        $section->active      = $subtpl->active;
        $section->public      = $subtpl->public;
        $section->rank        = $subtpl->rank;
        $section->page_title  = $subtpl->page_title;
        $section->keywords    = $subtpl->keywords;
        $section->description = $subtpl->description;
        $section->id          = $db->insertObject($section, 'section');
        self::process_section($section, $subtpl);
    }


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


    function audit($method, $class, $statement, $formats, $values, $users_id) {
        $this->method = $method;
        $this->class = $class;
        $this->statement = substr(str_replace("'", "", $statement),0,1000)."n";
        $this->formats = $formats;
        $this->values = $values;
        $this->ip = getRealIpAddr();
        $this->users_id = empty($users_id)?"NULL":$users_id;
        return $this->save();
    }


    public static function data($vars){
        $file = GX_THEME.'/'.$vars.'/themeinfo.php';
        $handle = fopen($file, 'r');
        $data = fread($handle, filesize($file));
        fclose($handle);
        preg_match('/\* Name: (.*)\n\*/U', $data, $matches);
        $d['name'] = $matches[1];
        preg_match('/\* Desc: (.*)\n\*/U', $data, $matches);
        $d['desc'] = $matches[1];
        preg_match('/\* Version: (.*)\n\*/U', $data, $matches);
        $d['version'] = $matches[1];
        preg_match('/\* Build: (.*)\n\*/U', $data, $matches);
        $d['build'] = $matches[1];
        preg_match('/\* Developer: (.*)\n\*/U', $data, $matches);
        $d['developer'] = $matches[1];
        preg_match('/\* URI: (.*)\n\*/U', $data, $matches);
        $d['url'] = $matches[1];
        preg_match('/\* License: (.*)\n\*/U', $data, $matches);
        $d['license'] = $matches[1];
        preg_match('/\* Icon: (.*)\n\*/U', $data, $matches);
        $d['icon'] = $matches[1];
        return $d;
    }


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

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

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


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

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

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


    public function uploadCompanyLogo(Request $request)
    {
        $company = Company::find($request->header('company'));

        $this->authorize('manage company', $company);

        $data = json_decode($request->company_logo);

        if ($data) {
            $company = Company::find($request->header('company'));

            if ($company) {
                $company->clearMediaCollection('logo');

                $company->addMediaFromBase64($data->data)
                    ->usingFileName($data->name)
                    ->toMediaCollection('logo');
            }
        }

        return response()->json([
            'success' => true,
        ]);
    }


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

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


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

		if ($this->tmp) {
			$local = $this->getTempFile();

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

		return $res;
	}