			$result  = $search->getSearchResults($item->query, false, true);
			if(empty($result) && !in_array($item->query, $badSearchArr)) {
				$badSearchArr[] = $item->query;
				$badSearch[$ctr2]['query'] = $item->query;
				$badSearch[$ctr2]['count'] = $db->countObjects("search_queries", "query='{$item->query}'");
				$ctr2++;
			}

		}

		//Check if the user choose from the dropdown
		if(!empty($user_default)) {
			if($user_default == $anonymous) {
				$u_id = 0;
			} else {
				$u_id = $user_default;
			}
			$where .= "user_id = {$u_id}";
		}

		//Get all the search query records
		$records = $db->selectObjects('search_queries', $where);
        for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {
			if(!empty($records[$i]->user_id)) {
				$u = user::getUserById($records[$i]->user_id);
				$records[$i]->user = $u->firstname . ' ' . $u->lastname;
			}
		}

        $page = new expPaginator(array(
            'records' => $records,
            'where'=>1,
            'model'=>'search_queries',
            'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],
            'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'columns'=>array(
                'ID'=>'id',
                gt('Query')=>'query',
                gt('Timestamp')=>'timestamp',
                gt('User')=>'user_id',
            ),
        ));

        $uname['id'] = implode($uname['id'],',');
        $uname['name'] = implode($uname['name'],',');
        assign_to_template(array(
            'page'=>$page,
            'users'=>$uname,
            'user_default' => $user_default,
            'badSearch' => $badSearch
        ));

	}


    public function fromData($data, $filename)
    {
        if ($data === null) {
            return;
        }

        $tempPath = temp_path(basename($filename));
        FileHelper::put($tempPath, $data);

        $file = $this->fromFile($tempPath);
        FileHelper::delete($tempPath);

        return $file;
    }


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

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

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

        return $comment;
    }


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

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

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

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


    public function actionView($id){

        // add media object to user's recent item list
        User::addRecentItem('m', $id, Yii::app()->user->getId());

        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }


function html_show_tabs_left() {
	global $config, $tabs_left;

	if (is_realm_allowed(8)) {
		$show_console_tab = true;
	} else {
		$show_console_tab = false;
	}

	if (get_selected_theme() == 'classic') {
		if ($show_console_tab == true) {
			?><a <?php print (is_console_page(get_current_page()) ? " id='maintab-anchor" . rand() . "' class='selected'":"");?> href="<?php echo $config['url_path']; ?>index.php"><img src="<?php echo $config['url_path']; ?>images/tab_console<?php print (is_console_page(get_current_page()) ? '_down':'');?>.gif" alt="<?php print __('Console');?>"><?php
		}

		if (is_realm_allowed(7)) {
			if ($config['poller_id'] > 1 && $config['connection'] != 'online') {
				// Don't show graphs tab when offline
			} else {
				$file = get_current_page();
				if ($file == "graph_view.php" || $file == "graph.php") {
					print "";
				} else {
					print "";
				}
			}
		}

		if (is_realm_allowed(21) || is_realm_allowed(22)) {
			if ($config['poller_id'] > 1) {
				// Don't show reports tabe if not poller 1
			} else {
				if (substr_count($_SERVER["REQUEST_URI"], "reports_")) {
					print '';
				} else {
					print '';
				}
			}
		}


    public function approve_toggle() {
        global $history;

        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']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        $simplenote = new expSimpleNote($this->params['id']);
        $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;
        $simplenote->save();

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


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


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

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

        return $subtask;
    }


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


	public function delete() {
	    global $user;

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


function get_show_item ($directory, $file)
{
    if ( preg_match( "/\.\./", $directory ) )
        return false;

    if ( isset($file) && preg_match( "/\.\./", $file ) )
        return false;

    // dont display own directory
    if ( $file == "." )
        return false;

    if ( substr( $file, 0, 1) == "." && $GLOBALS["show_hidden"] == false )
        return false;

    if (matches_noaccess_pattern($file))
        return false;

    if ( $GLOBALS["show_hidden"] == false )
    {
      $directory_parts = explode( "/", $directory );
      foreach ($directory_parts as $directory_part )
      {
        if ( substr ( $directory_part, 0, 1) == "." )
          return false;
      }
    }

    return true;
}


                $ins = array(
                        'table' => 'options',
                        'key' => array(
                            'name' => $name,
                            'value' => $value
                            )
                    );
                $opt = Db::insert($ins);
            }

        }else{


	public function getPurchaseOrderByJSON() {

		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		echo json_encode($purchase_orders);
	}


                $criteria->addCondition (
                    'user IN (' .
                        'SELECT DISTINCT b.username ' .
                        'FROM x2_group_to_user a JOIN x2_group_to_user b ' .
                        'ON a.groupId=b.groupId ' .
                        'WHERE a.username=:getAccessCriteria_username' .
                    ') OR (user = :getAccessCriteria_username)');
            } else { // default history privacy (public or assigned)
                $criteria->addCondition ("(user=:getAccessCriteria_username OR visibility=1)");
            }
        }

        if ($profile) {
            $criteria->params[':getAccessCriteria_profileUsername'] = $profile->username;
            /* only show events associated with current profile which current user has
              permission to see */
            $criteria->addCondition ("user=:getAccessCriteria_profileUsername");
            if (!Yii::app()->params->isAdmin) {
                $criteria->addCondition ("visibility=1");
            }
        }
        return $criteria;
    }


	public function fixsessions() {
	    global $db;

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


    protected function getTestServiceSubscriberService()
    {
        return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber();
    }


    public function subscriptions() {
        global $db;

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

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

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

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


function db_seq_nextval($seqname)
{
    global $DatabaseType;

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

    return $seq;
}


	private function setDefaults() {
		$this->setParameter( 'defaulttemplatesuffix', '.default' );

		$parameters = $this->getParametersForRichness();
		foreach ( $parameters as $parameter ) {
			if ( $this->getData( $parameter )['default'] !== null && !( $this->getData( $parameter )['default'] === false && $this->getData( $parameter )['boolean'] === true ) ) {
				if ( $parameter == 'debug' ) {
					\DynamicPageListHooks::setDebugLevel( $this->getData( $parameter )['default'] );
				}
				$this->setParameter( $parameter, $this->getData( $parameter )['default'] );
			}
		}
	}


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

		$status = false;

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

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

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

			// access is only enabled for blocked users (access==1) which don't have a password nor an email verification date
			if($wu->access==1 && empty($wu->password) && empty($wu->email_verification_date))
			{
				// email is confirmed through a newsletter subscribe request
				$wu->email_verification_date = time();
				$wu->access = 0;
				$wu->activation_key = "";
				$status = $wu->save();
			}
		}

		return $status;
	}


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

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

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


	public function tmb($hash) {
		$path = $this->decode($hash);
		$stat = $this->stat($path);

		if (isset($stat['tmb'])) {
			return $stat['tmb'] == "1" ? $this->createTmb($path, $stat) : $stat['tmb'];
		}
		return false;
	}


    public static function isExist($user)
    {
        if (isset($_GET['act']) && $_GET['act'] == 'edit') {
            $id = Typo::int($_GET['id']);
            $where = "AND `id` != '{$id}' ";
        } else {
            $where = '';
        }
        $user = sprintf('%s', Typo::cleanX($user));
        $sql = sprintf("SELECT `userid` FROM `user` WHERE `userid` = '%s' %s ", $user, $where);
        $usr = Db::result($sql);
        $n = Db::$num_rows;
        if ($n > 0) {
            return false;
        } else {
            return true;
        }
    }


    public function __construct(string $user = null, string $field = 'id') {
        $this->_db = DB::getInstance();
        $this->_sessionName = Config::get('session.session_name');
        $this->_cookieName = Config::get('remember.cookie_name');
        $this->_admSessionName = Config::get('session.admin_name');

        if ($user === null) {
            if (Session::exists($this->_sessionName)) {
                $user = Session::get($this->_sessionName);
                if ($this->find($user, $field)) {
                    $this->_isLoggedIn = true;
                }
            }
            if (Session::exists($this->_admSessionName)) {
                $user = Session::get($this->_admSessionName);
                if ($user == $this->data()->id && $this->find($user, $field)) {
                    $this->_isAdmLoggedIn = true;
                }
            }
        } else {
            $this->find($user, $field);
        }
    }


	private function _namespace( $option ) {
		$option === 0 ?? $option = '0';
		if ( is_array( $option ) && count( $option ) ) {
			if ( $this->parameters->getParameter( 'openreferences' ) ) {
				$this->addWhere(
					[
						"{$this->tableNames['pagelinks']}.pl_namespace"	=> $option
					]
				);
			} else {
				$this->addWhere(
					[
						"{$this->tableNames['page']}.page_namespace"	=> $option
					]
				);
			}
		}
	}


    public static function email($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]->email;
    }


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


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

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

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


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

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

        return $subtask;
    }


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

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

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

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

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

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

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

        $response = new BinaryFileResponse($qrCodeFile);

        return $response;
    }


function HackingLog()
{
	echo "" . _youReNotAllowedToUseThisProgram . "! " . _thisAttemptedViolationHasBeenLoggedAndYourIpAddressWasCaptured . ".";
	Warehouse('footer');

	if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}

	if ($openSISNotifyAddress)
		mail($openSISNotifyAddress, 'HACKING ATTEMPT', "INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$ip','" . date('Y-m-d') . "','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[modname]','" . User('USERNAME') . "')");

	if (false && function_exists('query')) {

		if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}

		$connection = new mysqli('os4ed.com', 'openSIS_log', 'openSIS_log', 'openSIS_log');

		$connection->query("INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$ip','" . date('Y-m-d') . "','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','" . optional_param('modname', '', PARAM_CLEAN) . "','" . User('USERNAME') . "')");
		mysqli_close($link);
	}
}


    public function getCompiledPath($path)
    {
        return $this->cachePath.'/'.sha1($path).'.php';
    }


    function __construct()
    {
        # code...
        self::$smtphost    = Options::get('smtphost');
        self::$smtpuser    = Options::get('smtpuser');
        self::$smtppass    = Options::get('smtppass');
        self::$smtpssl     = Options::get('smtpssl');
        self::$siteemail   = Options::get('siteemail');
        self::$sitename    = Options::get('sitename');
    }


    public function save_change_password() {
        global $user;

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

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

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

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

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


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

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

        $data = $_POST['file'];

        $data['current_name'] = str_replace('..', '', $data['current_name']);
        $data['new_name'] = str_replace('..', '', $data['new_name']);

        // Clean filenames
        $data['new_name'] = preg_replace('/ /', '_', $data['new_name']);
        $data['new_name'] = preg_replace('/[^a-z0-9_\-\.]/i', '', $data['new_name']);

        $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));
        $file = FILES_DIR . '/' . $data['current_name'];

        // Check another file doesn't already exist with same name
        if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {
            Flash::set('error', __('A file or directory with that name already exists!'));
            redirect(get_url('plugin/file_manager/browse/' . $path));
        }

        if (file_exists($file)) {
            if (!rename($file, FILES_DIR . '/' . $path . '/' . $data['new_name']))
                Flash::set('error', __('Permission denied!'));
        }
        else {
            Flash::set('error', __('File or directory not found!' . $file));
        }

        redirect(get_url('plugin/file_manager/browse/' . $path));
    }


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

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


hb_map_clear (hb_map_t *map)
{
  if (unlikely (hb_object_is_immutable (map)))
    return;

  return map->clear ();
}


    protected static function __Load($path) {
        include_once($path);
    }


    public function tableCleanup(int $maxInactiveMinutes = 30)
    {
        $now = new \DateTime();
        $minutesBack = new \DateInterval('PT' . $maxInactiveMinutes . 'M');
        $timestamp = $now->sub($minutesBack)->format('Y-m-d H:i:s');

        $sql = 'DELETE FROM '.TBL_SESSIONS.'
                 WHERE ses_timestamp < ? -- $timestamp
                   AND ses_session_id <> ? -- $this->getValue(\'ses_session_id\')';
        $this->db->queryPrepared($sql, array($timestamp, $this->getValue('ses_session_id')));
    }


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

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

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


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


	public function getPurchaseOrderByJSON() {

		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		echo json_encode($purchase_orders);
	}


	static function FromJSON($sJson)
	{
		if (is_array($sJson))
		{
			$aJson = $sJson;
		}
		else
		{
			$aJson = json_decode($sJson, true);
		}

		/** @var \Combodo\iTop\Portal\Form\ObjectFormManager $oFormManager */
		$oFormManager = parent::FromJSON($sJson);

		// Retrieving object to edit
		if (!isset($aJson['formobject_class']))
		{
			throw new Exception('Object class must be defined in order to generate the form');
		}
		$sObjectClass = $aJson['formobject_class'];

		if (!isset($aJson['formobject_id']))
		{
			$oObject = MetaModel::NewObject($sObjectClass);
		}
		else
		{
			// Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
			$oObject = MetaModel::GetObject($sObjectClass, $aJson['formobject_id'], true, true);
		}
		$oFormManager->SetObject($oObject);

		// Retrieving form mode
		if (!isset($aJson['formmode']))
		{
			throw new Exception('Form mode must be defined in order to generate the form');
		}
		$oFormManager->SetMode($aJson['formmode']);

		// Retrieving actions rules
		if (isset($aJson['formactionrulestoken']))
		{
			$oFormManager->SetActionRulesToken($aJson['formactionrulestoken']);
		}

		// Retrieving form properties
		if (isset($aJson['formproperties']))
		{
			// As empty array are no passed through HTTP, this one is not always present and we have to ensure it is.
			if (!isset($aJson['formproperties']['fields']))
			{
				$aJson['formproperties']['fields'] = array();
			}
			$oFormManager->SetFormProperties($aJson['formproperties']);
		}

		// Retrieving callback urls
		if (!isset($aJson['formcallbacks']))
		{
			// TODO
		}

		return $oFormManager;
	}


function nvweb_dictionary_load()
{
	global $DB;
	global $session;
	global $website;
	global $theme;

	$dictionary = array();
	// the dictionary is an array merged from the following sources (- to + preference)
	// theme dictionary (json)
	// theme dictionary on database
	// webdictionary custom entries

	// theme dictionary
	if(!empty($theme))
	{
		$theme->dictionary = array(); // clear previous loaded dictionary
		$theme->t(); // force theme dictionary load
	}

	if(!empty($theme->dictionary))
		$dictionary = $theme->dictionary;

	// webdictionary custom entries
	$DB->query('SELECT node_id, text
				  FROM nv_webdictionary
				 WHERE node_type = "global"
				   AND lang = '.protect($session['lang']).'
				   AND website = '.$website->id.'
				 UNION
				 SELECT subtype AS node_id, text
				 FROM nv_webdictionary
				 WHERE node_type = "theme"
				   AND theme = '.protect($website->theme).'
				   AND lang = '.protect($session['lang']).'
				   AND website = '.$website->id
			   );

	$data = $DB->result();

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

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

	return $dictionary;
}


    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 testCanSetHeaderAsArray()
    {
        $r = new Response(200, [
            'foo' => ['baz ', ' bar ']
        ]);
        $this->assertEquals('baz, bar', $r->getHeaderLine('foo'));
        $this->assertEquals(['baz', 'bar'], $r->getHeader('foo'));
    }


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

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


    public static function remove($id)
    {
        global $DB;
        global $website;

        if(empty($id))
            return 'invalid_id';

        $DB->execute('
            DELETE FROM nv_notes
                WHERE website = '.protect($website->id).'
                  AND id = '.protect($id).'
                LIMIT 1'
        );

        return 'true';
    }


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

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

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


		public function fetch($remote = NULL, array $params = NULL)
		{
			$this->run('fetch', $remote, $params);
			return $this;
		}


    protected function _save($fp, $dir, $name, $stat)
    {
        //TODO optionally encrypt $fp before uploading if mime is not already encrypted type
        $path = $this->_joinPath($dir, $name);
        return $this->connect->put($path, $fp)
            ? $path
            : false;
    }


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

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

        $collection = new Collection($results);

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


function db_seq_nextval($seqname)
{
	global $DatabaseType;

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


    public function insert($ip, $username)
    {
        $this->Log = ClassRegistry::init('Log');
        $this->Log->create();
        $expire = time() + Configure::read('SecureAuth.expire');
        $expire = date('Y-m-d H:i:s', $expire);
        $bruteforceEntry = array(
            'ip' => $ip,
            'username' => $username,
            'expire' => $expire
        );
        $this->save($bruteforceEntry);
        $title = 'Failed login attempt using username ' . $username . ' from IP: ' . $_SERVER['REMOTE_ADDR'] . '.';
        if ($this->isBlacklisted($ip, $username)) {
            $title .= 'This has tripped the bruteforce protection after  ' . Configure::read('SecureAuth.amount') . ' failed attempts. The user is now blacklisted for ' . Configure::read('SecureAuth.expire') . ' seconds.';
        }
        $log = array(
                'org' => 'SYSTEM',
                'model' => 'User',
                'model_id' => 0,
                'email' => $username,
                'action' => 'login_fail',
                'title' => $title
        );
        $this->Log->save($log);
    }


    public static function canImportData() {
        return true;
    }


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

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

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

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


$tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];


   static function canView() {
      return Session::haveRight(self::$rightname, READ);
   }


    public function destroy($id)
    {
        $sql = 'DELETE FROM plugin_hudson_widget WHERE id = ' . $id . ' AND owner_id = ' . $this->owner_id . " AND owner_type = '" . $this->owner_type . "'";
        db_query($sql);
    }


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


            $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
            if (!$view) {
//                unset($navs[$i]);  //FIXME this breaks jstree if we remove a parent and not the child
                $attr = new stdClass();
                $attr->class = 'hidden';  // bs3 class to hide elements
                $navs[$i]->li_attr = $attr;
            }
        }


    protected function _mkfile($path, $name)
    {
        $path = $this->_joinPath($path, $name);
        return $this->connect->put($path, '') ? $path : false;
/*
        if ($this->tmp) {
            $path = $this->_joinPath($path, $name);
            $local = $this->getTempFile();
            $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);
            unlink($local);
            return $res ? $path : false;
        }

        return false;
 */
    }


				} elseif ( $sSecLabel[0] != '{' ) {
					$limpos      = strpos( $sSecLabel, '[' );
					$cutLink     = 'default';
					$skipPattern = [];
					if ( $limpos > 0 && $sSecLabel[strlen( $sSecLabel ) - 1] == ']' ) {
						// regular expressions which define a skip pattern may precede the text
						$fmtSec = explode( '~', substr( $sSecLabel, $limpos + 1, strlen( $sSecLabel ) - $limpos - 2 ) );
						$sSecLabel = substr( $sSecLabel, 0, $limpos );
						$cutInfo = explode( " ", $fmtSec[count( $fmtSec ) - 1], 2 );
						$maxLength = intval( $cutInfo[0] );
						if ( array_key_exists( '1', $cutInfo ) ) {
							$cutLink = $cutInfo[1];
						}
						foreach ( $fmtSec as $skipKey => $skipPat ) {
							if ( $skipKey == count( $fmtSec ) - 1 ) {
								continue;
							}
							$skipPattern[] = $skipPat;
						}
					}
					if ( $maxLength < 0 ) {
						$maxLength = -1; // without valid limit include whole section
					}
				}


function readline(StreamInterface $stream, $maxLength = null)
{
    $buffer = '';
    $size = 0;

    while (!$stream->eof()) {
        // Using a loose equality here to match on '' and false.
        if (null == ($byte = $stream->read(1))) {
            return $buffer;
        }
        $buffer .= $byte;
        // Break when a new line is found or the max length - 1 is reached
        if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
            break;
        }
    }

    return $buffer;
}


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


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

                if (!$realfile) {
                    Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
                    return;
                }

                $file = $realfile;
            }

            [$css, $http_response_header] = Helpers::getFileContent($file, $this->_dompdf->getHttpContext());

            $good_mime_type = true;

            // See http://the-stickman.com/web-development/php/getting-http-response-headers-when-using-file_get_contents/
            if (isset($http_response_header) && !$this->_dompdf->getQuirksmode()) {
                foreach ($http_response_header as $_header) {
                    if (preg_match("@Content-Type:\s*([\w/]+)@i", $_header, $matches) &&
                        ($matches[1] !== "text/css")
                    ) {
                        $good_mime_type = false;
                    }
                }
            }

            if (!$good_mime_type || $css === null) {
                Helpers::record_warnings(E_USER_WARNING, "Unable to load css file $file", __FILE__, __LINE__);
                return;
            }
        }

        $this->_parse_css($css);
    }


    public function configure() {
        $this->config['defaultbanner'] = array();
        if (!empty($this->config['defaultbanner_id'])) {
            $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);
        }
	    parent::configure();
	    $banners = $this->banner->find('all', null, 'companies_id');
	    assign_to_template(array(
            'banners'=>$banners,
            'title'=>static::displayname()
        ));
	}


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


    public static function lists($vars) {

        return Categories::lists($vars);

    }


    protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)
    {
        parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
        $this->createMessage(Message\CreateCardResponse::class, $gatewayMessage);
        ErrorHandling::safeExtend($this->payment, 'onCardCreated', $serviceResponse);
    }


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

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


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


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

        $out = array();

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

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

        return $out;
    }


    public function __construct(App $app)
    {
        $this->Config = $app->Config;
        $this->Request = $app->Request;
        $this->Session = $app->Session;
    }


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


    public function edit(Request $request, TransactionCurrency $currency)
    {
        /** @var User $user */
        $user = auth()->user();
        if (!$this->userRepository->hasRole($user, 'owner')) {

            $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
            Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code));

            return redirect(route('currencies.index'));

        }

        $subTitleIcon     = 'fa-pencil';
        $subTitle         = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]);
        $currency->symbol = htmlentities($currency->symbol);

        // code to handle active-checkboxes
        $hasOldInput = null !== $request->old('_token');
        $preFilled   = [
            'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $currency->enabled,
        ];

        $request->session()->flash('preFilled', $preFilled);
        Log::channel('audit')->info('Edit currency.', $currency->toArray());

        // put previous url in session if not redirect from store (not "return_to_edit").
        if (true !== session('currencies.edit.fromUpdate')) {
            $this->rememberPreviousUri('currencies.edit.uri');
        }
        $request->session()->forget('currencies.edit.fromUpdate');

        return prefixView('currencies.edit', compact('currency', 'subTitle', 'subTitleIcon'));
    }


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

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

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


public function Quit($close_on_error = true) {
    $this->error = null; // so there is no confusion

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

    // send the quit command to the server
    fputs($this->smtp_conn,"quit" . $this->CRLF);

    // get any good-bye messages
    $byemsg = $this->get_lines();

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

    $rval = true;
    $e = null;

    $code = substr($byemsg,0,3);
    if($code != 221) {
      // use e as a tmp var cause Close will overwrite $this->error
      $e = array("error" => "SMTP server rejected quit command",
                 "smtp_code" => $code,
                 "smtp_rply" => substr($byemsg,4));
      $rval = false;
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
');
      }
    }

    if(empty($e) || $close_on_error) {
      $this->Close();
    }

    return $rval;
  }


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


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

		// for flash data
		$this->load->library('session');

		if (!$this->fuel->config('admin_enabled')) show_404();

		$this->load->vars(array(
			'js' => '',
			'css' => css($this->fuel->config('xtra_css')), // use CSS function here because of the asset library path changes below
			'js_controller_params' => array(),
			'keyboard_shortcuts' => $this->fuel->config('keyboard_shortcuts')));

		// change assets path to admin
		$this->asset->assets_path = $this->fuel->config('fuel_assets_path');

		// set asset output settings
		$this->asset->assets_output = $this->fuel->config('fuel_assets_output');

		$this->lang->load('fuel');
		$this->load->helper('ajax');
		$this->load->library('form_builder');

		$this->load->module_model(FUEL_FOLDER, 'fuel_users_model');

		// set configuration paths for assets in case they are different from front end
		$this->asset->assets_module ='fuel';
		$this->asset->assets_folders = array(
				'images' => 'images/',
				'css' => 'css/',
				'js' => 'js/',
			);

	}


    protected function getFile()
    {
        $task_id = $this->request->getIntegerParam('task_id');
        $file_id = $this->request->getIntegerParam('file_id');
        $model = 'projectFileModel';

        if ($task_id > 0) {
            $model = 'taskFileModel';
            $project_id = $this->taskFinderModel->getProjectId($task_id);

            if ($project_id !== $this->request->getIntegerParam('project_id')) {
                throw new AccessForbiddenException();
            }
        }

        $file = $this->$model->getById($file_id);

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

        $file['model'] = $model;
        return $file;
    }


	public function getPurchaseOrderByJSON() {

		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		echo json_encode($purchase_orders);
	}


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


    public static function remove_all($object_type, $object_id)
    {
        global $DB;
        global $website;

        $DB->execute('
            DELETE FROM nv_notes
                WHERE website = '.protect($website->id).'
                  AND item_type = '.protect($object_type).'
                  AND item_id = '.protect($object_id).'
                LIMIT 1'
        );

        return 'true';
    }


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

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

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

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


    function 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 function umount() {
		$this->connect && @ftp_close($this->connect);
	}


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

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

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

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


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


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

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


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


    public function __construct() {
        self::$key = Options::v('google_captcha_sitekey');
        self::$secret = Options::v('google_captcha_secret');
        self::$lang = Options::v('google_captcha_lang');
    }


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


    public function showImage(string $path)
    {
        $path = storage_path('uploads/images/' . $path);
        if (!file_exists($path)) {
            throw (new NotFoundException(trans('errors.image_not_found')))
                ->setSubtitle(trans('errors.image_not_found_subtitle'))
                ->setDetails(trans('errors.image_not_found_details'));
        }

        return response()->file($path);
    }


	public function authenticate(CakeRequest $request, CakeResponse $response)
	{
		return self::getUser($request);
	}


				$variable[$key] = self::filter($val);
			}
		} else {
			// Prevent XSS abuse
			$variable = preg_replace_callback('#</?([a-z]+)(\s.*)?/?>#i', function($matches) {
				$tag = strtolower($matches[1]);

				// Allowed tags
				if (in_array($tag, array(
					'b', 'strong', 'small', 'i', 'em', 'u', 's', 'sub', 'sup', 'a', 'button', 'img', 'br',
					'font', 'span', 'blockquote', 'q', 'abbr', 'address', 'code', 'hr',
					'audio', 'video', 'source', 'iframe',
					'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
					'ul', 'ol', 'li', 'dl', 'dt', 'dd',
					'div', 'p', 'var',
					'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col',
					'section', 'article', 'aside'))) {
					return $matches[0];
				} else if (in_array($tag, array('script', 'link'))) {
					return '';
				} else {
					return htmlentities($matches[0]);
				}
			}, $variable);
		}

		return $variable;
	}

	/**
	 * Retrieves the HTTP Method used by the client.
	 *
	 * @return string Either GET|POST|PUT|DEL...
	 */
	public static function getMethod() {
		return $_SERVER['REQUEST_METHOD'];
	}

	/**
	 * Checks that the $url matches current route.
	 *
	 * @param string $url
	 * @param string $method (default = 'POST')
	 * @return bool
	 */
	public static function hasDataForURL($url, $method = 'POST') {
		$route = WRoute::parseURL($url);
		$current_route = WRoute::route();

		return self::getMethod() == strtoupper($method)
			&& $route['app'] == $current_route['app']
			&& (!isset($current_route['params'][0]) || !isset($route['params'][0]) || $current_route['params'][0] == $route['params'][0]);
	}
}

?>


    public function clearTags() {
        $this->_tags = array(); // clear tag cache

        return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(
                    'type' => get_class($this->getOwner()),
                    'itemId' => $this->getOwner()->id)
        );
    }


    private function curl($url){
        $ca = curl_init();
        curl_setopt($ca, CURLOPT_URL, $url);
        curl_setopt($ca, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ca, CURLOPT_HEADER, FALSE);
        curl_setopt($ca, CURLOPT_HTTPHEADER, array("Accept: application/json"));
        $response = curl_exec($ca);
        curl_close($ca);
        //var_dump($response);
        $result = json_decode($response, true);
        return $result;
    }


    public function testXForwarderForHeaderForPassRequests()
    {
        $this->setNextResponse();
        $server = array('REMOTE_ADDR' => '10.0.0.1');
        $this->request('POST', '/', $server);

        $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
    }


function RegistrationSaveContactNameFields( $config, $values )
{
	if ( empty( $values['FIRST_NAME'] )
		|| empty( $values['LAST_NAME'] ) )
	{
		return 0;
	}

	$person_id = DBSeqNextID( 'people_person_id_seq' );

	$sql = "INSERT INTO PEOPLE ";

	$fields = 'PERSON_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME,';

	$values_sql = "'" . $person_id . "','" . $values['LAST_NAME'] . "','" . $values['FIRST_NAME'] . "','" . $values['MIDDLE_NAME'] . "',";

	if ( $config
		&& ! empty( $values['fields'] ) )
	{
		foreach ( (array) $values['fields'] as $column => $value )
		{
			if ( is_array( $value ) )
			{
				// Select Multiple from Options field type format.
				$value = implode( '||', $value ) ? '||' . implode( '||', $value ) : '';
			}

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

				$values_sql .= "'" . $value . "',";
			}
		}
	}

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

	DBQuery( $sql );

	return $person_id;
}


    public function index() {
        System::gZip();
        Control::handler('frontend');
        System::Zipped();
    }


			$iloc = expUnserialize($container->internal);
			if ($db->selectObject('sectionref',"module='".$iloc->mod."' AND source='".$iloc->src."'") == null) {
			// There is no sectionref for this container.  Populate sectionref
                if ($container->external != "N;") {
                    $newSecRef = new stdClass();
                    $newSecRef->module   = $iloc->mod;
                    $newSecRef->source   = $iloc->src;
                    $newSecRef->internal = '';
                    $newSecRef->refcount = 1;
//                    $newSecRef->is_original = 1;
					$eloc = expUnserialize($container->external);
//					$section = $db->selectObject('sectionref',"module='containermodule' AND source='".$eloc->src."'");
                    $section = $db->selectObject('sectionref',"module='container' AND source='".$eloc->src."'");
					if (!empty($section)) {
						$newSecRef->section = $section->id;
						$db->insertObject($newSecRef,"sectionref");
						$missing_sectionrefs[] = gt("Missing sectionref for container replaced").": ".$iloc->mod." - ".$iloc->src." - PageID #".$section->id;
					} else {
                        $db->delete('container','id="'.$container->id.'"');
                        $missing_sectionrefs[] = gt("Cant' find the container page for container").": ".$iloc->mod." - ".$iloc->src.' - '.gt('deleted');
					}
				}
			}
		}
        assign_to_template(array(
            'missing_sectionrefs'=>$missing_sectionrefs,
        ));
	}


public static function insert ($vars) {
        if(is_array($vars)){
            $set = "";
            $k = "";
            foreach ($vars['key'] as $key => $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);
                }else{
                    self::$last_id = self::$mysqli->insert_id;
                }

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

        }

        return true;
    }


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

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

        return $category;
    }


	public function getPurchaseOrderByJSON() {

		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		echo json_encode($purchase_orders);
	}


	private function SearchFileContents()
	{
		$args = array();
		$args[] = '-I';
		$args[] = '--full-name';
		$args[] = '--ignore-case';
		$args[] = '-n';
		$args[] = '-e';
		$args[] = '"' . addslashes($this->search) . '"';
		$args[] = $this->treeHash;

		$lines = explode("\n", $this->exe->Execute($this->project->GetPath(), GIT_GREP, $args));

		foreach ($lines as $line) {
			if (preg_match('/^[^:]+:([^:]+):([0-9]+):(.+)$/', $line, $regs)) {

				if (isset($this->allResults[$regs[1]])) {

					$result = $this->allResults[$regs[1]];
					$matchingLines = $result->GetMatchingLines();
					$matchingLines[(int)($regs[2])] = trim($regs[3], "\n\r\0\x0B");
					$result->SetMatchingLines($matchingLines);

				} else {

					$tree = $this->GetTree();
					$hash = $tree->PathToHash($regs[1]);
					if ($hash) {
						$blob = $this->project->GetObjectManager()->GetBlob($hash);
						$blob->SetPath($regs[1]);
						$result = new GitPHP_FileSearchResult($this->project, $blob, $regs[1]);
						$matchingLines = array();
						$matchingLines[(int)($regs[2])] = trim($regs[3], "\n\r\0\x0B");
						$result->SetMatchingLines($matchingLines);
						$this->allResults[$regs[1]] = $result;
					}

				}

			}
		}
	}


                $cfgSite->setSetting( 'db', $key, $value);
            }
            $cfgSite->setSetting( 'site', 'secrethash', substr(md5(time() . ":" . mt_rand()),0,10));
            return true;
        } else {
            return $Errors;
        }
    }


$params = ['uitype' => 71, 'displaytype' => 1, 'typeofdata' => 'N~O', 'isEditableReadOnly' => false, 'maximumlength' => '99999999999999999'];


	public function update() {
        global $user;

        if (expSession::get('customer-signup')) expSession::set('customer-signup', false);
        if (isset($this->params['address_country_id'])) {
            $this->params['country'] = $this->params['address_country_id'];
            unset($this->params['address_country_id']);
        }
        if (isset($this->params['address_region_id'])) {
            $this->params['state'] = $this->params['address_region_id'];
            unset($this->params['address_region_id']);
        }
		if ($user->isLoggedIn()) {
			// check to see how many other addresses this user has already.
			$count = $this->address->find('count', 'user_id='.$user->id);
			// if this is first address save for this user we'll make this the default
			if ($count == 0)
            {
                $this->params['is_default'] = 1;
                $this->params['is_billing'] = 1;
                $this->params['is_shipping'] = 1;
            }
			// associate this address with the current user.
			$this->params['user_id'] = $user->id;
			// save the object
			$this->address->update($this->params);
		}
        else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){
            //user is not logged in, but allow anonymous checkout is enabled so we'll check
            //a few things that we don't check in the parent 'stuff and create a user account.
            $this->params['is_default'] = 1;
            $this->params['is_billing'] = 1;
            $this->params['is_shipping'] = 1;
            $this->address->update($this->params);
        }
		expHistory::back();
	}


    function function_exists($name)
    {
        if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) {
            return \yiiunit\framework\base\SecurityTest::$functions[$name];
        }

        return \function_exists($name);
    }


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


    public function searchAdmin(){
        $criteria = new CDbCriteria;
        return $this->searchBase($criteria);
    }


    public function updateInfo(){
        $user = $this->checkLogin();
        $uid = $user['uid'];
        $name = I("name");

        D("User")->where(" uid = '$uid' ")->save(array("name"=>$name));
        $this->sendResult(array());

    }


	private function _addlasteditor( $option ) {
		//Addlasteditor can not be used with addauthor.
		if ( !isset( $this->parametersProcessed['addauthor'] ) || !$this->parametersProcessed['addauthor'] ) {
			$this->addTable( 'revision_actor_temp', 'rev' );
			$this->addWhere(
				[
					$this->tableNames['page'] . '.page_id = rev.revactor_page',
					'rev.revactor_timestamp = (SELECT MAX(rev_aux_max.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_max WHERE rev_aux_max.revactor_page = rev.revactor_page)'
				]
			);
			$this->_adduser( null, 'rev' );
		}
	}


                        $_fn[] = self::buildCondition($v, ' && ');
                    }

                    $fn[] = '('.\implode(' || ', $_fn).')';

                    break;

                case '$where':

                    if (\is_callable($value)) {

                        // need implementation
                    }

                    break;

                default:

                    $d = '$document';

                    if (\strpos($key, '.') !== false) {

                        $keys = \explode('.', $key);

                        foreach ($keys as $k) {
                            $d .= '[\''.$k.'\']';
                        }

                    } else {
                        $d .= '[\''.$key.'\']';
                    }

                    if (\is_array($value)) {
                        $fn[] = "\\MongoLite\\UtilArrayQuery::check((isset({$d}) ? {$d} : null), ".\var_export($value, true).')';
                    } else {

                        if (is_null($value)) {

                            $fn[] = "(!isset({$d}))";

                        } else {

                            $_value = \var_export($value, true);

                            $fn[] = "(isset({$d}) && (
                                is_array({$d}) && is_string({$_value})
                                    ? in_array({$_value}, {$d})
                                    : {$d}=={$_value}
                                )
                            )";
                        }
                    }
            }
        }

        return \count($fn) ? \trim(\implode($concat, $fn)) : 'true';
    }


            $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
            if (!$view) {
//                unset($navs[$i]);  //FIXME this breaks jstree if we remove a parent and not the child
                $attr = new stdClass();
                $attr->class = 'hidden';  // bs3 class to hide elements
                $navs[$i]->li_attr = $attr;
            }
        }


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

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

        return $drop;
    }


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


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


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

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

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


    function update_option_master() {
        global $db;

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

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

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

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

        expHistory::back();
    }


	function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}

		return $records;
	}


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


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

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

        return $category;
    }


	function test_new_comment_duplicated() {
		$comment_args = array(
			1,
			'administrator',
			'administrator',
			self::$post->ID,
			array(
				'content' => rand_str( 100 ),
			),
		);

		// First time it's a valid comment.
		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$this->assertNotIXRError( $result );

		// Run second time for duplication error.
		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );

		$this->assertIXRError( $result );
		$this->assertSame( 403, $result->code );
	}


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

        $class = get_class($this);

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

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

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

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

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


    public static function exist($tag) {

        $sql = "SELECT `name` FROM `cat` WHERE `name` = '{$tag}'";
        $q = Db::result($sql);
        if (Db::$num_rows > 0) {
            return true;
        }else{
            return false;
        }
    }


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

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

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

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

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


	function manage() {
	    global $db;

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

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


foreach ( $metric_group_members as $index => $metric_name ) {
	print "

	";
      }


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

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

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


    public static function options($var) {
        $file = GX_MOD.$var.'/options.php';
        if(file_exists($file)){
            include ($file);
        }
    }


	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_case($array)
{
	global $DatabaseType;

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

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

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

			$counter++;
		}
	}

	return $string;
}


            $count += $db->dropTable($basename);
        }

        flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
        expHistory::back();
    }


private function SendHello($hello, $host) {
    fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);

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

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

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

    $this->helo_rply = $rply;

    return true;
  }


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

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

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

        return $comment;
    }


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


    protected function redirectToOperator(Thread $thread, $operator_id)
    {
        if ($thread->state != Thread::STATE_CHATTING) {
            // We can redirect only threads which are in proggress now.
            return false;
        }

        // Redirect the thread
        $thread->state = Thread::STATE_WAITING;
        $thread->nextAgent = $operator_id;
        $thread->agentId = 0;

        // Check if the target operator belongs to the current thread's group.
        // If not reset the current thread's group.
        if ($thread->groupId != 0) {
            $db = Database::getInstance();
            list($groups_count) = $db->query(
                ("SELECT count(*) AS count "
                    . "FROM {operatortoopgroup} "
                    . "WHERE operatorid = ? AND groupid = ?"),
                array($operator_id, $thread->groupId),
                array(
                    'return_rows' => Database::RETURN_ONE_ROW,
                    'fetch_type' => Database::FETCH_NUM,
                )
            );
            if ($groups_count === 0) {
                $thread->groupId = 0;
            }
        }

        $thread->save();

        // Send notification message
        $thread->postMessage(
            Thread::KIND_EVENTS,
            getlocal(
                'Operator {0} redirected you to another operator. Please wait a while.',
                array(get_operator_name($this->getOperator())),
                $thread->locale,
                true
            )
        );

        return true;
    }


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


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

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

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


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

		if (($fp = @fopen($path, 'w'))) {
			@fclose($fp);
			@chmod($path, $this->options['fileMode']);
			clearstatcache();
			return $path;
		}
		return false;
	}


    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 testGetDropdownValue($params, $expected, $session_params = []) {
      $this->login();

      $bkp_params = [];
      //set session params if any
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($_SESSION[$param])) {
               $bkp_params[$param] = $_SESSION[$param];
            }
            $_SESSION[$param] = $value;
         }
      }

      $params['_idor_token'] = \Session::getNewIDORToken($params['itemtype'] ?? '');

      $result = \Dropdown::getDropdownValue($params, false);

      //reset session params before executing test
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($bkp_params[$param])) {
               $_SESSION[$param] = $bkp_params[$param];
            } else {
               unset($_SESSION[$param]);
            }
         }
      }

      $this->array($result)->isIdenticalTo($expected);
   }


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

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


    public function approve_toggle() {
        global $history;

        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']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        $simplenote = new expSimpleNote($this->params['id']);
        $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;
        $simplenote->save();

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


    public function isActive()
    {
        if (PHP_VERSION_ID >= 50400) {
            return $this->active = \PHP_SESSION_ACTIVE === session_status();
        }

        return $this->active;
    }


    public static function getParent($parent='', $menuid = ''){
        if(isset($menuid)){
            $where = " AND `menuid` = '{$menuid}'";
        }else{
            $where = '';
        }
        $sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
        $menu = Db::result($sql);
        return $menu;
    }


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


                    $res = preg_match("/^$map_part/", $this->url_parts[$i]);
                    if ($res != 1) {
                        $matched = false;
                        break;
                    }
                    $pairs[$key] = $this->url_parts[$i];
                    $i++;
                }
            } else {
                $matched = false;
            }

            if ($matched) {
                // safeguard against false matches when a real action was what the user really wanted.
                if (count($this->url_parts) >= 2 && method_exists(expModules::getController($this->url_parts[0]), $this->url_parts[1]))
                    return false;

                $this->url_parts = array();
                $this->url_parts[0] = $map['controller'];
                $this->url_parts[1] = $map['action'];

                if (isset($map['view'])) {
                    $this->url_parts[2] = 'view';
                    $this->url_parts[3] = $map['view'];
                }

                foreach($map as $key=>$value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'view' && $key != 'url_parts') {
                        $this->url_parts[] = $key;
                        $this->url_parts[] = $value;
                    }
                }

                foreach($pairs as $key=>$value) {
                    if ($key != 'controller') {
                        $this->url_parts[] = $key;
                        $this->url_parts[] = $value;
                    }
                }

                $this->params = $this->convertPartsToParams();
                return true;
            }
        }

        return false;
    }


    private function encloseForCSV($field)
    {
        return '"' .  cleanCSV($field) . '"';
    }


    function restart($sMessage = '')
    {
        $_COOKIE['sessionID'] = phpAds_SessionStart();
        OA_Auth::displayLogin($sMessage, $_COOKIE['sessionID']);
    }


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


    public function editAlt() {
        global $user;
        $file = new expFile($this->params['id']);
        if ($user->id==$file->poster || $user->isAdmin()) {
            $file->alt = $this->params['newValue'];
            $file->save();
            $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);
        } else {
            $ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
        }
        $ar->send();
        echo json_encode($file);  //FIXME we exit before hitting this
    }


        $input = (function ($settingName, $setting, $appView) {
            $settingId = str_replace('.', '_', $settingName);
            return $this->Bootstrap->switch([
                'label' => h($setting['description']),
                'checked' => !empty($setting['value']),
                'id' => $settingId,
                'class' => [
                    (!empty($setting['error']) ? 'is-invalid' : ''),
                    (!empty($setting['error']) ? $appView->get('variantFromSeverity')[$setting['severity']] : ''),
                ],
                'attrs' => [
                    'data-setting-name' => $settingName
                ]
            ]);
        })($settingName, $setting, $this);


    public function getUserList()
    {
        $result = [];
        $users = CodeModel::all(User::tableName(), 'nick', 'nick', false);
        foreach ($users as $codeModel) {
            if ($codeModel->code != 'admin') {
                $result[$codeModel->code] = $codeModel->description;
            }
        }

        return $result;
    }


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

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

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

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