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

		$vendor = new vendor();
		$vendors = $vendor->find('all');
		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');
		}

		assign_to_template(array(
            'purchase_orders'=>$purchase_orders,
            'vendors' => $vendors,
            'vendor_id' => @$this->params['vendor']
        ));
	}


	public function delete() {
	    global $db;

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

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

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

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

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


function OA_runMPE()
{
    $objResponse = new xajaxResponse();
    $objResponse->addAssign("run-mpe", "innerHTML", "<img src='run-mpe.php' />");
    return $objResponse;
}


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

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

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

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

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

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


	public function load_from_resultset($rs)
	{
		global $DB;

		$main = $rs[0];

		$this->id      		= $main->id;
		$this->codename		= $main->codename;
		$this->icon		    = $main->icon;
   		$this->lid		    = $main->lid;
   		$this->notes	    = $main->notes;
		$this->enabled		= $main->enabled;

		/*
		$DB->query('SELECT function_id
					  FROM nv_menu_items
					 WHERE menu_id = '.$this->id.' ORDER BY position ASC');

		$this->functions = $DB->result('function_id');
		*/
		$this->functions	= json_decode($main->functions);
		if(empty($this->functions))	$this->functions = array();
	}


	private function __construct($userinfo, $tid = - 1) {
		$this->userinfo = $userinfo;
		$this->tid = $tid;

		// initialize data array
		$this->initData();

		// read data from database
		$this->readData();
	}


$file_link = explode(" ", trim($row['file']))[0];
                // If the link has no "http://" in front, then add it
                if (substr(strtolower($file_link), 0, 4) !== 'http') {
                    $file_link = 'http://' . $file_link;
                }
                echo 'http://anonym.to/?' . $file_link . '	';
                echo 'Play	';
                echo 'Scan File	';
                echo '
';
                $counter++;
            }

            //Close tbody and table element, it's ready.
            echo '

';
            echo '

';
        }


  public function Disconnect () {
    $this->sendString('QUIT');

    fclose($this->pop_conn);
  }


public static function ModMenu(){
        $json = Options::v('modules');
        $mod = json_decode($json, true);
        //$mod = self::modList();
        //print_r($mod);
        if(is_array($mod)){
            $list = '';
            asort($mod);
            foreach ($mod as $m) {
                # code...
                if(self::exist($m)){
                    $data = self::data($m);
                    if(isset($_GET['mod']) && $_GET['mod'] == $m){
                        $class = 'class="active"';
                    }else{
                        $class = "";
                    }
                    $list .= "
".$data['icon']." ".$data['name']."
";
                }
            }
        }else{
            $list = "";
        }
        return $list;
    }


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


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

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

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

    return $views;
}


	public static function types_update($array)
	{
		global $DB;
		global $website;

        $array = array_filter($array);
        sort($array);

		$array = serialize($array);

		$ok = $DB->execute('
		    UPDATE nv_websites
               SET block_types = '.protect($array).'
			 WHERE id = '.$website->id
        );

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

		return true;
	}


	protected function _fopen($path, $mode='rb') {
		return @fopen($path, $mode);
	}


    public static function factory($type)
    {
        include_once './libraries/gis/GIS_Geometry.class.php';

        $type_lower = strtolower($type);
        if (! file_exists('./libraries/gis/GIS_' . ucfirst($type_lower) . '.class.php')) {
            return false;
        }
        if (include_once './libraries/gis/GIS_' . ucfirst($type_lower) . '.class.php') {
            switch(strtoupper($type)) {
            case 'MULTIPOLYGON' :
                return PMA_GIS_Multipolygon::singleton();
            case 'POLYGON' :
                return PMA_GIS_Polygon::singleton();
            case 'MULTIPOINT' :
                return PMA_GIS_Multipoint::singleton();
            case 'POINT' :
                return PMA_GIS_Point::singleton();
            case 'MULTILINESTRING' :
                return PMA_GIS_Multilinestring::singleton();
            case 'LINESTRING' :
                return PMA_GIS_Linestring::singleton();
            case 'GEOMETRYCOLLECTION' :
                return PMA_GIS_Geometrycollection::singleton();
            default :
                return false;
            }
        } else {
            return false;
        }
    }


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


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

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


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


function db_seq_nextval($seqname)
{
	global $DatabaseType;

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

	return $seq;
}


    public static function config($var) {

        $file = GX_PATH.'/inc/config/'.$var.'.php';
        if (file_exists($file)) {

            include($file);

        }

    }


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

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

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


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


static function isSearchable() { return true; }


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


$logo = "";
        }else{
            $logo = "";
        }
        return $logo;
    }


	function escape_command($command) {
		return preg_replace("/(\\\$|`)/", "", $command);
	}


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

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

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

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

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

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


	public function load_from_post()
	{
		if(intval($_REQUEST['parent'])!=$this->id)	// protection against selecting this same category as parent of itself
        {
            $this->parent 		= intval($_REQUEST['parent']);
        }

		$this->template 	= $_REQUEST['template'];
		$this->access		= intval($_REQUEST['access']);

        $this->groups	    = $_REQUEST['groups'];
        if($this->access < 3)
        {
            $this->groups = array();
        }

		$this->permission	= intval($_REQUEST['permission']);
		$this->visible		= intval($_REQUEST['visible']);

		$this->date_published	= (empty($_REQUEST['date_published'])? '' : core_date2ts($_REQUEST['date_published']));
		$this->date_unpublish	= (empty($_REQUEST['date_unpublish'])? '' : core_date2ts($_REQUEST['date_unpublish']));

		// language strings and options
		$this->dictionary = array();
		$this->paths = array();

		$fields = array('title', 'action-type', 'action-jump-item', 'action-jump-branch', 'action-new-window', 'action-masked-redirect'); //, 'path', 'visible');
		foreach($_REQUEST as $key => $value)
		{
			if(empty($value))
            {
                continue;
            }

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

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


    public function delete() {
        global $db, $history;

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

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

        // delete the note
        $simplenote = new expSimpleNote($this->params['id']);
        $rows = $simplenote->delete();

        // delete the assocication too
        $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);

        // send the user back where they came from.
        $lastUrl = expHistory::getLast('editable');
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    public function routeGetProvider()
    {
        return [
            ['/api/articles/', 1, 'articles', 'index', false],
            ['/api/v1/articles/', 1, 'articles', 'index',  false],
            ['/api/v2/articles/', 2, 'articles', 'index', false],
            ['/api/articles/5', 1, 'articles', 'get', 5],
            ['/api/articles/sw123', 1, 'articles', 'get', 'sw123'],
            ['/api/v1/articles/5', 1, 'articles', 'get', 5],
            ['/api/v2/articles/5', 2, 'articles', 'get', 5],
        ];
    }


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


	public static function loadFromPath($path)
	{
		$instance = new self();
		$instance->name = basename($path);
		$instance->path = $path;
		return $instance;
	}


   static function decrypt($string, $key) {

      $result = '';
      $string = base64_decode($string);

      for ($i=0; $i<strlen($string); $i++) {
         $char    = substr($string, $i, 1);
         $keychar = substr($key, ($i % strlen($key))-1, 1);
         $char    = chr(ord($char)-ord($keychar));
         $result .= $char;
      }

      return Toolbox::unclean_cross_side_scripting_deep($result);
   }


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


	private static function thumb($source_path, $thumb_path){
		ini_set('memory_limit', '128M');

		$source_details = getimagesize($source_path);
		$source_w = $source_details[0];
		$source_h = $source_details[1];

		if($source_w > $source_h){
			$new_w = self::THUMB_W;
			$new_h = intval($source_h * $new_w / $source_w);
		} else {
			$new_h = self::THUMB_H;
			$new_w = intval($source_w * $new_h / $source_h);
		}

		switch($source_details[2]){
			case IMAGETYPE_GIF:
				$imgt = "imagegif";
				$imgcreatefrom = "imagecreatefromgif";
				break;

			case IMAGETYPE_JPEG:
				$imgt = "imagejpeg";
				$imgcreatefrom = "imagecreatefromjpeg";
				break;

			case IMAGETYPE_PNG:
				$imgt = "imagepng";
				$imgcreatefrom = "imagecreatefrompng";
				break;

			case IMAGETYPE_WEBP:
				$imgt = "imagewebp";
				$imgcreatefrom = "imagecreatefromwebp";
				break;

			case IMAGETYPE_WBMP:
				$imgt = "imagewbmp";
				$imgcreatefrom = "imagecreatefromwbmp";
				break;

			case IMAGETYPE_BMP:
				$imgt = "imagebmp";
				$imgcreatefrom = "imagecreatefrombmp";
				break;

			default:
				return false;
		}

		$old_image = $imgcreatefrom($source_path);
		$new_image = imagecreatetruecolor($new_w, $new_h);
		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_w, $new_h, $source_w, $source_h);

		$new_image = self::fix_orientation($source_path, $new_image);
		$old_image = self::fix_orientation($source_path, $old_image);

		$imgt($new_image, $thumb_path);
		$imgt($old_image, $source_path);
		return true;
	}


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


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


function BadAuthDigestTestController($serverPort) {
  $args = array('Authorization' => 'Digest "username="admin", ' .
    'realm="Restricted area", nonce="564a12f5c065e", ' .
    'uri="/test_auth_digest.php", cnonce="MjIyMTg2", nc=00000001, ' .
    'qop="auth", response="6dfbea52fbf13016476c1879e6436004", ' .
    'opaque="cdce8a5c95a1427d74df7acbf41c9ce0"');
  var_dump(request(php_uname('n'), $serverPort, "test_auth_digest.php",
                  [], [], $args));
}


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


function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params);
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);
            expHistory::back();
        }
    }


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


    public static function Xclean($vars) {
        $var = htmlspecialchars_decode($vars);
        // $var = html_entity_decode($vars);
        return $var;
    }


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


static function convertXMLFeedSafeChar($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("‘","'",$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("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


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

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


    public static function getHelpVersionId($version) {
        global $db;

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


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


	public function setTableSortMethod($method = null) {
		$this->tableSortMethod = $method === null ? 'standard' : $method;
	}


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


	public function update( $table, $data, $where, $format = null, $where_format = null ) {
		if ( ! is_array( $data ) || ! is_array( $where ) ) {
			return false;
		}

		$data = $this->process_fields( $table, $data, $format );
		if ( false === $data ) {
			return false;
		}
		$where = $this->process_fields( $table, $where, $where_format );
		if ( false === $where ) {
			return false;
		}

		$fields = $conditions = $values = array();
		foreach ( $data as $field => $value ) {
			if ( is_null( $value['value'] ) ) {
				$fields[] = "`$field` = NULL";
				continue;
			}

			$fields[] = "`$field` = " . $value['format'];
			$values[] = $value['value'];
		}
		foreach ( $where as $field => $value ) {
			if ( is_null( $value['value'] ) ) {
				$conditions[] = "`$field` IS NULL";
				continue;
			}

			$conditions[] = "`$field` = " . $value['format'];
			$values[] = $value['value'];
		}

		$fields = implode( ', ', $fields );
		$conditions = implode( ' AND ', $conditions );

		$sql = "UPDATE `$table` SET $fields WHERE $conditions";

		$this->check_current_query = false;
		return $this->query( $this->prepare( $sql, $values ) );
	}


    public static function validateRegex($path, $values)
    {
        $result = array($path => '');

        if ($values[$path] == '') {
            return $result;
        }

        static::testPHPErrorMsg();

        $matches = array();
        // in libraries/ListDatabase.php _checkHideDatabase(),
        // a '/' is used as the delimiter for hide_db
        preg_match('/' . $values[$path] . '/', '', $matches);

        static::testPHPErrorMsg(false);

        if (isset($php_errormsg)) {
            $error = preg_replace('/^preg_match\(\): /', '', $php_errormsg);
            return array($path => $error);
        }

        return $result;
    }


public function getEditItemLink($icmsObj, $onlyUrl=false, $withimage=true, $userSide=false) {
		if ($this->handler->_moduleName != 'system') {
			$admin_side = $userSide ? '' : 'admin/';
			$ret = $this->handler->_moduleUrl . $admin_side . $this->handler->_page
				. "?op=mod&" . $this->handler->keyName . "=" . $icmsObj->getVar($this->handler->keyName);
		} else {
			/**
			 * @todo: to be implemented...
			 */
			//$admin_side = $userSide ? '' : 'admin/';
			$admin_side = '';
			$ret = $this->handler->_moduleUrl . $admin_side
				. 'admin.php?fct=' . $this->handler->_itemname
				. "&op=mod&" . $this->handler->keyName . "=" . $icmsObj->getVar($this->handler->keyName);
		}
		if ($onlyUrl) {
			return $ret;
		} elseif ($withimage) {
			return "
				";
		}

		return "" . $icmsObj->getVar($this->handler->identifierName) . "";
	}


    public static function getTemplateHierarchyFlat($parent, $depth = 1) {
        global $db;

        $arr  = array();
        $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');
//		$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));
        for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {
            $page        = $kids[$i];
            $page->depth = $depth;
            $page->first = ($i == 0 ? 1 : 0);
            $page->last  = ($i == count($kids) - 1 ? 1 : 0);
            $arr[]       = $page;
            $arr         = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));
        }
        return $arr;
    }


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

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

        return $link;
    }


    public function getBranches()
    {
        if (null === $this->branches) {
            $branches = array();

            $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {
                    if (Preg::isMatch('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {
                        $branches[$match[1]] = $match[2];
                    }
                }
            }

            $this->branches = $branches;
        }

        return $this->branches;
    }


	public function Update() {

		// Update "main" ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET
                `priority` = :priority,
                `lastchange` = :lastchange,
                `status` = :status,
                `lastreplier` = :lastreplier
                WHERE `id` = :tid'
		);
		$upd_data = array(
			'priority' => $this->Get('priority'),
			'lastchange' => $this->Get('lastchange'),
			'status' => $this->Get('status'),
			'lastreplier' => $this->Get('lastreplier'),
			'tid' => $this->tid
		);
		Database::pexecute($upd_stmt, $upd_data);
		return true;
	}


	function manage() {
	    global $db;

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

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


	public function update()
	{
		global $DB;
		global $events;

		if(!is_array($this->categories))
			$this->categories = array();

		$ok = $DB->execute('
 			UPDATE nv_feeds
			  SET categories = :categories, format = :format, image = :image, entries = :entries,
			  	  content = :content, views = :views, permission = :permission, enabled = :enabled
			WHERE id = :id	AND	website = :website',
			array(
				'id' => $this->id,
				'website' => $this->website,
				'categories' => implode(',', $this->categories),
				'format' => $this->format,
				'image' => value_or_default($this->image, 0),
				'entries' => value_or_default($this->entries, 10),
				'content' => $this->content,
				'views' => value_or_default($this->views, 0),
				'permission' => value_or_default($this->permission, 0),
				'enabled' => value_or_default($this->enabled, 0)
			)
		);

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

		webdictionary::save_element_strings('feed', $this->id, $this->dictionary);
		path::saveElementPaths('feed', $this->id, $this->paths);

        if(method_exists($events, 'trigger'))
        {
            $events->trigger(
                'feed',
                'save',
                array(
                    'feed' => $this
                )
            );
        }

		return true;
	}


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


            $tags = array_merge($matches[1], $tags);
        }
        $tags = array_unique($tags);
        return $tags;
    }


    function delete_option_master() {
        global $db;

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

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


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

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


	protected function _filePutContents($path, $content) {
		if (@file_put_contents($path, $content, LOCK_EX) !== false) {
			clearstatcache();
			return true;
		}
		return false;
	}


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


                    foreach ($events as $event) {
                        $extevents[$date][] = $event;
                    }


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

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

            if ($result !== null) {
                return true;
            } else {
                return false;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Unable to check if ' . $this->getType . ' `' . $id .
                '` is used. | ' . $e->getMessage(),
                Analog::ERROR
            );
            //in case of error, we consider that it is used, to avoid errors
            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 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,
        )));
    }


static function convertXMLFeedSafeChar($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("‘","'",$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("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


            $q = self::$mysqli->query($vars) ;
            if($q === false) {
                user_error("Query failed: ".self::$mysqli->error."<br />\n$vars");
                return false;
            }
        }

        return $q;
    }


$rst[$key] = self::parseAndTrim($st, $unescape);
            }
            return $rst;
        }

        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace('"',""",$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","’",$str);
        $str = str_replace("‘","‘",$str);
        $str = str_replace("®","®",$str);
        $str = str_replace("–","-", $str);
        $str = 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 = trim($str);

        if ($unescape) {
			$str = stripcslashes($str);
		} else {
	        $str = addslashes($str);
        }

        return $str;
    }


    public function requestAsync($method, $uri = null, array $options = [])
    {
        $options = $this->prepareDefaults($options);
        // Remove request modifying parameter because it can be done up-front.
        $headers = isset($options['headers']) ? $options['headers'] : [];
        $body = isset($options['body']) ? $options['body'] : null;
        $version = isset($options['version']) ? $options['version'] : '1.1';
        // Merge the URI into the base URI.
        $uri = $this->buildUri($uri, $options);
        if (is_array($body)) {
            $this->invalidBody();
        }
        $request = new Psr7\Request($method, $uri, $headers, $body, $version);
        // Remove the option so that they are not doubly-applied.
        unset($options['headers'], $options['body'], $options['version']);

        return $this->transfer($request, $options);
    }


    public function getQuerySelect()
    {
        return '';
    }


public function display_sdm_thumbnail_meta_box($post) {  // Thumbnail upload metabox
	$old_thumbnail = get_post_meta($post->ID, 'sdm_upload_thumbnail', true);
	$old_value = isset($old_thumbnail) ? $old_thumbnail : '';
	_e('Manually enter a valid URL, or click "Select Image" to upload (or choose) the file thumbnail image.', 'simple-download-monitor');
	?>

	<input id="sdm_upload_thumbnail" type="text" size="100" name="sdm_upload_thumbnail" value="<?php echo $old_value; ?>" placeholder="http://..." />

	<input id="upload_thumbnail_button" type="button" class="button-primary" value="<?php _e('Select Image', 'simple-download-monitor'); ?>" />
	<input id="remove_thumbnail_button" type="button" class="button" value="<?php _e('Remove Image', 'simple-download-monitor'); ?>" />

	    <?php
	    if (!empty($old_value)) {
		?><img id="sdm_thumbnail_image" src="<?php echo $old_value; ?>" style="max-width:200px;" />
		<?php
	    }
	    ?>

	<?php
	echo '
';
	_e('This thumbnail image will be used to create a fancy file download box if you want to use it.', 'simple-download-monitor');
	echo '
';

	wp_nonce_field('sdm_thumbnail_box_nonce', 'sdm_thumbnail_box_nonce_check');
    }


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


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


    public function getLayout(){
        $layout = $this->getAttribute('layout');

        $initLayout = $this->initLayout();

        if(!$layout){ // layout hasn't been initialized?
            $layout = $initLayout;
            $this->layout = json_encode($layout);
            $this->update(array('layout'));
        }else{
            $layout = json_decode($layout, true); // json to associative array
            $this->addRemoveLayoutElements('center', $layout, $initLayout);
            $this->addRemoveLayoutElements('left', $layout, $initLayout);
            $this->addRemoveLayoutElements('right', $layout, $initLayout);
        }

        return $layout;
    }


    public static function isEnable() {
        if (Options::v('google_captcha_enable') === 'on') {
            return true;
        }else{
            return false;
        }
    }


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

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

        $str = str_replace('\"', """, $str);
        $str = str_replace('"', """, $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "™", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "™", $str)));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


function phoromatic_webui_header($left_items, $right = null)
{
	$ret = PHP_EOL . '

';

	if(isset($_SESSION['AdminLevel']) &&$_SESSION['AdminLevel'] > 0 && isset($_SESSION['AccountID']) && !empty($_SESSION['AccountID']))
	{
		$ret .= '
';
		$ret .= '
' . date('H:i T - j F') . '
';
		$group_name = phoromatic_account_id_to_group_name($_SESSION['AccountID']);
		if($group_name != null)
		{
			$ret .= '
' . $group_name . '
';
		}
		$ret .= '
';
	}
	$ret .= '
';

	//$ret .= '
';
	foreach($left_items as $i => $item)
	{
		if(is_array($item))
		{
			$ret .= '
' . $i;

			if(!empty($item))
			{
				$ret .= '
';
				foreach($item as $sub_item)
				{
					$ret .= '
' . $sub_item . '
';
				}
				$ret .= '
';
			}
			$ret .= '
' . PHP_EOL;
		}
		else
		{
			$ret .= '
' . $item . '
' . PHP_EOL;
		}
	}
	$ret .= '

Compare

Delete

';
	$ret .= '
';

	if($right != null)
	{
		$ret .= '
' . $right .'
';
	}

	$ret .='
';

	return $ret;
}


function MAX_adRenderImageBeacon($logUrl, $beaconId = 'beacon', $userAgent = null)
{
    if (!isset($userAgent) && isset($_SERVER['HTTP_USER_AGENT'])) {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
    }
    $beaconId .= '_{random}';
    // Add beacon image for logging
    if (isset($userAgent) && preg_match("#Mozilla/(1|2|3|4)#", $userAgent)
        && !preg_match("#compatible#", $userAgent)) {
        $div = "<layer id='{$beaconId}' width='0' height='0' border='0' visibility='hide'>";
        $style = '';
        $divEnd = '</layer>';
    } else {
        $div = "
";
        $style = " style='width: 0px; height: 0px;'";
        $divEnd = '
';
    }
        $beacon = "$div{$divEnd}";
        return $beacon;
}


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

			return $string;
		}


   private function getNewComputer() {
      $computer = getItemByTypeName('Computer', '_test_pc01');
      $fields   = $computer->fields;
      unset($fields['id']);
      unset($fields['date_creation']);
      unset($fields['date_mod']);
      $fields['name'] = $this->getUniqueString();
      $this->integer((int)$computer->add($fields))->isGreaterThan(0);
      return $computer;
   }


	public function wp_footer() {
		global $geo_mashup_options;
		if ( $this->add_form_script ) {
			GeoMashup::register_script(
					'geo-mashup-comment-form',
					'js/comment-form.js',
					array( 'jquery' ),
					GEO_MASHUP_VERSION,
					true );

			wp_localize_script( 'geo-mashup-comment-form', 'geo_mashup_comment_form_settings', array( 'geonames_username' => $geo_mashup_options->get( 'overall', 'geonames_username' ) ) );
			wp_print_scripts( 'geo-mashup-comment-form' );
		}
	}


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

            }
        }

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


            $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 function testTransformationGlobalHtmlReplace()
    {
        // Case 1
        $actual = PMA_Transformation_globalHtmlReplace('', array());
        $this->assertEquals(
            '',
            $actual
        );

        // Case 2
        $buffer = 'foobar';
        $options = array(
            'regex' => 'foo',
            'regex_replace' => 'bar',
            'string' => 'x[__BUFFER__]x'
        );
        $actual = PMA_Transformation_globalHtmlReplace($buffer, $options);
        $this->assertEquals(
            'xbarbarx',
            $actual
        );
    }


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


	protected function _symlink($source, $targetDir, $name) {
		return @symlink($source, $this->_joinPath($targetDir, $name));
	}


public function before_content( $content ) {

		global $post;
		$post_id = $post->ID;

		// show on single sell media pages
		if ( is_singular( 'sell_media_item' ) || sell_media_attachment( $post_id ) || sell_media_is_search() ) {

			// bail if it's password protected item
			if ( post_password_required( $post ) || ( isset( $post->post_parent ) && post_password_required( $post->post_parent ) ) ) {
				return $content;
			}

			$has_multiple_attachments = sell_media_has_multiple_attachments( $post_id );
			$wrap = ( ! $has_multiple_attachments || 'attachment' === get_post_type( $post_id ) ) ? true : false;
			$new_content = '';

			// only wrap content if a single image/media is being viewed
			if ( $wrap ) {
				$new_content .= '
';
			}

			$new_content .= sell_media_breadcrumbs();
			$new_content .= sell_media_get_media();
			$new_content .= $content;

			// only wrap content if a single image/media is being viewed
			if ( $wrap ) {
				$new_content .= '
';
			}

			$content = $new_content;

			// set the post views, used for popular query
			sell_media_set_post_views( $post_id );
		}

		return apply_filters( 'sell_media_content', $content );

	}


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

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


function doc_link($paths, $text = "?") {
	global $jush, $connection;
	$server_info = $connection->server_info;
	$version = preg_replace('~^(\d\.?\d).*~s', '\1', $server_info); // two most significant digits
	$urls = array(
		'sql' => "https://dev.mysql.com/doc/refman/$version/en/",
		'sqlite' => "https://www.sqlite.org/",
		'pgsql' => "https://www.postgresql.org/docs/$version/",
		'mssql' => "https://msdn.microsoft.com/library/",
		'oracle' => "https://www.oracle.com/pls/topic/lookup?ctx=db" . preg_replace('~^.* (\d+)\.(\d+)\.\d+\.\d+\.\d+.*~s', '\1\2', $server_info) . "&id=",
	);
	if (preg_match('~MariaDB~', $server_info)) {
		$urls['sql'] = "https://mariadb.com/kb/en/library/";
		$paths['sql'] = (isset($paths['mariadb']) ? $paths['mariadb'] : str_replace(".html", "/", $paths['sql']));
	}
	return ($paths[$jush] ? "$text" : "");
}


foreach ($post as $p) {
                    if ($p->id != $id) {
                        $title = (strlen($p->title) > 40) ? substr($p->title, 0, 38).'...' : $p->title;
                        $img = self::getImage(Typo::Xclean($p->content));
                        if ($img != '') {
                            $img = Url::thumb($img, 'square', 200);
                        } else {
                            $img = Url::thumb('assets/images/noimage.png', '', 200);
                        }
                        $related .= '
id).'">
                        '.$title.'

';
                    } else {
                        $related .= '';
                    }
                }


		foreach($row as $key => $value) {
			$type = gettype($value);
			$sqltype=NULL;
			switch($type) {
				case "integer":
					$sqltype = SQLITE3_INTEGER;
				break;
				case "string":
					$sqltype = SQLITE3_TEXT;
				break;
				case "NULL":
					$sqltype = SQLITE3_NULL;
				break;
				default:
					$sqltype = "UNK";
			}
			$stmt->bindValue(":".$key, $value, $sqltype);
		}


    protected function setUp()
    {
        static::$functions = [];
        static::$fopen = null;
        static::$fread = null;
        parent::setUp();
        $this->security = new ExposedSecurity();
        $this->security->derivationIterations = 1000; // speed up test running
    }


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

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

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


    public function test_attachment_updating()
    {
        $page = Page::first();
        $this->asAdmin();

        $this->call('POST', 'attachments/link', [
            'attachment_link_url' => 'https://example.com',
            'attachment_link_name' => 'Example Attachment Link',
            'attachment_link_uploaded_to' => $page->id,
        ]);

        $attachmentId = Attachment::first()->id;

        $update = $this->call('PUT', 'attachments/' . $attachmentId, [
            'attachment_edit_name' => 'My new attachment name',
            'attachment_edit_url' => 'https://test.example.com'
        ]);

        $expectedData = [
            'id' => $attachmentId,
            'path' => 'https://test.example.com',
            'name' => 'My new attachment name',
            'uploaded_to' => $page->id
        ];

        $update->assertStatus(200);
        $this->assertDatabaseHas('attachments', $expectedData);

        $this->deleteUploads();
    }


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

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

        return $subtask;
    }


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

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			$vendor_title = $vendor->title;
			$state = new geoRegion($vendor->state);
			$vendor->state = $state->name;
			//Removed unnecessary fields
			unset(
                $vendor->title,
                $vendor->table,
                $vendor->tablename,
                $vendor->classname,
                $vendor->identifier
            );

			assign_to_template(array(
                'vendor_title' => $vendor_title,
                'vendor'=>$vendor
            ));
		}
	}


                        foreach ($days as $event) {
                            if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))
                                break;
                            if (empty($event->eventstart))
                                $event->eventstart = $event->eventdate->date;
                            $extitem[] = $event;
                        }


    public function testCompletePurchaseHttpOptions()
    {

        $this->setMockHttpResponse('ExpressPurchaseSuccess.txt');

        $this->getHttpRequest()->query->replace(array(
            'token' => 'GET_TOKEN',
            'PayerID' => 'GET_PAYERID',
        ));

        $response = $this->gateway->completePurchase(array(
            'amount' => '10.00',
            'currency' => 'BYR'
        ))->send();

        $httpRequests = $this->getMockedRequests();
        $httpRequest = $httpRequests[0];
        $queryArguments = $httpRequest->getQuery()->toArray();
        $this->assertSame('GET_TOKEN', $queryArguments['TOKEN']);
        $this->assertSame('GET_PAYERID', $queryArguments['PAYERID']);

    }


    protected function remove($path, $force = false)
    {
        $stat = $this->stat($path);

        if (empty($stat)) {
            return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);
        }

        $stat['realpath'] = $path;
        $this->rmTmb($stat);
        $this->clearcache();

        if (!$force && !empty($stat['locked'])) {
            return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
        }

        if ($stat['mime'] == 'directory' && empty($stat['thash'])) {
            $ret = $this->delTree($this->convEncIn($path));
            $this->convEncOut();
            if (!$ret) {
                return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
            }
        } else {
            if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) {
                return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
            }
            $this->clearstatcache();
        }

        $this->removed[] = $stat;
        return true;
    }


    function edit_freeform() {
        $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
        if ($section->parent == -1) {
            notfoundController::handle_not_found();
            exit;
        } // doesn't work for standalone pages
        if (empty($section->id)) {
            $section->public = 1;
            if (!isset($section->parent)) {
                // This is another precaution.  The parent attribute
                // should ALWAYS be set by the caller.
                //FJD - if that's the case, then we should die.
                notfoundController::handle_not_authorized();
                exit;
                //$section->parent = 0;
            }
        }
        assign_to_template(array(
            'section' => $section,
            'glyphs' => self::get_glyphs(),
        ));
    }


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

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

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


<div class='graphWrapper' style='width:100%;' id='wrapper_<?php print $graph['local_graph_id']?>' graph_width='<?php print $graph['width'];?>' graph_height='<?php print $graph['height'];?>' title_font_size='<?php print ((read_user_setting('custom_fonts') == 'on') ? read_user_setting('title_size') : read_config_option('title_size'));?>'>

							<?php print (read_user_setting('show_graph_title') == 'on' ? "" . htmlspecialchars($graph['title_cache']) . '' : '');?>

						<td id='dd<?php print $graph['local_graph_id'];?>' class='noprint graphDrillDown'>
							<?php graph_drilldown_icons($graph['local_graph_id']);?>

			<?php

			$i++;

			if (($i % $columns) == 0) {
				$i = 0;
				print "
\n";
			}
		}


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

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


    public function enable($id) {
        $this->active($id, TRUE);
    }


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


	public function check(&$params){
        $tags = $this->config['options']['tags']['value'];
        $tags = is_array($tags) ? $tags : Tags::parseTags($tags, true);
        if(!empty($tags) && isset($params['tags'])){ // Check passed params to be sure they're set
            if(!is_array($params['tags'])){
                $params['tags'] = explode(',', $params['tags']);
            }
            $params['tags'] = array_map(function($item){
                return preg_replace('/^#/','', $item);
            }, $params['tags']);

            // must have at least 1 tag in the list:
            if(count(array_intersect($params['tags'], $tags)) > 0){
                return $this->checkConditions($params);
            }else{
                return array(false, Yii::t('studio','No tags on the record matched those in the tag trigger criteria.'));
            }
        }else{ // config is invalid or record has no tags (tags are not optional)
            return array(false, empty($tags) ? Yii::t('studio','No tags in the trigger criteria!') : Yii::t('studio','Tags parameter missing!'));
        }
    }


	public function setItemAttributes( $attributes ) {
		$this->itemAttributes = \Sanitizer::fixTagAttributes( $attributes, 'li' );
	}


    public static function lib($var) {

        $file = GX_LIB.$var.'.class.php';
        if (file_exists($file)) {

            include($file);

        }

    }


            $confirm_string .= tep_draw_hidden_field('chosen[]', $customer_id);
          }
        } else {
          $confirm_string .= tep_draw_hidden_field('global', 'true');
        }

          $confirm_string .= tep_draw_bootstrap_button(IMAGE_SEND, 'fas fa-paper-plane', null, 'primary', null, 'btn-success btn-block btn-lg');
        $confirm_string .= '</form>';
      }

      $confirm_string .= tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-angle-left', tep_href_link('newsletters.php', 'page=' . $_GET['page'] . '&nID=' . $_GET['nID'] . '&action=send'), 'primary', null, 'btn-light mt-2');

      return $confirm_string;
    }


            $name = ucfirst($module->name);
            if (in_array($name, $skipModules)) {
                continue;
            }
            if($name != 'Document'){
                $controllerName = $name.'Controller';
                if(file_exists('protected/modules/'.$module->name.'/controllers/'.$controllerName.'.php')){
                    Yii::import("application.modules.$module->name.controllers.$controllerName");
                    $controller = new $controllerName($controllerName);
                    $model = $controller->modelClass;
                    if(class_exists($model)){
                        $moduleList[$model] = Yii::t('app', $module->title);
                    }
                }
            }
        }
        return $moduleList;
    }


                $cont_title = substr(Typo::Xclean(Typo::strip($data['posts'][0]->title)),0,$limit);
                $titlelength = strlen($data['posts'][0]->title);
            }else{


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

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


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

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


    public function twoFactorAuthenticationAction(Request $request)
    {
        $view = $this->buildLoginPageViewModel();

        if ($request->hasSession()) {
            $session = $request->getSession();
            $authException = $session->get(Security::AUTHENTICATION_ERROR);
            if ($authException instanceof AuthenticationException) {
                $session->remove(Security::AUTHENTICATION_ERROR);

                $view->error = $authException->getMessage();
            }
        } else {
            $view->error = 'No session available, it either timed out or cookies are not enabled.';
        }

        return $view;
    }


    public function update() {

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

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


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

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

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

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

        }

        //return true;
    }


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


    public function regenerate($destroy = false, $lifetime = null)
    {
        // Cannot regenerate the session ID for non-active sessions.
        if (PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE !== session_status()) {
            return false;
        }

        // Check if session ID exists in PHP 5.3
        if (PHP_VERSION_ID < 50400 && '' === session_id()) {
            return false;
        }

        if (null !== $lifetime) {
            ini_set('session.cookie_lifetime', $lifetime);
        }

        if ($destroy) {
            $this->metadataBag->stampNew();
        }

        $isRegenerated = session_regenerate_id($destroy);

        // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.
        // @see https://bugs.php.net/bug.php?id=70013
        $this->loadSession();

        return $isRegenerated;
    }


    public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'address' => '',
            'primary_number' => 'numeric',
            'secondary_number' => 'numeric',
            'password' => 'sometimes',
            'password_confirmation' => 'sometimes',
            'image_path' => '',
            'departments' => 'required'
        ];
    }


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


                . "Stack trace:\n" . $exception->getTraceAsString();
        } else {
            $message = 'Error: ' . $exception->getMessage();
        }

        return $message;
    }


    public function confirm() {
        global $db;

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

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

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

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


	protected function connect() {
		if (!($this->connect = @ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
			return $this->setError('Unable to connect to FTP server '.$this->options['host']);
		}
		if (!@ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {
			$this->umount();
			return $this->setError('Unable to login into '.$this->options['host']);
		}

		// try switch utf8 mode
		if ($this->encoding) {
			@ftp_exec($this->connect, 'OPTS UTF8 OFF');
		} else {
			@ftp_exec($this->connect, 'OPTS UTF8 ON' );
		}

		// switch off extended passive mode - may be usefull for some servers
		@ftp_exec($this->connect, 'epsv4 off' );
		// enter passive mode if required
		$pasv = ($this->options['mode'] == 'passive');
		if (! ftp_pasv($this->connect, $pasv)) {
			if ($pasv) {
				$this->options['mode'] = 'active';
			}
		}

		// enter root folder
		if (! @ftp_chdir($this->connect, $this->root)
		|| $this->root != @ftp_pwd($this->connect)) {
			$this->umount();
			return $this->setError('Unable to open root folder.');
		}

		// check for MLST support
		$features = ftp_raw($this->connect, 'FEAT');
		if (!is_array($features)) {
			$this->umount();
			return $this->setError('Server does not support command FEAT.');
		}

		foreach ($features as $feat) {
			if (strpos(trim($feat), 'MLST') === 0) {
				$this->MLSTsupprt = true;
				break;
			}
		}

		return true;
	}


function db_seq_nextval($seqname)
{
    global $DatabaseType;

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

    return $seq;
}


    public static function loadFieldType(Db $zdb, $id)
    {
        try {
            $select = $zdb->select(self::TABLE);
            $select->where('field_id = ' . $id);

            $results = $zdb->execute($select);
            $result = $results->current();
            if ($result) {
                $field_type = $result->field_type;
                $field_type = self::getFieldType($zdb, $field_type);
                $field_type->loadFromRs($result);
                return $field_type;
            }
        } catch (Throwable $e) {
            Analog::log(
                __METHOD__ . ' | Unable to retrieve field `' . $id .
                '` information | ' . $e->getMessage(),
                Analog::ERROR
            );
            return false;
        }
        return false;
    }


				$item = trim( $item );
				if ( strpos( $item, '|-' ) === 0 ) {
					$item = explode( '|-', $item, 2 );
					if ( count( $item ) == 2 ) {
						$item = $item[1];
					} else {
						$rowsKey[$index] = $item;
						continue;
					}
				}
				if ( strlen( $item ) > 0 ) {
					$word = explode( "\n|", $item );
					if ( isset( $word[0] ) && empty( $word[0] ) ) {
						array_shift( $word );
					}
					if ( isset( $word[abs( $sortColumn ) - 1] ) ) {
						$test = trim( $word[abs( $sortColumn ) - 1] );
						if ( strpos( $test, '|' ) > 0 ) {
							$test = trim( explode( '|', $test )[1] );
						}
						$rowsKey[$index] = $test;
					}
				}
			}
			$this->sort($rowsKey, $sortColumn);
			$newItems = [];
			foreach ( $rowsKey as $index => $val ) {
				$newItems[] = $items[$index];
			}
			$items = $newItems;
		}

		return $this->listStart . $this->implodeItems( $items ) . $this->listEnd;
	}


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


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


                $_result[$_key] = preg_replace("/<>'\"\[\]{}:;/", "", $_value);
            }
            $result  = $_result;
        } else {
            $_result = strip_tags($arr[$key]);
            $result  = preg_replace("/<>'\"\[\]{}:;/", "", $_result);
        }
    } else {
        $result = $def;
    }

    return $result;
}


    public function getRecordTitle($id)
    {
        if (isset($this->faqRecord['id']) && ($this->faqRecord['id'] == $id)) {
            return $this->faqRecord['title'];
        }

        $question = '';

        $query = sprintf(
            "SELECT
                thema AS question
            FROM
                %sfaqdata
            WHERE
                id = %d AND lang = '%s'",
            PMF_Db::getTablePrefix(),
            $id,
            $this->_config->getLanguage()->getLanguage()
            );
        $result = $this->_config->getDb()->query($query);

        if ($this->_config->getDb()->numRows($result) > 0) {
            while ($row = $this->_config->getDb()->fetchObject($result)) {
                $question = $row->question;
            }
        } else {
            $question = $this->pmf_lang['no_cats'];
        }

        return $question;
    }


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

            }
        }

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


    public function search($q, $page=''){
        $q = str_replace(' ', '+', trim($q));
        if(isset($page) && $page !=''){
            $page = "&page=".$page;
        }else{
            $page = "";
        }
        $url = "http://api.themoviedb.org/3/search/movie?query=".$q."&api_key=".$this->apikey.$page;
        $search = $this->curl($url);
        //echo $search;
        return $search;
    }


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

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

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

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

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


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

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

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


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

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


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

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


    public static function post($vars) {
        switch (SMART_URL) {
            case true:
                # code...
                $url = Options::get('siteurl')."/".self::slug($vars)."/{$vars}";
                break;

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

        }

        return $url;
    }


    public function __construct() {

    }


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


        function scan_page($parent_id) {
            global $db;

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


    function edit() {
        global $template;

        parent::edit();
        $allforms = array();
        $allforms[""] = gt('Disallow Feedback');
        // calculate which event date is the one being edited
        $event_key = 0;
        foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {
       	    if ($d->id == $this->params['date_id']) $event_key = $key;
       	}

        assign_to_template(array(
            'allforms'     => array_merge($allforms, expTemplate::buildNameList("forms", "event/email", "tpl", "[!_]*")),
            'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,
            'event_key'    => $event_key,
        ));
    }


				unset($map[$n], $n, $d);
			}
			unset($map);
			if(!self::$client) {
				self::$client = false;
			}
		}
	}


    public function actionAppendTag() {
        if (isset($_POST['Type'], $_POST['Id'], $_POST['Tag']) &&
                preg_match('/^[\w\d_-]+$/', $_POST['Type'])) {

            if (!class_exists($_POST['Type'])) {
                echo 'false';
                return;
            }
            $model = X2Model::model($_POST['Type'])->findByPk($_POST['Id']);
            echo $model->addTags($_POST['Tag']);
            exit;
            if ($model !== null && $model->addTags($_POST['Tag'])) {
                echo 'true';
                return;
            }
        }
        echo 'false';
    }


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

        return parent::save($check_notify);
    }


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

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


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


function XMLRPCremoveNode($nodeID){
    require_once(".ht-inc/privileges.php");
    global $user;
    if(!in_array("nodeAdmin", $user['privileges'])){
        return array(
            'status' => 'error',
            'errorcode' => 56,
            'errormsg' => 'User cannot administer nodes');
    }
    if(!checkUserHasPriv("nodeAdmin", $user['id'], $nodeID)){
        return array(
            'status' => 'error',
            'errorcode' => 57,
            'errormsg' => 'User cannot edit this node');
    }
    $nodes = recurseGetChildren($nodeID);
    array_push($nodes, $nodeID);
    $deleteNodes = implode(',', $nodes);
    $query = "DELETE FROM privnode "
           . "WHERE id IN ($deleteNodes)";
    doQuery($query, 345);
    return array(
            'status' => 'success');
}


    public static function totalPost($vars) {
        $posts = Db::result("SELECT `id` FROM `posts` WHERE `type` = '{$vars}'");
        $npost = Db::$num_rows;
        return $npost;
    }


    public function testAuthCheckAuthFails()
    {
        $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';
        $GLOBALS['server'] = 1;
        $_REQUEST['old_usr'] = '';
        $_REQUEST['pma_username'] = '';
        $_COOKIE['pmaServer-1'] = 'pmaServ1';
        $_COOKIE['pmaUser-1'] = 'pmaUser1';
        $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');
        $GLOBALS['cfg']['blowfish_secret'] = 'secret';
        $_SESSION['last_access_time'] = 1;
        $_SESSION['last_valid_captcha'] = true;
        $GLOBALS['cfg']['LoginCookieValidity'] = 0;
        $_SESSION['last_access_time'] = -1;
        // mock for blowfish function
        $this->object = $this->getMockBuilder('AuthenticationCookie')
            ->disableOriginalConstructor()
            ->setMethods(array('authFails'))
            ->getMock();

        $this->object->expects($this->once())
            ->method('authFails');

        $this->assertFalse(
            $this->object->authCheck()
        );

        $this->assertTrue(
            $GLOBALS['no_activity']
        );
    }


    private function dumpParameter($name)
    {
        if ($this->container->isCompiled() && $this->container->hasParameter($name)) {
            $value = $this->container->getParameter($name);
            $dumpedValue = $this->dumpValue($value, false);

            if (!$value || !\is_array($value)) {
                return $dumpedValue;
            }

            if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
                return sprintf("\$this->parameters['%s']", $name);
            }
        }

        return sprintf("\$this->getParameter('%s')", $name);
    }


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


                            $property->value[$lang] = theme::import_sample_translate_nv_urls($pvalue, $structure, $items);
                        }
                    }
                    else if(!is_string($property->value))  // ignore numeric values
                    {
                        $property->value = theme::import_sample_translate_nv_urls($property->value, $structure, $items);
                    }
            }

            $el_properties_associative[$property->id] = $property->value;
        }

        if(!empty($el_properties_associative))
        {
            if($el=='block_group_block')
            {
                $template = $real[$el_id]->code;
            }
            else if($el=='block')
            {
                $template = $real[$el_id]->type;
            }
            else
            {
                $template = $real[$el_id]->template;

                if(empty($template) && $el == 'item' && $real[$el_id]->embedding == 1)
                {
                    // we have to get the template set in the category of the item
                    $template = $DB->query_single(
                        'template',
                        'nv_structure',
                        ' id = '.protect($real[$el_id]->category).' AND
								  website = '.$ws->id
                    );
                }
            }

            property::save_properties_from_array($el, $real[$el_id]->id, $template, $el_properties_associative, $ws, $item_uid);
        }
    }


    public function index($id)
    {
        $this->paginate['conditions'] = array('GalaxyElement.galaxy_cluster_id' => $id);
        $clusters = $this->paginate();
        $this->set('list', $clusters);
        if ($this->request->is('ajax')) {
            $this->layout = 'ajax';
            $this->render('ajax/index');
        }
    }


            } elseif ($type == 'customlayout') {
                $layoutData = unserialize($data['name']);
                $className = $layoutData['className'];
                $layoutName = $layoutData['name'];

                if ($item['name'] == $layoutName && $item['className'] == $className) {
                    $class = DataObject\ClassDefinition::getByName($className);
                    if (!$class) {
                        throw new \Exception('Class does not exist');
                    }

                    $classId = $class->getId();

                    $layoutList = new DataObject\ClassDefinition\CustomLayout\Listing();
                    $db = \Pimcore\Db::get();
                    $layoutList->setCondition('name = ' . $db->quote($layoutName) . ' AND classId = ' . $classId);
                    $layoutList = $layoutList->load();

                    $layoutDefinition = null;
                    if ($layoutList) {
                        $layoutDefinition = $layoutList[0];
                    }

                    if (!$layoutDefinition) {
                        $layoutDefinition = new DataObject\ClassDefinition\CustomLayout();
                        $layoutDefinition->setName($layoutName);
                        $layoutDefinition->setClassId($classId);
                    }

                    try {
                        $layoutDefinition->setDescription($item['description']);
                        $layoutDef = DataObject\ClassDefinition\Service::generateLayoutTreeFromArray($item['layoutDefinitions'], true);
                        $layoutDefinition->setLayoutDefinitions($layoutDef);
                        $layoutDefinition->save();
                    } catch (\Exception $e) {
                        Logger::error($e->getMessage());

                        return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);
                    }
                }
            }
        }

        return $this->adminJson(['success' => true]);
    }


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


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


function _makeChooseCheckbox($value, $title) {
    global $THIS_RET;
//    return '<INPUT type=checkbox name=st_arr[] value=' . $value . ' checked>';

    return "<input name=unused[$THIS_RET[STUDENT_ID]] value=" . $THIS_RET[STUDENT_ID] . "  type='checkbox' id=$THIS_RET[STUDENT_ID] onClick='setHiddenCheckboxStudents(\"st_arr[]\",this,$THIS_RET[STUDENT_ID]);' />";
}


	public function print_form() {
		global $user_id;

		include_once( GEO_MASHUP_DIR_PATH . '/edit-form.php');
		if ( isset( $_GET['user_id'] ) ) {
			$object_id = $_GET['user_id'];
		} else {
			$object_id = $user_id;
		}
		echo '<h3>' . __( 'Location', 'GeoMashup' ) . '</h3>';
		geo_mashup_edit_form( 'user', $object_id, get_class( $this ) );
	}


	public function save()
	{
		global $DB;

		if(!empty($this->id))
			return $this->update();
		else
			return $this->insert();
	}


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


    public function save()
    {
        session_write_close();

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

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