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


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

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

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

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

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

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


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

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

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


	protected function decode($hash) {
		if (strpos($hash, $this->id) === 0) {
			// cut volume id after it was prepended in encode
			$h = substr($hash, strlen($this->id));
			// replace HTML safe base64 to normal
			$h = base64_decode(strtr($h, '-_.', '+/='));
			// TODO uncrypt hash and return path
			$path = $this->uncrypt($h);
			// append ROOT to path after it was cut in encode
			return $this->abspathCE($path);//$this->root.($path == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR.$path);
		}
	}


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


    protected function getRot13EnvVarProcessorService()
    {
        return $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor();
    }


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

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


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


    public static function backend($vars="") {

        if(!empty($_GET['page'])) {
            self::incBack($_GET['page']);
        }else{
            self::incBack('default');
        }
    }


	function insertServiceCategorieInDB(){
		global $pearDB, $centreon;

		if (testServiceCategorieExistence($_POST["sc_name"])){
                $DBRESULT = $pearDB->query("INSERT INTO `service_categories` (`sc_name`, `sc_description`, `level`, `icon_id`, `sc_activate` )
                    VALUES ('".$_POST["sc_name"]."', '".$_POST["sc_description"]."', ".
                        (isset($_POST['sc_severity_level']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_level']):"NULL").", ".
                        (isset($_POST['sc_severity_icon']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_icon']) : "NULL").", ".
                        "'".$_POST["sc_activate"]["sc_activate"]."')");


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


    public function getFilePath($fileName = null)
    {
        if ($fileName === null) {
            $fileName = $this->fileName;
        }

        return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;
    }


	public function	queryLimit($cols, $table, $where="1=1", $order="", $offset=0, $max=100)
	{
		$this->lastError = '';
		$this->lastResult = '';
		$fetch = PDO::FETCH_ASSOC;

		try
		{
			$sql = ' SELECT SQL_CALC_FOUND_ROWS '.$cols.'
					   FROM '.$table.'
					  WHERE '.$where.'
 				   ORDER BY '.$order.'
					  LIMIT '.$max.'
					 OFFSET '.$offset;

			$statement = $this->db->query($sql);
            $this->queries_count++;
			$statement->setFetchMode($fetch);
			$this->lastResult = $statement->fetchAll();
			$statement->closeCursor();
			unset($statement);
		}
		catch(PDOException $e)
		{
			$this->lastError = $e->getMessage();
		}
		catch(Exception $e)
		{
			return false;
		}

		return empty($this->lastError);
	}


    public function confirm() {
        global $db;

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

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

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

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


    public function buildControl() {
        $control = new colorcontrol();
        if (!empty($this->params['value'])) $control->value = $this->params['value'];
        if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];
        $control->default = $this->params['value'];
        if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];
        if (isset($this->params['flip'])) $control->flip = $this->params['flip'];
        $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';
        $control->name  = $this->params['name'];
        $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';
        $control->id  = isset($this->params['id']) && $this->params['id'] != "" ? $this->params['id'] : "";
        //echo $control->id;
        if (empty($control->id)) $control->id = $this->params['name'];
        if (empty($control->name)) $control->name = $this->params['id'];

        // attempt to translate the label
        if (!empty($this->params['label'])) {
            $this->params['label'] = gt($this->params['label']);
        } else {
            $this->params['label'] = null;
        }
        echo $control->toHTML($this->params['label'], $this->params['name']);
//        $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));
//        $ar->send();
    }


    public function getRequestFormat($default = 'html')
    {
        if (null === $this->format) {
            $this->format = $this->get('_format', $default);
        }

        return $this->format;
    }


    public function newpassword() {

        if ($token = $this->param('token')) {

            $user = $this->app->storage->findOne('cockpit/accounts', ['_reset_token' => $token]);

            if (!$user) {
                return false;
            }

            $user['md5email'] = md5($user['email']);

            return $this->render('cockpit:views/layouts/newpassword.php', compact('user', 'token'));
        }

        return false;

    }


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

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

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


$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 static function set_session($vars) {
        if (is_array($vars)) {
            if(is_array($_SESSION['gxsess']['val'])){
                $arr = array_merge($_SESSION['gxsess']['val'], $vars);
                $_SESSION['gxsess']['val'] = $arr;
            }else{
                $_SESSION['gxsess']['val'] = $vars;
            }

        }

    }


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


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

	$person_id = DBSeqNextID( 'people_person_id_seq' );

	$sql = "INSERT INTO PEOPLE ";

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

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

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

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

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

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

	DBQuery( $sql );

	return $person_id;
}


private function writeComment(Worksheet $pSheet, $coordinate)
    {
        $result = '';
        if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) {
            $result .= '';
            $result .= '
' . nl2br($pSheet->getComment($coordinate)->getText()->getPlainText()) . '
';
            $result .= PHP_EOL;
        }

        return $result;
    }


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

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

        $out = $DB->result();

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

        return $out;
    }


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


    public static function makeSafeFilename($filename)
    {
        /* Strip out *nix directories. */
        $filenameParts = explode('/', $filename);
        $filename = end($filenameParts);

        /* Strip out Windows directories. */
        $filenameParts = explode('\\', $filename);
        $filename = end($filenameParts);

        /* Strip out non-ASCII characters. */
        for ($i = 0; $i < strlen($filename); $i++)
        {
            if (ord($filename[$i]) >= 128 || ord($filename[$i]) < 32)
            {
                $filename[$i] = '_';
            }
        }

        /* Is the file extension safe? */
        $fileExtension = self::getFileExtension($filename);
        if (in_array($fileExtension, $GLOBALS['badFileExtensions']))
        {
            $filename .= '.txt';
        }

        return $filename;
    }


	public function updateTab($id, $array)
	{
		if (!$id || $id == '') {
			$this->setAPIResponse('error', 'id was not set', 422);
			return null;
		}
		if (!$array) {
			$this->setAPIResponse('error', 'no data was sent', 422);
			return null;
		}
		$tabInfo = $this->getTabById($id);
		if ($tabInfo) {
			$array = $this->checkKeys($tabInfo, $array);
		} else {
			$this->setAPIResponse('error', 'No tab info found', 404);
			return false;
		}
		if (array_key_exists('name', $array)) {
			$array['name'] = htmlspecialchars($array['name']);
			if ($this->isTabNameTaken($array['name'], $id)) {
				$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
				return false;
			}
		}
		if (array_key_exists('default', $array)) {
			if ($array['default']) {
				$this->clearTabDefault();
			}
		}
		$response = [
			array(
				'function' => 'query',
				'query' => array(
					'UPDATE tabs SET',
					$array,
					'WHERE id = ?',
					$id
				)
			),
		];
		$this->setAPIResponse(null, 'Tab info updated');
		$this->setLoggerChannel('Tab Management');
		$this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
		return $this->processQueries($response);
	}


$contents = ['form' => tep_draw_form('manufacturers', 'manufacturers.php', 'page=' . $_GET['page'] . '&mID=' . $mInfo->manufacturers_id . '&action=save', 'post', 'enctype="multipart/form-data"')];


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


    protected function moveVotes()
    {
        $sql = "SELECT * FROM package_proposal_votes WHERE pkg_prop_id = {$this->proposal}";
        $res = $this->mdb2->query($sql);
        if (MDB2::isError($res)) {
            throw new RuntimeException("DB error occurred: {$res->getDebugInfo()}");
        }
        if ($res->numRows() == 0) {
            return; // nothing to do
        }

        $insert  = "INSERT INTO package_proposal_comments (";
        $insert .= "user_handle, pkg_prop_id, timestamp, comment";
        $insert .= ") VALUES(%s, {$this->proposal}, %d, %s)";

        $delete  = "DELETE FROM package_proposal_votes WHERE";
        $delete .= " pkg_prop_id = {$this->proposal}";
        $delete .= " AND user_handle = %s";

        while ($row = $res->fetchRow(MDB2_FETCHMODE_OBJECT)) {

            $comment  = "Original vote: {$row->value}\n";
            $comment .= "Conditional vote: " . ($row->is_conditional != 0)?'yes':'no' . "\n";
            $comment .= "Comment on vote: " . $row->comment . "\n\n";
            $comment .= "Reviewed: " . implode(", ", unserialize($row->reviews));

            $sql = sprintf(
                $insert,
                $this->mdb2->quote($row->user_handle),
                $row->timestamp,
                $this->mdb2->quote($comment)
            );
            $this->queryChange($sql);

            $sql = sprintf(
                $delete,
                $this->mdb2->quote($row->user_handle)
            );
            $this->queryChange($sql);
        }


    public function update()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);
        $values = $this->request->getValues();
        list($valid, $errors) = $this->tagValidator->validateModification($values);

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

        if ($valid) {
            if ($this->tagModel->update($values['id'], $values['name'])) {
                $this->flash->success(t('Tag updated successfully.'));
            } else {
                $this->flash->failure(t('Unable to update this tag.'));
            }

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


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


function dol_print_error($db='',$error='')
{
	global $conf,$langs,$argv;
	global $dolibarr_main_prod;

	$out = '';
	$syslog = '';

	// Si erreur intervenue avant chargement langue
	if (! $langs)
	{
		require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
		$langs = new Translate('', $conf);
		$langs->load("main");
	}
	$langs->load("main");
	$langs->load("errors");

	if ($_SERVER['DOCUMENT_ROOT'])    // Mode web
	{
		$out.=$langs->trans("DolibarrHasDetectedError").".
\n";
		if (! empty($conf->global->MAIN_FEATURES_LEVEL))
		$out.="You use an experimental level of features, so please do NOT report any bugs, anywhere, until going back to MAIN_FEATURES_LEVEL = 0.
\n";
		$out.=$langs->trans("InformationToHelpDiagnose").":
\n";

		$out.="".$langs->trans("Date").": ".dol_print_date(time(),'dayhourlog')."
\n";;
		$out.="".$langs->trans("Dolibarr").": ".DOL_VERSION."
\n";;
		if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="".$langs->trans("LevelOfFeature").": ".$conf->global->MAIN_FEATURES_LEVEL."
\n";;
		if (function_exists("phpversion"))
		{
			$out.="".$langs->trans("PHP").": ".phpversion()."
\n";
			//phpinfo();       // This is to show location of php.ini file
		}
		$out.="".$langs->trans("Server").": ".$_SERVER["SERVER_SOFTWARE"]."
\n";;
		$out.="
\n";
		$out.="".$langs->trans("RequestedUrl").": ".$_SERVER["REQUEST_URI"]."
\n";;
		$out.="".$langs->trans("Referer").": ".(isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:'')."
\n";;
		$out.="".$langs->trans("MenuManager").": ".$conf->top_menu."
\n";
		$out.="
\n";
		$syslog.="url=".$_SERVER["REQUEST_URI"];
		$syslog.=", query_string=".$_SERVER["QUERY_STRING"];
	}


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

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

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

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


        function scan_page($parent_id) {
            global $db;

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


    public static function create() {
        $length = "80";
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
        $codeAlphabet.= "0123456789";
        // $codeAlphabet.= "!@#$%^&*()[]\/{}|:\<>";
        //$codeAlphabet.= SECURITY_KEY;
        for($i=0;$i<$length;$i++){
            $token .= $codeAlphabet[Typo::crypto_rand_secure(0,strlen($codeAlphabet))];
        }
        $url = $_SERVER['REQUEST_URI'];
        $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
        $ip = $_SERVER['REMOTE_ADDR'];
        $time = time();
        define('TOKEN', $token);
        define('TOKEN_URL', $url);
        define('TOKEN_IP', $ip);
        define('TOKEN_TIME', $time);
        $json = self::json();
        Options::update('tokens',$json);
        return $token;
    }


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


    protected function itemLock($hashes, $autoUnlock = true)
    {
        if (!elFinder::$commonTempPath) {
            return;
        }
        if (!is_array($hashes)) {
            $hashes = array($hashes);
        }
        foreach ($hashes as $hash) {
            $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
            if ($this->itemLocked($hash)) {
                $cnt = file_get_contents($lock) + 1;
            } else {
                $cnt = 1;
            }
            if (file_put_contents($lock, $cnt, LOCK_EX)) {
                if ($autoUnlock) {
                    $this->autoUnlocks[] = $hash;
                }
            }
        }
    }


    public static function _date2timestamp( $datetime, $wtz=null ) {
      if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
      if( !isset( $datetime['min'] ))  $datetime['min']  = 0;
      if( !isset( $datetime['sec'] ))  $datetime['sec']  = 0;
      if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty(  $datetime['tz'] )))
        return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      $output = $offset = 0;
      if( empty( $wtz )) {
        if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
          $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
          $wtz    = 'UTC';
        }
        else
          $wtz    = $datetime['tz'];
      }
      if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
        $wtz      = 'UTC';
      try {
        $strdate  = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
        $d        = new DateTime( $strdate, new DateTimeZone( $wtz ));
        if( 0    != $offset )  // adjust for offset
          $d->modify( $offset.' seconds' );
        $output   = $d->format( 'U' );
        unset( $d );
      }
      catch( Exception $e ) {
        $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      }
      return $output;
    }


	public function get_items( $request ) {

		$sked = get_template_sked( $request['post_id'] );

		return new WP_REST_Response( $sked, 200 );

	}


    private function buildUri($uri, array $config)
    {
        if (!isset($config['base_uri'])) {
            return $uri instanceof UriInterface ? $uri : new Psr7\Uri($uri);
        }

        return Psr7\Uri::resolve(Psr7\uri_for($config['base_uri']), $uri);
    }


	public function update() {
        global $user;

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


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

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

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

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

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

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

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

	return $navibars->generate();

}


    public function index(Request $request)
    {

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

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


    public static function config($var) {

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

            include($file);

        }

    }


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


function html_edit_form($param) {
    global $TEXT;

    if ($param['target'] !== 'section') {
        msg('No editor for edit target ' . $param['target'] . ' found.', -1);
    }

    $attr = array('tabindex'=>'1');
    if (!$param['wr']) $attr['readonly'] = 'readonly';

    $param['form']->addElement(form_makeWikiText($TEXT, $attr));
}


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

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

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


				} elseif (!is_numeric($item) && ($item != '')) {
					return false;
				}
			}
		} else {
			return false;
		}
	} else {


    public function __construct(){

    }


    public function breadcrumb() {
        global $sectionObj;

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


    function categoryBreadcrumb() {
//        global $db, $router;

        //eDebug($this->category);

        /*if(isset($router->params['action']))
        {
            $ancestors = $this->category->pathToNode();
        }else if(isset($router->params['section']))
        {
            $current = $db->selectObject('section',' id= '.$router->params['section']);
            $ancestors[] = $current;
            if( $current->parent != -1 || $current->parent != 0 )
            {
                while ($db->selectObject('section',' id= '.$router->params['section']);)
                    if ($section->id == $id) {
                        $current = $section;
                        break;
                    }
                }
            }
            eDebug($sections);
            $ancestors = $this->category->pathToNode();
        }*/

        $ancestors = $this->category->pathToNode();
        // eDebug($ancestors);
        assign_to_template(array(
            'ancestors' => $ancestors
        ));
    }


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


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

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


	public function update_groupdiscounts() {
	    global $db;

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

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


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

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


                ";
            }
            $html .= "
";
            Hooks::attach('footer_load_lib', array('Language', 'flagLib'));
        }

        return $html;
    }


function check_app_exists($uniq_name, $bdd)
{
	$sql = "select count(*) from bp where name = '" . $uniq_name . "';";
	$req = $bdd->query($sql);
	$bp_exist = $req->fetch(PDO::FETCH_NUM);

	if($bp_exist[0] == 1){
		echo "true";
	} else {
		echo "false";
	}
}


function process_tasks($task)
{
    global $send;
    /**
     *  First see if the doc_ID exists
     *  if not we need to create this
     */
    $task = make_document($task);
    update_taskman($task, 'created', '1');
    if ($task['DOC_TYPE'] == 'Fax') {
        deliver_document($task);
    }

    update_taskman($task, 'completed', '1');

    if ($task['DOC_TYPE'] == "Fax") {
        //now return any objects you need to Eye Form
        $send['DOC_link'] = "

							";
                            //if we want a "resend" icon, add it here.
    }

    return $send;
}


	protected function _fopen($path, $mode='rb') {
		// try ftp stream wrapper
		if ($this->options['mode'] == 'passive' && ini_get('allow_url_fopen')) {
			$url = 'ftp://'.$this->options['user'].':'.$this->options['pass'].'@'.$this->options['host'].':'.$this->options['port'].$path;
			if (strtolower($mode[0]) === 'w') {
				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
				$fp = @fopen($url, $mode, false, $context);
			} else {
				$fp = @fopen($url, $mode);
			}
			if ($fp) {
				return $fp;
			}
		}

		if ($this->tmp) {
			$local = $this->getTempFile($path);
			$fp = @fopen($local, 'wb');
			if (ftp_fget($this->connect, $fp, $path, FTP_BINARY)) {
				fclose($fp);
				$fp = fopen($local, $mode);
				return $fp;
			}
			@fclose($fp);
			is_file($local) && @unlink($local);
		}

		return false;
	}


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

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

        return $link;
    }


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

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

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

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


	protected function _dimensions($path, $mime) {
		clearstatcache();
		return strpos($mime, 'image') === 0 && ($s = @getimagesize($path)) !== false
			? $s[0].'x'.$s[1]
			: false;
	}


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

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

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

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


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


    public function setText($text)
    {
        $return = $this->setOneToOne($text, Text::class, 'text', 'container');
        $this->setType('ctText');

        return $return;
    }


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


function draw_vdef_preview($vdef_id) {
	?>

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

	<?php
}


    public function detach()
    {
        global $zdb, $hist;

        try {
            $update = $zdb->update(self::TABLE);
            $update->set(
                array('parent_group' => new Expression('NULL'))
            )->where(
                self::PK . ' = ' . $this->id
            );

            $edit = $zdb->execute($update);

            //edit == 0 does not mean there were an error, but that there
            //were nothing to change
            if ($edit->count() > 0) {
                $this->parent_group = null;
                $hist->add(
                    _T("Group has been detached from its parent"),
                    $this->group_name
                );
            }

            return true;
        } catch (Throwable $e) {
            Analog::log(
                'Something went wrong detaching group `' . $this->group_name .
                '` (' . $this->id . ') from its parent:\'( | ' .
                $e->getMessage() . "\n" .
                $e->getTraceAsString(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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


	protected function _basename($path) {
		return basename($path);
	}


	protected function _dirname($path) {
		return dirname($path);
	}


    private function transfer(RequestInterface $request, array $options)
    {
        // save_to -> sink
        if (isset($options['save_to'])) {
            $options['sink'] = $options['save_to'];
            unset($options['save_to']);
        }

        // exceptions -> http_error
        if (isset($options['exceptions'])) {
            $options['http_errors'] = $options['exceptions'];
            unset($options['exceptions']);
        }

        $request = $this->applyOptions($request, $options);
        $handler = $options['handler'];

        try {
            return Promise\promise_for($handler($request, $options));
        } catch (\Exception $e) {
            return Promise\rejection_for($e);
        }
    }


    public static function isActive () {
        switch (SMART_URL) {
            case true:
                if (Options::v('multilang_enable') === 'on') {
                    $langs = Session::val('lang');
                    if($langs != '') {
                        $lang = Session::val('lang');
                    }else{
                        $lang = '';
                    }

                }else{
                    $lang = '';
                }

                break;

            default:
                if (Options::v('multilang_enable') === 'on') {
                    $langs = Session::val('lang');
                    if($langs != '') {
                        $lang = Session::val('lang');
                    }else{
                        $lang = isset($_GET['lang'])? $_GET['lang']: '' ;
                    }
                }else{
                    $lang = '';
                }
                break;

        }
        return $lang;
    }


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

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

        return $drop;
    }


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

        parent::saveConfig();
    }


    public function update()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);
        $values = $this->request->getValues();
        list($valid, $errors) = $this->tagValidator->validateModification($values);

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

        if ($valid) {
            if ($this->tagModel->update($values['id'], $values['name'])) {
                $this->flash->success(t('Tag updated successfully.'));
            } else {
                $this->flash->failure(t('Unable to update this tag.'));
            }

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


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


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


function commit_criteria_list_to_query($criteria_list)
{
    $criteria_list = str_replace('>', ' ASC', $criteria_list);
    $criteria_list = str_replace('<', ' DESC', $criteria_list);

    return $criteria_list;
}


public function showCredits() {
		?>

<?php _e('Thank you very much for your donation', 'wp-piwik'); ?>: Marco L., Rolf W., Tobias U., Lars K., Donna F., Kevin D., Ramos S., Thomas M., John C., Andreas G., Ben M., Myra R. I., Carlos U. R.-S., Oleg I., M. N., Daniel K., James L., Jochen K., Cyril P., Thomas K., Patrik K., <?php _e('the Piwik team itself','wp-piwik');?><?php _e(', and all people flattering this','wp-piwik'); ?>!

<?php _e('Graphs powered by jqPlot (License: GPL 2.0 and MIT) and jQuery Sparklines (License: New BSD License).','wp-piwik'); ?>

<?php _e('Metabox support inspired by', 'wp-piwik'); echo ' Heiko Rabe\'s metabox demo plugin.';?>

<?php _e('Tabbed settings page suggested by the', 'wp-piwik'); echo' Smashing Magazine.';?>

<?php _e('Thank you very much','wp-piwik'); ?>, Besnik Bleta, FatCow, Rene, Fab, EzBizNiz, Gormer, Natalya, AggelioPolis, Web Hosting Geeks, Web Hosting Rating, Nata Strazda (Web Hosting Hub), Hossein (LibreOffice localization team), Ste & Chris <?php _e('for your translation work','wp-piwik'); ?>!

<?php _e('Thank you very much, all users who send me mails containing criticism, commendation, feature requests and bug reports! You help me to make WP-Piwik much better.','wp-piwik'); ?>

<?php _e('Thank you for using my plugin. It is the best commendation if my piece of code is really used!','wp-piwik'); ?>

		<?php
	}


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


    function manage() {
        global $db, $router, $user;

        expHistory::set('manageable', $router->params);
        assign_to_template(array(
            'canManageStandalones' => self::canManageStandalones(),
            'sasections'           => $db->selectObjects('section', 'parent=-1'),
            'user'                 => $user,
//            'canManagePagesets'    => $user->isAdmin(),
//            'templates'            => $db->selectObjects('section_template', 'parent=0'),
        ));
    }


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

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


	public function approvedFileExtension($filename, $type = 'image')
	{
		$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		if ($type == 'image') {
			switch ($ext) {
				case 'gif':
				case 'png':
				case 'jpeg':
				case 'jpg':
				case 'svg':
					return true;
				default:
					return false;
			}
		} elseif ($type == 'cert') {
			switch ($ext) {
				case 'pem':
					return true;
				default:
					return false;
			}
		}
	}


            $class = $container->getParameterBag()->resolveValue($def->getClass());

            $refClass = new \ReflectionClass($class);
            $interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
            if (!$refClass->implementsInterface($interface)) {
                throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
            }

            $definition->addMethodCall('addSubscriberService', array($id, $class));
        }


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

        $this->proxy->setActive(true);
        $this->assertTrue($this->proxy->isActive());
        $this->proxy->setActive(false);
        $this->assertFalse($this->proxy->isActive());
    }


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

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

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


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


	public function query($sql, $fetch_mode='object')
	{
		$this->lastError = '';
		$this->lastResult = '';

		switch($fetch_mode)
		{
			case 'array':
				$fetch = PDO::FETCH_ASSOC;
				break;

			case 'object':
			default:
				$fetch = PDO::FETCH_OBJ;
				break;
		}

		try
		{
			$statement = $this->db->query($sql);
			$this->queries_count++;

			// avoid firing a fatal error exception when the result is NULL
            // and the query is not malformed
			if(!$statement)
                return false;

			$statement->setFetchMode($fetch);
			$this->lastResult = $statement->fetchAll();
			$statement->closeCursor();
			unset($statement);
		}
		catch(PDOException $e)
		{
			$this->lastError = $e->getMessage();
		}
		catch(Exception $e)
		{
			return false;
		}

		return empty($this->lastError);
	}


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


    public function activate_discount(){
        if (isset($this->params['id'])) {
            $discount = new discounts($this->params['id']);
            $discount->update($this->params);
            //if ($discount->discountulator->hasConfig() && empty($discount->config)) {
                //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');
                //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));
            //}
        }

        expHistory::back();
    }


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


    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 function upload() {

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

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

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


	public function fixsessions() {
	    global $db;

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


    public function buildCurrentUrl() {
        $url =  URL_BASE;
        if ($this->url_style == 'sef') {
            $url .= substr(PATH_RELATIVE,0,-1).$this->sefPath;
        } else {
            $url .= urldecode((empty($_SERVER['REQUEST_URI'])) ? $_ENV['REQUEST_URI'] : $_SERVER['REQUEST_URI']);
        }
        return expString::escape(expString::sanitize($url));
    }


        $file = sprintf('%s/%s.class.php', $path, $class_name);
        if(is_file($file))
        {
            include_once $file;
        }

    }
}


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


   function prepareInputForAdd($input) {

      //If it's the first ldap directory then set it as the default directory
      if (!self::getNumberOfServers()) {
         $input['is_default'] = 1;
      }

      if (isset($input["rootdn_passwd"]) && !empty($input["rootdn_passwd"])) {
         $input["rootdn_passwd"] = Toolbox::encrypt(stripslashes($input["rootdn_passwd"]), GLPIKEY);
      }

      return $input;
   }


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


    public function update()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);
        $values = $this->request->getValues();
        list($valid, $errors) = $this->tagValidator->validateModification($values);

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

        if ($valid) {
            if ($this->tagModel->update($values['id'], $values['name'])) {
                $this->flash->success(t('Tag updated successfully.'));
            } else {
                $this->flash->failure(t('Unable to update this tag.'));
            }

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


	protected function _save($fp, $dir, $name, $stat) {
		$path = $this->_joinPath($dir, $name);

		$meta = stream_get_meta_data($fp);
		$uri = isset($meta['uri'])? $meta['uri'] : '';
		if ($uri && ! preg_match('#^[a-zA-Z0-9]+://#', $uri)) {
			@fclose($fp);
			$isCmdPaste = ($this->ARGS['cmd'] === 'paste');
			$isCmdCopy = ($isCmdPaste && empty($this->ARGS['cut']));
			if (($isCmdCopy || !@rename($uri, $path)) && !@copy($uri, $path)) {
				return false;
			}
			// re-create the source file for remove processing of paste command
			$isCmdPaste && !$isCmdCopy && touch($uri);
		} else {
			if (@file_put_contents($path, $fp, LOCK_EX) === false) {
				return false;
			}
		}

		@chmod($path, $this->options['fileMode']);
		clearstatcache();
		return $path;
	}


function db_case($array)
{
	global $DatabaseType;

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

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

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

			$counter++;
		}
	}

	return $string;
}


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


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


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


function db_seq_nextval($seqname)
{
    global $DatabaseType;

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

    return $seq;
}


function db_case($array)
{
    global $DatabaseType;

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

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

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

            $counter++;
        }
    }
    return $string;
}


    public function safePath($filename = 'data.csv'){
        return implode(DIRECTORY_SEPARATOR, array(
                    Yii::app()->basePath,
                    'data',
                    $filename
                ));
    }


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

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

        return $subtask;
    }


  public function __construct() {
    $this->smtp_conn = 0;
    $this->error = null;
    $this->helo_rply = null;

    $this->do_debug = 0;
  }


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


$a = ${($_ = isset($this->services['App\Registry']) ? $this->services['App\Registry'] : $this->getRegistryService()) && false ?: '_'};


    public function remove($transaction = true)
    {
        global $emitter;

        try {
            if ($transaction) {
                $this->zdb->connection->beginTransaction();
            }

            $delete = $this->zdb->delete(self::TABLE);
            $delete->where(self::PK . ' = ' . $this->_id);
            $del = $this->zdb->execute($delete);
            if ($del->count() > 0) {
                $this->updateDeadline();
                $this->dynamicsRemove(true);
            } else {
                Analog::log(
                    'Contribution has not been removed!',
                    Analog::WARNING
                );
                return false;
            }
            if ($transaction) {
                $this->zdb->connection->commit();
            }
            $emitter->emit('contribution.remove', $this);
            return true;
        } catch (Throwable $e) {
            if ($transaction) {
                $this->zdb->connection->rollBack();
            }
            Analog::log(
                'An error occurred trying to remove contribution #' .
                $this->_id . ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    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 static function getHelpVersion($version_id) {
        global $db;

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


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

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

        return $category;
    }


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

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


    public static function inc($vars, $data, $dir){
        $file = $dir."/".$vars.".php";
        if (file_exists($file)) {
            include($file);
        }
    }


                        foreach ($days as $value) {
                            $regitem[] = $value;
                        }


	protected function cacheDir($path) {
		$this->dirsCache[$path] = array();

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

		$res = $this->query($sql);
		if ($res) {
			while ($row = $res->fetch_assoc()) {
				// debug($row);
				$id = $row['id'];
				if ($row['parent_id']) {
					$row['phash'] = $this->encode($row['parent_id']);
				}

				if ($row['mime'] == 'directory') {
					unset($row['width']);
					unset($row['height']);
				} else {
					unset($row['dirs']);
				}

				unset($row['id']);
				unset($row['parent_id']);

				if (($stat = $this->updateCache($id, $row)) && empty($stat['hidden'])) {
					$this->dirsCache[$path][] = $id;
				}
			}
		}

		return $this->dirsCache[$path];
	}


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

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

        return $link;
    }


	private function LoadData()
	{
		$this->dataLoaded = true;

		$args = array();
		$args[] = '-s';
		$args[] = '-l';
		$args[] = $this->commitHash;
		$args[] = '--';
		$args[] = $this->path;

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

		$lastcommit = '';
		foreach ($blamelines as $line) {
			if (preg_match('/^([0-9a-fA-F]{40})(\s+.+)?\s+([0-9]+)\)/', $line, $regs)) {
				if ($regs[1] != $lastcommit) {
					$this->blame[(int)($regs[3])] = $regs[1];
					$lastcommit = $regs[1];
				}
			}
		}
	}


    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 getMailingVoucher($id)
    {
        trigger_error(sprintf('%s:%s is deprecated since Shopware 5.6 and will be private with 5.8.', __CLASS__, __METHOD__), E_USER_DEPRECATED);

        $sql = 'SELECT value FROM s_campaigns_containers WHERE type=? AND promotionID=?';
        $voucherID = Shopware()->Db()->fetchOne($sql, ['ctVoucher', $id]);
        if (empty($voucherID)) {
            return false;
        }
        $sql = "
            SELECT ev.*, 'VOUCHER123' as code
            FROM s_emarketing_vouchers ev
            WHERE  ev.modus = 1 AND (ev.valid_to >= CURDATE() OR ev.valid_to IS NULL)
            AND (ev.valid_from <= CURDATE() OR ev.valid_from IS NULL)
            AND ev.id=?
        ";

        return Shopware()->Db()->fetchRow($sql, [$voucherID]);
    }


public function remind()
	{
		/*if (!check_captcha())
		{
			$this->templatemanager->notify_next(__("You have entered wrong security code."), "error", __("Error!"));
			redirect("administration/auth/forgot");
			die;
		}//*/

		$email = trim($this->input->post("email", true));

		$u = User::factory()->get_by_email($email);

		if (!$u->exists())
		{
			$this->templatemanager->notify_next(__("User with that e-mail does not exists!"), "error", __("Error"));
			redirect("administration/auth/forgot");
		}

		$u->key = random_string('unique');
		$u->save();

		Log::write('requested password change', LogSeverity::Notice, $u->id);

		//set variables for template
		$vars = array(
			'name'=>$u->name
			,'email'=>$u->email

			,'website_title'=>Setting::value('website_title', CS_PRODUCT_NAME)
			,'reset_link'=>site_url('administration/auth/resetpass/'.$u->id.'/'.$u->key)
			,'site_url'=>site_url()
		);

		//get email template
		$template = file_get_contents(APPPATH . "templates/forgot_password.html");
		$template = __($template, null, 'email');
		$template .= "
\n
\n
\n" . __(file_get_contents(APPPATH . "templates/signature.html"), null, 'email');
		$template = parse_template($template, $vars);

		//send email
		$this->email->to("$email");
		$this->email->subject(__("%s password reset", Setting::value('website_title', CS_PRODUCT_NAME), 'email'));
		$this->email->message($template);
		$this->email->set_alt_message(strip_tags($template));

		$from = Setting::value("default_email", false);

		if (empty($from))
			$from = "noreply@".get_domain_name(true);

		$this->email->from($from);

		$sent = $this->email->send();

		if ($sent)
			$this->templatemanager->notify_next(__("Please check your e-mail for further information."), "notice", __("Notice"));
		else
			$this->templatemanager->notify_next(__("Activation e-mail could not be sent!"), "error", __("Error"));

		redirect("administration/auth/login");
	}


    public static function functionExist($var) {
        if (file_exists(GX_THEME.$var.'/function.php')) {
            return true;
        }else{
            return false;
        }

    }


    public static function filter() {
        //print_r(self::$hooks[$var]);
        $hooks = self::$hooks;
        $num_args = func_num_args();
        $args = func_get_args();
        // print_r($args);
        // if($num_args < 2)
        //     trigger_error("Insufficient arguments", E_USER_ERROR);

        // Hook name should always be first argument
        $hook_name = array_shift($args);

        if(!isset($hooks[$hook_name]))
            return; // No plugins have registered this hook
        // print_r($args[0]);
        // $args = (is_array($args))?$args[0]: $args;
        if (is_array($hooks[$hook_name])) {

            foreach($hooks[$hook_name] as $func){
                if ($func != '') {
                    // $args = call_user_func_array($func, $args); //
                    $args = $func((array)$args);
                }else{
                    $args = $args;
                }

            }

            $args = $args;
        }else{
            $args = $args;
        }

        $args = is_array($args)?  $args[0]:  $args;
        return $args;
    }


	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 getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
    {
        $str = '';

        if ($title !== false && $title instanceof Title) {
            $str .= $title->tshort . ' ';
        }

        $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
            ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");

        if ($id !== false || $nick !== false) {
            $str .= ' (';
        }
        if ($nick !== false) {
            $str .= $nick;
        }
        if ($id !== false) {
            if ($nick !== false && !empty($nick)) {
                $str .= ', ';
            }
            $str .= $id;
        }
        if ($id !== false || $nick !== false) {
            $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 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']),
        )));
    }


            $comments->records[$key]->avatar = $db->selectObject('user_avatar',"user_id='".$record->poster."'");
        }

        if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);
        // eDebug($sql, true);

        // count the unapproved comments
        if ($require_approval == 1 && $user->isAdmin()) {
            $sql  = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';
            $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';
            $sql .= 'WHERE cnt.content_id='.$this->params['content_id']." AND cnt.content_type='".$this->params['content_type']."' ";
            $sql .= 'AND com.approved=0';
            $unapproved = $db->countObjectsBySql($sql);
        } else {
            $unapproved = 0;
        }

        $this->config = $this->params['config'];
        $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');
        $ratings = !empty($this->params['ratings']) ? true : false;

        assign_to_template(array(
            'comments'=>$comments,
            'config'=>$this->params['config'],
            'unapproved'=>$unapproved,
			'content_id'=>$this->params['content_id'],
			'content_type'=>$this->params['content_type'],
			'user'=>$user,
			'hideform'=>$this->params['hideform'],
			'hidecomments'=>$this->params['hidecomments'],
			'title'=>$this->params['title'],
			'formtitle'=>$this->params['formtitle'],
            'type'=>$type,
            'ratings'=>$ratings,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
		));
	}


    function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
        if (empty($endtimestamp)) {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
        } else {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
        }
        if ($multiday)
            $date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
        $date_sql .= ")";
        return $date_sql;
    }


function _makeMpName($value) {
    if ($value != '') {
        $get_name = DBGet(DBQuery('SELECT TITLE FROM marking_periods WHERE marking_period_id=' . $value));
        return $get_name[1]['TITLE'];
    } else
        return ''._customCoursePeriod.'';
}


$instance->processor = [0 => ${($_ = isset($this->services['App\Db']) ? $this->services['App\Db'] : $this->getDbService()) && false ?: '_'}, 1 => ${($_ = isset($this->services['App\Bus']) ? $this->services['App\Bus'] : $this->getBusService()) && false ?: '_'}];


	public function get($extramediatypes = false) {
		try {
			return $this->getConfig($extramediatypes);
		} catch (\Exception $exception) {
			return $this->jsonError($exception);
		}
	}


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

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

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


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


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 referenceFixtures() {
        return array(
            'campaign' => array ('Campaign', '.CampaignMailingBehaviorTest'),
            'lists' => 'X2List',
            'credentials' => 'Credentials',
            'users' => 'User',
            'profile' => array('Profile','.marketing')
        );
    }


	protected function readlink($path) {
		if (!($target = @readlink($path))) {
			return null;
		}

		if (strpos($target, $this->systemRoot) !== 0) {
			$target = $this->_joinPath(dirname($path), $target);
		}

		if (!file_exists($target)) {
			return false;
		}

		return $target;
	}


    static function isSearchable() {
        return true;
    }


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

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

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


    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 backup($type='json')
    {
        global $DB;
        global $website;

        $out = array();

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

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

        return $out;
    }


    public function testIsActivePhp54()
    {
        $this->assertFalse($this->proxy->isActive());
        session_start();
        $this->assertTrue($this->proxy->isActive());
    }


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


    public function getSelectorsBySpecificity($sSpecificitySearch = null) {
        if (is_numeric($sSpecificitySearch) || is_numeric($sSpecificitySearch[0])) {
            $sSpecificitySearch = "== $sSpecificitySearch";
        }
        $aResult = array();
        $this->allSelectors($aResult, $sSpecificitySearch);
        return $aResult;
    }


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


    public function testConstruct()
    {
        $storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir()));

        if (PHP_VERSION_ID < 50400) {
            $this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
            $this->assertEquals('files', ini_get('session.save_handler'));
        } else {
            $this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
            $this->assertEquals('user', ini_get('session.save_handler'));
        }

        $this->assertEquals(sys_get_temp_dir(), ini_get('session.save_path'));
        $this->assertEquals('TESTING', ini_get('session.name'));
    }


    public function __construct () {
        if (self::existConf()) {
            # code...
            self::config('config');
            self::lang(GX_LANG);
        }else{
            GxMain::install();
        }

    }


function form_confirm_buttons($action_url, $cancel_url) {
	global $config;
	?>

			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $cancel_url);?>")' value='<?php print __esc('Cancel');?>'>
			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $action_url . '&confirm=true');?>")' value='<?php print __esc('Delete');?>'>

<?php }


    function delete() {
        global $db;

        if (empty($this->params['id'])) return false;
        $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);
        $product = new $product_type($this->params['id'], true, false);
        //eDebug($product_type);
        //eDebug($product, true);
        //if (!empty($product->product_type_id)) {
        //$db->delete($product_type, 'id='.$product->product_id);
        //}

        $db->delete('option', 'product_id=' . $product->id . " AND optiongroup_id IN (SELECT id from " . $db->prefix . "optiongroup WHERE product_id=" . $product->id . ")");
        $db->delete('optiongroup', 'product_id=' . $product->id);
        //die();
        $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type="' . $product_type . '"');

        if ($product->product_type == "product") {
            if ($product->hasChildren()) {
                $this->deleteChildren();
            }
        }

        $product->delete();

        flash('message', gt('Product deleted successfully.'));
        expHistory::back();
    }


			moveup = function(hash) {
				var self = $('#'+hash2id(hash)),
					tgt  = self.parent(),
					prev = tgt.prev('div'),
					cls  = 'ui-state-hover',
					ctm  = fm.getUI('contextmenu');

				menuTimer && clearTimeout(menuTimer);

				if (prev.length) {
					ctm.find(':first').data('placesHash', hash);
					self.addClass(cls);
					tgt.insertBefore(prev);
					prev = tgt.prev('div');
					menuTimer = setTimeout(function() {
						self.removeClass(cls);
						if (ctm.find(':first').data('placesHash') === hash) {
							ctm.hide().empty();
						}
					}, 1500);
				}

				if(!prev.length) {
					self.removeClass(cls);
					ctm.hide().empty();
				}
			},


    onIgnoreTagAttr(tag, name, value) {
      const forTag = allowList.attrList[tag];
      if (forTag) {
        const forAttr = forTag[name];
        if (
          (forAttr &&
            (forAttr.indexOf("*") !== -1 || forAttr.indexOf(value) !== -1)) ||
          (name.indexOf("data-") === 0 && forTag["data-*"]) ||
          (tag === "a" &&
            name === "href" &&
            hrefAllowed(value, extraHrefMatchers)) ||
          (tag === "img" &&
            name === "src" &&
            (/^data:image.*$/i.test(value) ||
              hrefAllowed(value, extraHrefMatchers))) ||
          (tag === "iframe" &&
            name === "src" &&
            allowedIframes.some((i) => {
              return value.toLowerCase().indexOf((i || "").toLowerCase()) === 0;
            }))
        ) {
          return attr(name, value);
        }

        if (tag === "iframe" && name === "src") {
          return "-STRIP-";
        }

        if (tag === "video" && name === "autoplay") {
          // This might give us duplicate 'muted' attributes
          // but they will be deduped by later processing
          return "autoplay muted";
        }

        // Heading ids must begin with `heading--`
        if (
          ["h1", "h2", "h3", "h4", "h5", "h6"].indexOf(tag) !== -1 &&
          value.match(/^heading\-\-[a-zA-Z0-9\-\_]+$/)
        ) {
          return attr(name, value);
        }

        const custom = allowLister.getCustom();
        for (let i = 0; i < custom.length; i++) {
          const fn = custom[i];
          if (fn(tag, name, value)) {
            return attr(name, value);
          }
        }
      }
    },


NewListFromSelection.prototype.convertToAddToList = function (listId, dialogState) {
    var that = this;
    var addToList = this.massActionsManager.massActionObjects['addToList'];
    var newListName = this.dialogElem$.find ('.new-list-name');
    var listName = $(newListName).val ();
    addToList.addListOption (listId, listName);
    addToList.setListId (listId);
    addToList.progressBar = this.progressBar;
    addToList.recordCount = this.recordCount;
    dialogState.superExecuteParams.listId = listId;
    dialogState.superExecuteParams.massAction = addToList.massActionName;

    return addToList;
};


module.exports.getTestMessageUrl = function(info) {
    if (!info || !info.response) {
        return false;
    }

    let infoProps = new Map();
    info.response.replace(/\[([^\]]+)\]$/, (m, props) => {
        props.replace(/\b([A-Z0-9]+)=([^\s]+)/g, (m, key, value) => {
            infoProps.set(key, value);
        });
    });

    if (infoProps.has('STATUS') && infoProps.has('MSGID')) {
        return (testAccount.web || ETHEREAL_WEB) + '/message/' + infoProps.get('MSGID');
    }

    return false;
};


export const redirectAnyRequest = response => {
  const {headers: {location}} = Response.message (response);
  const original = Response.request (response);
  const oldUrl = Request.url (original);
  const newUrl = mergeUrls (oldUrl) (location);
  return (Request (Request.options (original))
                  (newUrl)
                  (Request.body (original)));
};


							var itemClicked = function(evt)
							{
								if (evt == null || mxEvent.getSource(evt).nodeName != 'INPUT')
								{
									preview.style.textAlign = 'center';
									preview.style.padding = '0px';
									preview.style.color = '';
									preview.innerHTML = '';

									if (entry.desc != null)
									{
										var pre = document.createElement('pre');
										pre.style.boxSizing = 'border-box';
										pre.style.fontFamily = 'inherit';
										pre.style.margin = '20px';
										pre.style.right = '0px';
										pre.style.textAlign = 'left';
										mxUtils.write(pre, entry.desc);
										preview.appendChild(pre);
									}

									if (entry.imageCallback != null)
									{
										entry.imageCallback(preview);
									}
									else if (entry.image != null)
									{
										preview.innerHTML += '<img border="0" src="' + entry.image + '"/>';
									}
									else if (entry.desc == null)
									{
										preview.style.padding = '20px';
										preview.style.color = 'rgb(179, 179, 179)';
										mxUtils.write(preview, mxResources.get('noPreview'));
									}

									if (currentListItem != null)
									{
										currentListItem.style.backgroundColor = '';
									}

									currentListItem = option;
									currentListItem.style.backgroundColor = Editor.isDarkMode() ? '#000000' : '#ebf2f9';

									if (evt != null)
									{
										mxEvent.consume(evt);
									}
								}
							};


    $scope.delete = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteRequisition(foreignSource).then(
            function() { // success
              growl.success('The requisition ' + foreignSource + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = core_slice.call( arguments ),
			length = resolveValues.length,

			// the count of uncompleted subordinates
			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

			// Update function for both resolve and progress values
			updateFunc = function( i, contexts, values ) {
				return function( value ) {
					contexts[ i ] = this;
					values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
					if( values === progressValues ) {
						deferred.notifyWith( contexts, values );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( contexts, values );
					}
				};
			},

			progressValues, progressContexts, resolveContexts;

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			progressValues = new Array( length );
			progressContexts = new Array( length );
			resolveContexts = new Array( length );
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressContexts, progressValues ) );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( resolveContexts, resolveValues );
		}

		return deferred.promise();
	}


  constructor () {
    this.LOG_DISABLE = constant.LOG_DISABLE
    this.LOG_ERROR = constant.LOG_ERROR
    this.LOG_WARN = constant.LOG_WARN
    this.LOG_INFO = constant.LOG_INFO
    this.LOG_DEBUG = constant.LOG_DEBUG

    // DEFAULT CONFIG
    this.frameworks = []
    this.protocol = 'http:'
    this.port = constant.DEFAULT_PORT
    this.listenAddress = constant.DEFAULT_LISTEN_ADDR
    this.hostname = constant.DEFAULT_HOSTNAME
    this.httpsServerConfig = {}
    this.basePath = ''
    this.files = []
    this.browserConsoleLogOptions = {
      level: 'debug',
      format: '%b %T: %m',
      terminal: true
    }
    this.customContextFile = null
    this.customDebugFile = null
    this.customClientContextFile = null
    this.exclude = []
    this.logLevel = constant.LOG_INFO
    this.colors = true
    this.autoWatch = true
    this.autoWatchBatchDelay = 250
    this.restartOnFileChange = false
    this.usePolling = process.platform === 'linux'
    this.reporters = ['progress']
    this.singleRun = false
    this.browsers = []
    this.captureTimeout = 60000
    this.pingTimeout = 5000
    this.proxies = {}
    this.proxyValidateSSL = true
    this.preprocessors = {}
    this.preprocessor_priority = {}
    this.urlRoot = '/'
    this.upstreamProxy = undefined
    this.reportSlowerThan = 0
    this.loggers = [constant.CONSOLE_APPENDER]
    this.transports = ['polling', 'websocket']
    this.forceJSONP = false
    this.plugins = ['karma-*']
    this.defaultClient = this.client = {
      args: [],
      useIframe: true,
      runInParent: false,
      captureConsole: true,
      clearContext: true
    }
    this.browserDisconnectTimeout = 2000
    this.browserDisconnectTolerance = 0
    this.browserNoActivityTimeout = 30000
    this.processKillTimeout = 2000
    this.concurrency = Infinity
    this.failOnEmptyTestSuite = true
    this.retryLimit = 2
    this.detached = false
    this.crossOriginAttribute = true
    this.browserSocketTimeout = 20000
  }


OAuthServer.prototype.start = function(callback) {
    this.server = http.createServer((req, res) => {
        let data = [];
        let datalen = 0;

        req.on('data', chunk => {
            if (!chunk || !chunk.length) {
                return;
            }

            data.push(chunk);
            datalen += chunk.length;
        });

        req.once('end', () => {
            let query = querystring.parse(Buffer.concat(data, datalen).toString()),
                response = this.generateAccessToken(query.refresh_token);

            res.writeHead(!response.error ? 200 : 401, {
                'Content-Type': 'application/json'
            });

            res.end(JSON.stringify(response));
        });
    });

    this.server.listen(this.options.port, callback);
};