    private function getDefaultConf(EasyHandle $easy)
    {
        $conf = [
            '_headers'             => $easy->request->getHeaders(),
            CURLOPT_CUSTOMREQUEST  => $easy->request->getMethod(),
            CURLOPT_URL            => (string) $easy->request->getUri(),
            CURLOPT_RETURNTRANSFER => false,
            CURLOPT_HEADER         => false,
            CURLOPT_CONNECTTIMEOUT => 150,
        ];

        if (defined('CURLOPT_PROTOCOLS')) {
            $conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
        }

        $version = $easy->request->getProtocolVersion();
        if ($version == 1.1) {
            $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
        } elseif ($version == 2.0) {
            $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
        } else {
            $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
        }

        return $conf;
    }


function list_process($bp,$display,$bdd){
	$sql = "select name from bp where is_define = 1 and name!='".$bp."' and priority = '" . $display . "'";
	$req = $bdd->query($sql);
	$process = $req->fetchall();

    echo json_encode($process);
}


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

        // build out a SQL query that gets all the data we need and is sortable.
        $sql  = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';
        $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';
        $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type="banner")';

		$page = new expPaginator(array(
			'model'=>'banner',
			'sql'=>$sql,
			'order'=>'title',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
			'columns'=>array(
                gt('Title')=>'title',
                gt('Company')=>'companyname',
                gt('Impressions')=>'impressions',
                gt('Clicks')=>'clicks'
            )
        ));

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


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

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

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

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


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

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

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


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

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

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


    public static function remove_properties($element_type, $element_id, $website_id)
    {
        global $DB;
        global $website;

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

        webdictionary::save_element_strings('property-'.$element_type, $element_id, array());

        $DB->execute('
            DELETE FROM nv_properties_items
                  WHERE website = '.$website_id.'
                    AND element = '.protect($element_type).'
                    AND node_id = '.intval($element_id).'
        ');
    }


	public function uniqueName($dir, $name, $suffix = ' copy', $checkNum = true, $start = 1) {
		$ext  = '';

		if (preg_match('/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i', $name, $m)) {
			$ext  = '.'.$m[1];
			$name = substr($name, 0,  strlen($name)-strlen($m[0]));
		}

		if ($checkNum && preg_match('/('.preg_quote($suffix, '/').')(\d*)$/i', $name, $m)) {
			$i    = (int)$m[2];
			$name = substr($name, 0, strlen($name)-strlen($m[2]));
		} else {
			$i     = $start;
			$name .= $suffix;
		}
		$max = $i+100000;

		while ($i <= $max) {
			$n = $name.($i > 0 ? $i : '').$ext;

			if (!$this->stat($this->joinPathCE($dir, $n))) {
				$this->clearcache();
				return $n;
			}
			$i++;
		}


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

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

        return $subtask;
    }


static function isSearchable() { return true; }


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

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

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

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


static function convertXMLFeedSafeChar($str) {
		$str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace(""",'"',$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","'",$str);
        $str = str_replace("‘","'",$str);
        $str = str_replace("®","",$str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("”",'"', $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("“",'"', $str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


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

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

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


    private function addServiceInstance($id, Definition $definition, $isSimpleInstance)
    {
        $class = $this->dumpValue($definition->getClass());

        if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
            throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
        }

        $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
        $instantiation = '';

        if (!$isProxyCandidate && $definition->isShared()) {
            $instantiation = "\$this->services['$id'] = ".($isSimpleInstance ? '' : '$instance');
        } elseif (!$isSimpleInstance) {


    function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }


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


    public function testCanGiveCustomReason()
    {
        $r = new Response(200, [], null, '1.1', 'bar');
        $this->assertEquals('bar', $r->getReasonPhrase());
    }


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

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

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

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

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

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


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

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


function render_menu_tabs()
    {
        $current_tab = $this->get_current_tab();

        echo '
';
        foreach ( $this->menu_tabs as $tab_key => $tab_caption )
        {
            $active = $current_tab == $tab_key ? 'nav-tab-active' : '';
            echo 'menu_page_slug . '&tab=' . $tab_key . '">' . $tab_caption . '';
        }
        echo '
';
    }


	public function delete() {
	    global $db;

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

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

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

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

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


    public function skip($value)
    {
        return $this->offset($value);
    }


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

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

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


    public function store()
    {
        $title = $this->title;
        if ($title === null || trim($title) === '') {
            $title = new Expression('NULL');
        }

        $subtitle = $this->subtitle;
        if ($subtitle === null || trim($subtitle) === '') {
            $subtitle = new Expression('NULL');
        }

        $data = array(
            'model_header'      => $this->header,
            'model_footer'      => $this->footer,
            'model_type'        => $this->type,
            'model_title'       => $title,
            'model_subtitle'    => $subtitle,
            'model_body'        => $this->body,
            'model_styles'      => $this->styles
        );

        try {
            if ($this->id !== null) {
                $update = $this->zdb->update(self::TABLE);
                $update->set($data)->where(
                    self::PK . '=' . $this->id
                );
                $this->zdb->execute($update);
            } else {
                $data['model_name'] = $this->name;
                $insert = $this->zdb->insert(self::TABLE);
                $insert->values($data);
                $add = $this->zdb->execute($insert);
                if (!($add->count() > 0)) {
                    Analog::log('Not stored!', Analog::ERROR);
                    return false;
                }
            }
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred storing model: ' . $e->getMessage() .
                "\n" . print_r($data, true),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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

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


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

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

            //remove associated contributions if needeed
            if ($this->getDispatchedAmount() > 0) {
                $c = new Contributions($this->zdb, $this->login);
                $clist = $c->getListFromTransaction($this->_id);
                $cids = array();
                foreach ($clist as $cid) {
                    $cids[] = $cid->id;
                }
                $rem = $c->remove($cids, $hist, false);
            }

            //remove transaction itself
            $delete = $this->zdb->delete(self::TABLE);
            $delete->where(
                self::PK . ' = ' . $this->_id
            );
            $del = $this->zdb->execute($delete);
            if ($del->count() > 0) {
                $this->dynamicsRemove(true);
            } else {
                Analog::log(
                    'Transaction has not been removed!',
                    Analog::WARNING
                );
                return false;
            }

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

            $emitter->emit('transaction.remove', $this);
            return true;
        } catch (Throwable $e) {
            if ($transaction) {
                $this->zdb->connection->rollBack();
            }
            Analog::log(
                'An error occurred trying to remove transaction #' .
                $this->_id . ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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

        return $link;
    }


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


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

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

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

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

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


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


            $this->setType('folder');
        }

        // do not allow PHP and .htaccess files
        if (preg_match("@\.ph(p[\d+]?|t|tml|ps)$@i", $this->getFilename()) || $this->getFilename() == '.htaccess') {
            $this->setFilename($this->getFilename() . '.txt');
        }

        if(mb_strlen($this->getFilename()) > 255) {
            throw new \Exception('Filenames longer than 255 characters are not allowed');
        }

        if (Asset\Service::pathExists($this->getRealFullPath())) {
            $duplicate = Asset::getByPath($this->getRealFullPath());
            if ($duplicate instanceof Asset and $duplicate->getId() != $this->getId()) {
                throw new \Exception('Duplicate full path [ ' . $this->getRealFullPath() . ' ] - cannot save asset');
            }
        }

        $this->validatePathLength();
    }


							 * function my_query_args_filter( $field_query ) {
							 *     // your code here
							 *     return $field_query;
							 * }


  private function catchWarning ($errno, $errstr, $errfile, $errline) {
    $this->error[] = array(
      'error' => "Connecting to the POP3 server raised a PHP warning: ",
      'errno' => $errno,
      'errstr' => $errstr
    );
  }


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

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


	public function insert()
	{
		global $DB;

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

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

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

		return true;
	}


    public function avatar($avatar_name)
    {
        list($user_id,$size) = explode('_',str_replace(".jpg",'',$avatar_name));
        $avatarFile = storage_path('app/'.User::getAvatarPath($user_id,$size));
        if(!is_file($avatarFile)){
            $avatarFile = public_path('static/images/default_avatar.jpg');
        }
        $image =   Image::make($avatarFile);
        $response = response()->make($image->encode('jpg'));
        $image->destroy();
        $response->header('Content-Type', 'image/jpeg');
        $response->header('Expires',  date(DATE_RFC822,strtotime(" 2 day")));
        $response->header('Cache-Control', 'private, max-age=86400, pre-check=86400');
        return $response;
    }


    public static function insert($vars){
        if(is_array($vars)){
            $sql = array(
                        'table' => 'menus',
                        'key' => $vars
                    );
            $menu = Db::insert($sql);
        }
    }


	public function doConfigPageInit($page) {
		$action = isset($_REQUEST['action'])?$_REQUEST['action']:'';
		//the extension we are currently displaying
		$managerdisplay = isset($_REQUEST['managerdisplay'])?$_REQUEST['managerdisplay']:'';
		$name = isset($_REQUEST['name'])?$_REQUEST['name']:'';
		$secret = isset($_REQUEST['secret'])?$_REQUEST['secret']:'';
		$deny = isset($_REQUEST['deny'])?$_REQUEST['deny']:'0.0.0.0/0.0.0.0';
		$permit = isset($_REQUEST['permit'])?$_REQUEST['permit']:'127.0.0.1/255.255.255.0';
		$engineinfo = engine_getinfo();
		$writetimeout = isset($_REQUEST['writetimeout'])?$_REQUEST['writetimeout']:'100';
		$astver =  $engineinfo['version'];
		//if submitting form, update database
		global $amp_conf;
		if($action == 'add' || $action == 'delete') {
			$ampuser = $amp_conf['AMPMGRUSER'];
			if($ampuser == $name) {
				$action = 'conflict';
			}
		}
		switch ($action) {
		case "add":
			$rights = manager_format_in($_REQUEST);
			manager_add($name,$secret,$deny,$permit,$rights['read'],$rights['write'],$writetimeout);
			$_REQUEST['managerdisplay'] = $name;
			needreload();
			break;
		case "delete":
			manager_del($managerdisplay);
			needreload();
			break;
		case "edit":  //just delete and re-add
			manager_del($name);
			$rights = manager_format_in($_REQUEST);
			manager_add($name,$secret,$deny,$permit,$rights['read'],$rights['write'],$writetimeout);
			needreload();
			break;
		case "conflict":
			//do nothing we are conflicting with the FreePBX Asterisk Manager User
			break;
		}
	}


        foreach ($data['alertred'] as $alert) {
            # code...
            echo "<li>$alert</li>\n";
        }


    public static function createFromGlobals()
    {
        // With the php's bug #66606, the php's built-in web server
        // stores the Content-Type and Content-Length header values in
        // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields.
        $server = $_SERVER;
        if ('cli-server' === php_sapi_name()) {
            if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) {
                $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH'];
            }
            if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) {
                $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
            }
        }

        $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);

        if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
            && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
        ) {
            parse_str($request->getContent(), $data);
            $request->request = new ParameterBag($data);
        }

        return $request;
    }


    public function testGetAuthorityReturnsCorrectPort()
    {
        // HTTPS non-standard port
        $uri = new Uri('https://foo.co:99');
        $this->assertEquals('foo.co:99', $uri->getAuthority());

        // HTTP non-standard port
        $uri = new Uri('http://foo.co:99');
        $this->assertEquals('foo.co:99', $uri->getAuthority());

        // No scheme
        $uri = new Uri('foo.co:99');
        $this->assertEquals('foo.co:99', $uri->getAuthority());

        // No host or port
        $uri = new Uri('http:');
        $this->assertEquals('', $uri->getAuthority());

        // No host or port
        $uri = new Uri('http://foo.co');
        $this->assertEquals('foo.co', $uri->getAuthority());
    }


    public function testCanGetInstance()
    {
        static::assertInstanceOf('ShopwarePlugins\RestApi\Components\Router', $this->router);
    }


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

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

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


    public static function desc($vars){
        if(!empty($vars)){
            $desc = substr(strip_tags(htmlspecialchars_decode($vars).". ".self::$desc),0,150);
        }else{
            $desc = substr(self::$desc,0,150);
        }
        $desc = Hooks::filter('site_desc_filter', $desc);
        return $desc;
    }


public function printerFriendlyLink($link_text="Printer Friendly", $class=null, $width=800, $height=600, $view='', $title_text = "Printer Friendly") {
        $url = '';
        if (PRINTER_FRIENDLY != 1 && EXPORT_AS_PDF != 1) {
            $class = !empty($class) ? $class : 'printer-friendly-link';
            $url =  'url_style == 'sef') {
                $url .= $this->convertToOldSchoolUrl();
                if (empty($_REQUEST['view']) && !empty($view)) $url .= '&view='.$view;
                if ($this->url_type=='base') $url .= '/index.php?section='.SITE_DEFAULT_SECTION;
            } else {
                $url .= $this->current_url;
            }
            $url .= '&printerfriendly=1\' , \'mywindow\',\'menubar=1,resizable=1,scrollbars=1,width='.$width.',height='.$height.'\');"';
            $url .= ' title="'.$title_text.'"';
            $url .= '> '.$link_text.'';
            $url = str_replace('&ajax_action=1','',$url);
        }

        return $url;
    }


    protected function getJobIdFromWidgetConfiguration()
    {
        $sql = "SELECT *
                    FROM plugin_hudson_widget
                    WHERE widget_name = '" . db_es($this->widget_id) . "'
                      AND owner_id = " . db_ei($this->owner_id) . "
                      AND owner_type = '" . db_es($this->owner_type) . "'
                      AND id = " . db_ei($this->content_id);

        $res = db_query($sql);
        if ($res && db_numrows($res)) {
            $data   = db_fetch_array($res);
            return $data['job_id'];
        }

        return null;
    }


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


            $WHERE[] = ['NOT' => ['name' => $locks]];
         }

         // Build query for frequency and allowed hour
         $WHERE[] = ['OR' => [
            ['AND' => [
               ['hourmin'   => ['<', $DB->quoteName('hourmax')]],
               'hourmin'   => ['<=', $hour],
               'hourmax'   => ['>', $hour]
            ]],
            ['AND' => [
               'hourmin'   => ['>', $DB->quoteName('hourmax')],
               'OR'        => [
                  'hourmin'   => ['<=', $hour],
                  'hourmax'   => ['>', $hour]
               ]
            ]]
         ]];
         $WHERE[] = ['OR' => [
            'lastrun'   => null,
            new \QueryExpression('unix_timestamp(' . $DB->quoteName('lastrun') . ') + ' . $DB->quoteName('frequency') . ' <= unix_timestamp(now())')
         ]];
      }

      $iterator = $DB->request([
         'SELECT' => [
            '*',
            new \QueryExpression("LOCATE('Plugin', " . $DB->quoteName('itemtype') . ") AS ISPLUGIN")
         ],
         'FROM'   => $this->getTable(),
         'WHERE'  => $WHERE,
         // Core task before plugins
         'ORDER'  => [
            'ISPLUGIN',
            new \QueryExpression('unix_timestamp(' . $DB->quoteName('lastrun') . ')+' . $DB->quoteName('frequency') . '')
         ]
      ]);

      if (count($iterator)) {
         $this->fields = $iterator->next();
         return true;
      }
      return false;
   }


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


	protected function GetOrderedRefs($refList, $type, $order, $count = 0, $skip = 0)
	{
		if (!$refList)
			return;

		if (empty($type) || empty($order))
			return null;

		$args = array();
		$args[] = '--sort=' . $order;
		$args[] = '--format="%(refname)"';
		if ($count > 0) {
			if ($skip > 0) {
				$args[] = '--count=' . ($count + $skip);
			} else {
				$args[] = '--count=' . $count;
			}
		}


public function getDeleteItemLink($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=del&" . $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=del&" . $this->handler->keyName . "=" . $icmsObj->getVar($this->handler->keyName);
		}
		if ($onlyUrl) {
			return $ret;
		} elseif ($withimage) {
			return "
				";
		}

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


    public static function lists($vars) {

        return Categories::lists($vars);

    }


    public function getQuerySelect()
    {
        return '';
    }


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

        // set paths we will search in for the view
        $paths = array(
            BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',
            BASE.'framework/modules/common/views/file/configure',
        );

        foreach ($paths as $path) {
            $view = $path.'/'.$this->params['view'].'.tpl';
            if (is_readable($view)) {
                if (bs(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                if (bs3(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                $template = new controllertemplate($this, $view);
                $ar = new expAjaxReply(200, 'ok');
		        $ar->send();
            }
        }
    }


	protected function _normpath($path) {
		if (empty($path)) {
			return '.';
		}

		$changeSep = (DIRECTORY_SEPARATOR !== '/');
		if ($changeSep) {
			$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
		}

		if (strpos($path, '/') === 0) {
			$initial_slashes = true;
		} else {
			$initial_slashes = false;
		}

		if (($initial_slashes)
		&& (strpos($path, '//') === 0)
		&& (strpos($path, '///') === false)) {
			$initial_slashes = 2;
		}

		$initial_slashes = (int) $initial_slashes;

		$comps = explode('/', $path);
		$new_comps = array();
		foreach ($comps as $comp) {
			if (in_array($comp, array('', '.'))) {
				continue;
			}

			if (($comp != '..')
			|| (!$initial_slashes && !$new_comps)
			|| ($new_comps && (end($new_comps) == '..'))) {
				array_push($new_comps, $comp);
			} elseif ($new_comps) {
				array_pop($new_comps);
			}
		}
		$comps = $new_comps;
		$path = implode('/', $comps);
		if ($initial_slashes) {
			$path = str_repeat('/', $initial_slashes) . $path;
		}

		if ($changeSep) {
			$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
		}

		return $path ? $path : '.';
	}


	public function getImageSize($path, $mime = '') {
		$size = false;
		if ($mime === '' || strtolower(substr($mime, 0, 5)) === 'image') {
			if ($work = $this->getWorkFile($path)) {
				if ($size = @getimagesize($work)) {
					$size['dimensions'] = $size[0].'x'.$size[1];
				}
			}
			is_file($work) && @unlink($work);
		}
		return $size;
	}


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


                $removed[] = $fi->getFilename();
            }
            if ($removed = implode(', ', $removed)) {
                $result .= $removed . ' ' . dgettext('tuleap-tracker', 'removed');
            }

            $added = $this->fetchAddedFiles(array_diff($this->files, $changeset_value->getFiles()), $format, $is_for_mail);
            if ($added && $result) {
                $result .= $format === 'html' ? '; ' : PHP_EOL;
            }
            $result .= $added;

            return $result;
        }
        return false;
    }


	public function load_from_post()
	{
		$this->codename		= $_REQUEST['codename'];
		$this->icon		    = $_REQUEST['icon'];
   		$this->lid		    = $_REQUEST['lid'];
   		$this->notes	    = $_REQUEST['notes'];
		$this->enabled		= ($_REQUEST['enabled']=='1'? '1' : '0');

		// load associated functions
		$functions = explode('#', $_REQUEST['menu-functions']);
		$this->functions = array();
		foreach($functions as $function)
		{
			if(!empty($function))
				$this->functions[] = $function;
		}
	}


    public function saveOption(Request $request) {

        $cleanFromXss = true;
        $option = $request->all();

        // Allow for this keys
        if (isset($option['option_key'])) {
            if ($option['option_key'] == 'website_head') {
                $cleanFromXss = false;
            }
            if ($option['option_key'] == 'website_footer') {
                $cleanFromXss = false;
            }
        }

        if ($cleanFromXss) {
            $clean = new HTMLClean();
            $option = $clean->cleanArray($option);
        }

        return save_option($option);
    }


	static function convertUTF($string) {
		return $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));
	}


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

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

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

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


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

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


    public function allowedViewProfileField(self $user, $fieldNameIntern)
    {
        return $user->mProfileFieldsData->isVisible($fieldNameIntern, $this->hasRightEditProfile($user));
    }


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


    public function shippingMethodSave(Request $request) {

        if (is_array($request->get('Address'))) {
            $request->merge([
               'city'=>$request->get('Address')['city'],
               'zip'=>$request->get('Address')['zip'],
               'state'=>$request->get('Address')['state'],
               'address'=>$request->get('Address')['address'],
            ]);
        }

        session_append_array('checkout_v2', [
            'shipping_gw'=> $request->get('shipping_gw'),
            'city'=> $request->get('city'),
            'address'=> $request->get('address'),
            'country'=> $request->get('country'),
            'state'=> $request->get('state'),
            'zip'=> $request->get('zip'),
            'other_info'=> $request->get('other_info'),
        ]);

        $checkIfShippingEnabled = app()->shipping_manager->getShippingModules(true);
        if ($checkIfShippingEnabled) {
            $validate = $this->_validateShippingMethod();
            if ($validate['valid'] == false) {
                session_set('errors', $validate['errors']);
                return redirect(route('checkout.shipping_method'));
            }
        }
        // Success
        return redirect(route('checkout.payment_method'));
    }


function db_seq_nextval($seqname)
{
	global $DatabaseType;

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

	return $seq;
}


	public function setError ($pn_error_number, $ps_error_description='', $ps_error_context='', $ps_error_source='') {
		$this->opn_error_number = $pn_error_number;
		$this->ops_error_description = $ps_error_description;
		$this->ops_error_context = $ps_error_context;
		$this->ops_error_source = $ps_error_source;

		if (($this->opb_halt_on_error) || ($this->opb_report_on_error)) {
			$this->halt();
		}
		return 1;
	}


            $masteroption->delete();
        }

        // delete the mastergroup
        $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);
        $mastergroup->delete();

        expHistory::back();
    }


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

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

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

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


    function productFeed() {
//        global $db;
        //check query password to avoid DDOS
        /*
            * condition  = new
            * description
            * id - SKU
            * link
            * price
            * title
            * brand - manufacturer
            * image link - fullsized image, up to 10, comma seperated
            * product type - category - "Electronics > Audio > Audio Accessories MP3 Player Accessories","Health & Beauty > Healthcare > Biometric Monitors > Pedometers"
         */
        $out = '"id","condition","description","like","price","title","brand","image link","product type"' . chr(13) . chr(10);

        $p = new product();
        $prods = $p->find('all', 'parent_id=0 AND ');
        //$prods =  $db->selectObjects('product','parent_id=0 AND');
    }


            foreach($image->expTag as $tag) {
                if (isset($used_tags[$tag->id])) {
                    $used_tags[$tag->id]->count++;
                } else {
                    $exptag = new expTag($tag->id);
                    $used_tags[$tag->id] = $exptag;
                    $used_tags[$tag->id]->count = 1;
                }

            }


    public function __construct(array $attributes = null)
    {
        $rootDir = realpath(__DIR__ . "/../");
        $this->setChroot(array($rootDir));
        $this->setRootDir($rootDir);
        $this->setTempDir(sys_get_temp_dir());
        $this->setFontDir($rootDir . "/lib/fonts");
        $this->setFontCache($this->getFontDir());

        $ver = "";
        $versionFile = realpath(__DIR__ . "/../VERSION");
        if (file_exists($versionFile) && ($version = trim(file_get_contents($versionFile))) !== false && $version !== '$Format:<%h>$') {
            $ver = "/$version";
        }
        $this->setHttpContext([
            "http" => [
                "follow_location" => false,
                "user_agent" => "Dompdf$ver https://github.com/dompdf/dompdf"
            ]
        ]);

        if (null !== $attributes) {
            $this->set($attributes);
        }
    }


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

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


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

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


	public static function available($username, $website_id)
	{
		global $DB;

		// remove spaces and make username lowercase (only to compare case insensitive)
		$username = trim($username);
		$username = mb_strtolower($username);

		$data = NULL;
		if($DB->query('SELECT COUNT(*) as total
					   FROM nv_webusers
					   WHERE LOWER(username) = '.protect($username).'
					   	 AND website = '.$website_id))
		{
			$data = $DB->first();
		}

		return ($data->total <= 0);
	}


    public function setScriptSrc(Response $response)
    {
        if (config('app.allow_content_scripts')) {
            return;
        }

        $parts = [
            'http:',
            'https:',
            '\'nonce-' . $this->nonce . '\'',
            '\'strict-dynamic\'',
        ];

        $value = 'script-src ' . implode(' ', $parts);
        $response->headers->set('Content-Security-Policy', $value, false);
    }


    protected function _afterLoad()
    {
        if ($this->_addUrlRewrite) {
            $this->_addUrlRewrite($this->_urlRewriteCategory);
        }

        if (count($this) > 0) {
            Mage::dispatchEvent('catalog_product_collection_load_after', array('collection' => $this));
        }

        foreach ($this as $product) {
            if ($product->isRecurring() && $profile = $product->getRecurringProfile()) {
                $product->setRecurringProfile(unserialize($profile));
            }
        }

        return $this;
    }


	protected function stat($path) {
		if ($path === false || is_null($path)) {
			return false;
		}
		$is_root = ($path == $this->root);
		if ($is_root) {
			$rootKey = md5($path);
			if (!isset($this->sessionCache['rootstat'])) {
				$this->sessionCache['rootstat'] = array();
			}
			if (! $this->isMyReload()) {
				// need $path as key for netmount/netunmount
				if (isset($this->sessionCache['rootstat'][$rootKey])) {
					if ($ret = $this->sessionCache['rootstat'][$rootKey]) {
						return $ret;
					}
				}
			}
		}
		$ret = isset($this->cache[$path])
			? $this->cache[$path]
			: $this->updateCache($path, $this->convEncOut($this->_stat($this->convEncIn($path))));
		if ($is_root) {
			$this->sessionCache['rootstat'][$rootKey] = $ret;
			$this->session->set($this->id, $this->sessionCache);
		}
		return $ret;
	}


	public function admin_download()
	{
		$this->autoRender = false;
		$tmpDir = TMP . 'theme' . DS;
		$Folder = new Folder();
		$Folder->create($tmpDir);
		$path = BASER_THEMES . $this->siteConfigs['theme'] . DS;
		$Folder->copy([
			'from' => $path,
			'to' => $tmpDir . $this->siteConfigs['theme'],
			'chmod' => 0777
		]);
		$Simplezip = new Simplezip();
		$Simplezip->addFolder($tmpDir);
		$Simplezip->download($this->siteConfigs['theme']);
		$Folder->delete($tmpDir);
	}


    public function testAddsSlashForRelativeUriStringWithHost()
    {
        $uri = (new Uri)->withPath('foo')->withHost('bar.com');
        $this->assertEquals('foo', $uri->getPath());
        $this->assertEquals('bar.com/foo', (string) $uri);
    }


    function selectExpObjectsBySql($sql, $classname, $get_assoc=true, $get_attached=true) {
        $res = @mysqli_query($this->connection, $sql);
        if ($res == null)
            return array();
        $arrays = array();
        $numrows = mysqli_num_rows($res);
        for ($i = 0; $i < $numrows; $i++)
            $arrays[] = new $classname(mysqli_fetch_assoc($res), true, true);
        return $arrays;
    }


    public function showall() {
        expHistory::set('viewable', $this->params);
        // figure out if should limit the results
        if (isset($this->params['limit'])) {
            $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];
        } else {
            $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
        }
        $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';

        // pull the news posts from the database
        $items = $this->news->find('all', $this->aggregateWhereClause(), $order);

        // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.
        if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);

        // setup the pagination object to paginate the news stories.
        $page = new expPaginator(array(
            'records'=>$items,
            'limit'=>$limit,
            'order'=>$order,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'view'=>empty($this->params['view']) ? null : $this->params['view']
        ));

        assign_to_template(array(
            'page'=>$page,
            'items'=>$page->records,
            'rank'=>($order==='rank')?1:0,
            'params'=>$this->params,
        ));
    }


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


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

        return $q;
    }


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


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

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

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

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


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

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

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

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

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


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

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


    public static function getUploadFileFromPost($siteID, $subDirectory, $id)
    {
        if (isset($_FILES[$id]))
        {
            if (!@file_exists($_FILES[$id]['tmp_name']))
            {
                // File was removed, accessed from another window, or no longer exists
                return false;
            }

            if (!eval(Hooks::get('FILE_UTILITY_SPACE_CHECK'))) return;

            $uploadPath = FileUtility::getUploadPath($siteID, $subDirectory);
            $newFileName = $_FILES[$id]['name'];

            // Could just while(file_exists) it, but I'm paranoid of infinate loops
            // Shouldn't have 1000 files of the same name anyway
            for ($i = 0; @file_exists($uploadPath . '/' . $newFileName) && $i < 1000; $i++)
            {
                $mp = explode('.', $newFileName);
                $fileNameBase = implode('.', array_slice($mp, 0, count($mp)-1));
                $fileNameExt = $mp[count($mp)-1];

                if (preg_match('/(.*)_Copy([0-9]{1,3})$/', $fileNameBase, $matches))
                {
                    // Copy already appending, increase the #
                    $fileNameBase = sprintf('%s_Copy%d', $matches[1], intval($matches[2]) + 1);
                }
                else
                {
                    $fileNameBase .= '_Copy1';
                }

                $newFileName = $fileNameBase . '.' . $fileNameExt;
            }

            if (@move_uploaded_file($_FILES[$id]['tmp_name'], $uploadPath . '/' . $newFileName) &&
                @chmod($uploadPath . '/' . $newFileName, 0777))
            {
                return $newFileName;
            }
        }

        return false;
    }


    public static function getId($id=''){
        if(isset($id)){
            $sql = sprintf("SELECT * FROM `menus` WHERE `id` = '%d'", $id);
            $menus = Db::result($sql);
            $n = Db::$num_rows;
        }else{
            $menus = '';
        }

        return $menus;
    }


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


    protected function itemLocked($hash)
    {
        if (!elFinder::$commonTempPath) {
            return false;
        }
        $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
        if (file_exists($lock)) {
            if (filemtime($lock) + $this->itemLockExpire < time()) {
                unlink($lock);
                return false;
            }
            return true;
        }

        return false;
    }


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

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


   static function encrypt($string, $key) {

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


    function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }


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

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


    public function testSameInstanceWhenSameProtocol()
    {
        $r = new Response(200);
        $this->assertSame($r, $r->withProtocolVersion('1.1'));
    }


    function edit_externalalias() {
        $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(),
        ));
    }


                        echo '</SCHOOL_' . htmlentities($i) . '>';
                        $i++;
                    }
                    echo '</SCHOOL_ACCESS>';
                    //                }
                    echo '</STAFF_' . htmlentities($j) . '>';
                    $j++;
                }


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

        $this->iniSet('session.save_handler', 'files');
        $storage = $this->getStorage();
        $storage->setSaveHandler();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(null);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NullSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeProxy());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
    }


function fm_get_size($file)
{
    static $iswin;
    static $isdarwin;
    if (!isset($iswin)) {
        $iswin = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN');
    }
    if (!isset($isdarwin)) {
        $isdarwin = (strtoupper(substr(PHP_OS, 0)) == "DARWIN");
    }

    static $exec_works;
    if (!isset($exec_works)) {
        $exec_works = (function_exists('exec') && !ini_get('safe_mode') && @exec('echo EXEC') == 'EXEC');
    }

    // try a shell command
    if ($exec_works) {
        $cmd = ($iswin) ? "for %F in (\"$file\") do @echo %~zF" : ($isdarwin ? "stat -f%z \"$file\"" : "stat -c%s \"$file\"");
        @exec($cmd, $output);
        if (is_array($output) && ctype_digit($size = trim(implode("\n", $output)))) {
            return $size;
        }
    }

    // try the Windows COM interface
    if ($iswin && class_exists("COM")) {
        try {
            $fsobj = new COM('Scripting.FileSystemObject');
            $f = $fsobj->GetFile( realpath($file) );
            $size = $f->Size;
        } catch (Exception $e) {
            $size = null;
        }
        if (ctype_digit($size)) {
            return $size;
        }
    }

    // if all else fails
    return filesize($file);
}


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


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

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

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


    public function destroy(Image $image)
    {
        $this->destroyImagesFromPath($image->path);
        $image->delete();
    }


    public function setFrameAncestors(Response $response)
    {
        $iframeHosts = $this->getAllowedIframeHosts();
        array_unshift($iframeHosts, "'self'");
        $cspValue = 'frame-ancestors ' . implode(' ', $iframeHosts);
        $response->headers->set('Content-Security-Policy', $cspValue, false);
    }


	public function load_by_hash($hash)
	{
		global $DB;
		global $session;
        global $events;

        $ok = $DB->query('SELECT * FROM nv_webusers WHERE cookie_hash = '.protect($hash));
        if($ok)
            $data = $DB->result();

        if(!empty($data))
		{
			$this->load_from_resultset($data);

			// check if the user is still allowed to sign in
			$blocked = 1;
			if( $this->access == 0 ||
                ( $this->access == 2 &&
                    ($this->access_begin==0 || $this->access_begin < time()) &&
                    ($this->access_end==0 || $this->access_end > time())
                )
            )
			{
				$blocked = 0;
			}

			if($blocked==1)
				return false;

			$session['webuser'] = $this->id;

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

	}


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


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


    public static function footer($vars=""){
        global $GLOBALS;
        if (isset($vars)) {
            # code...
            $GLOBALS['data'] = $vars;
            self::theme('footer', $vars);
        }else{
            self::theme('footer');
        }

    }


            $message = getlocal(
                "Operator {0} joined the chat",
                array($operator_name),
                $this->locale,
                true
            );
        } elseif ($is_operator_back) {


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

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

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


    private function initProfileFieldFilter(ProfileField $profileField, $sortOrder = 1000)
    {
        $profileFieldType = $profileField->getFieldType();

        if (!$profileFieldType) {
            return;
        }

        $definition = $profileFieldType->getFieldFormDefinition();
        $fieldType = isset($definition[$profileField->internal_name]['type']) ? $definition[$profileField->internal_name]['type'] : null;

        $filterData = [
            'title' => Yii::t($profileField->getTranslationCategory(), $profileField->title),
            'type' => $fieldType,
            'sortOrder' => $sortOrder,
        ];

        switch ($fieldType) {
            case 'text':
                $filterData['type'] = 'widget';
                $filterData['widget'] = PeopleFilterPicker::class;
                $filterData['widgetOptions'] = [
                    'itemKey' => $profileField->internal_name
                ];
                break;

            case 'dropdownlist':
                $filterData['options'] = array_merge(['' => Yii::t('UserModule.base', 'Any')], $definition[$profileField->internal_name]['items']);
                break;

            default:
                // Skip not supported type
                return;
        }

        $this->addFilter('fields[' . $profileField->internal_name . ']', $filterData);
    }


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


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


function getUserPartForHeader() {
    global $i18n;
    if (!$this->id) return null;

    $user_part = htmlspecialchars($this->name);
    $user_part .= ' - '.htmlspecialchars($this->role_name);
    if ($this->behalf_id) {
      $user_part .= ' '.$i18n->get('label.on_behalf').' '.htmlspecialchars($this->behalf_name).'';
    }
    if ($this->behalf_group_id) {
      $user_part .= ',  '.htmlspecialchars($this->behalf_group_name).'';
    } else {
      if ($this->group_name) // Note: we did not require group names in the past.
        $user_part .= ', '.$this->group_name;
    }
    return $user_part;
  }


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


static function convertXMLFeedSafeChar($str) {
		$str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace(""",'"',$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","'",$str);
        $str = str_replace("‘","'",$str);
        $str = str_replace("®","",$str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("”",'"', $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("“",'"', $str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


    public static function incBack($vars) {
        $file = GX_PATH.'/inc/lib/Control/Backend/'.$vars.'.control.php';
        if ( file_exists($file) ) {
            # code...
            include($file);
        }else{
            self::error('404');
        }
    }


        foreach ($data['alertDanger'] as $alert) {
            # code...
            echo "<li>$alert</li>\n";
        }


	protected function copy($src, $dst, $name) {
		$srcStat = $this->stat($src);
		$this->clearcache();

		if (!empty($srcStat['thash'])) {
			$target = $this->decode($srcStat['thash']);
			if (!$this->inpathCE($target, $this->root)) {
				return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']), elFinder::ERROR_MKOUTLINK);
			}
			$stat   = $this->stat($target);
			$this->clearcache();
			return $stat && $this->symlinkCE($target, $dst, $name)
				? $this->joinPathCE($dst, $name)
				: $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
		}

		if ($srcStat['mime'] == 'directory') {
			$test = $this->stat($this->joinPathCE($dst, $name));
			$this->clearcache();

			if (($test && $test['mime'] != 'directory') || (! $test = $this->mkdir($this->encode($dst), $name))) {
				return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
			}

			$dst = $this->decode($test['hash']);

			foreach ($this->getScandir($src) as $stat) {
				if (empty($stat['hidden'])) {
					$name = $stat['name'];
					$_src = $this->decode($stat['hash']);
					if (! $this->copy($_src, $dst, $name)) {
						$this->remove($dst, true); // fall back
						return $this->setError($this->error, elFinder::ERROR_COPY, $this->_path($src));
					}
				}
			}
			$this->clearcache();
			return $dst;
		}

		if ($res = $this->convEncOut($this->_copy($this->convEncIn($src), $this->convEncIn($dst), $this->convEncIn($name)))) {
			return is_string($res)? $res : $this->joinPathCE($dst, $name);
		}

		return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
	}


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


    public function whereFileName($fileName)
    {
        $this->selectSingle = $this->model->getFileNameParts($fileName);

        return $this;
    }


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


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


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


                            'data' => str_replace(array_keys($tags), array_values($tags), $content),
                            'status' => array(),
                            'type' => 'text/html; charset=UTF-8'
                        )
                    );
                }


    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 testIsActivePhp53()
    {
        if (PHP_VERSION_ID >= 50400) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->assertFalse($this->proxy->isActive());
    }


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


	public function authenticate($user, $pass)
	{
		global $DB;

		$user = trim($user);
		$user = mb_strtolower($user);

		$A1 = md5($user.':'.APP_REALM.':'.$pass);

		if($DB->query('SELECT *
						 FROM nv_users
						WHERE LOWER(username) = '.protect($user)))
		{
			$data = $DB->result();

			if($data[0]->password==$A1)
			{
				$this->load_from_resultset($data[0]);
				$this->attempts = 0;
				$this->update();
				return true;
			}
			else if(!empty($data[0]->id))
			{
				$this->load_from_resultset($data[0]);
				$this->attempts++;

				if($this->attempts > 9)
					$this->blocked = 1;

				$this->update();
				return false;
			}
		}

		return false;
	}


    public static function cleanLink($fulllink)
    {
        if(substr($fulllink, -1) == '/') $fulllink = substr($fulllink, 0, -1);
        return $fulllink;
    }


    static function description() {
        return "Manage events and schedules, and optionally publish them.";
    }


		$event = mysqli_fetch_assoc($result);

		if($queue == "active"){
			$ged_command = "-drop -type $ged_type_nbr -queue $queue ";
			foreach ($array_ged_packets as $key => $value) {
				if($value["key"] == true){
					$ged_command .= "\"".$event[$key]."\" ";
				}
			}
			$ged_command = trim($ged_command, " ");

			shell_exec($path_ged_bin." ".$ged_command);
			logging("ged_update",$ged_command);
		} else {
			$id_list .= $id.",";
		}
	}

	if($queue == "history"){
		$id_list = trim($id_list, ",");
		$ged_command = "-drop -id ".$id_list." -queue history";

		shell_exec($path_ged_bin." ".$ged_command);
		logging("ged_update",$ged_command);
	}
}


	public function setRssValues($rss)
	{
		$this->set('rsstitle', \App\Purifier::purifyByType((string) $rss->title, 'Text'));
		$this->set('url', $rss->link);
	}


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


	protected function _rmdir($path) {
		return $this->query(sprintf('DELETE FROM %s WHERE id=%d AND mime="directory" LIMIT 1', $this->tbf, $path)) && $this->db->affected_rows;
	}


    public static function isPublic($s) {
        if ($s == null) {
            return false;
        }
        while ($s->public && $s->parent > 0) {
            $s = new section($s->parent);
        }
        $lineage = (($s->public) ? 1 : 0);
        return $lineage;
    }


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


            self::get($arr);

        } else {

            self::incFront('default');

        }

    }


$contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_DELETE, 'fas fa-trash', null, 'primary', null, 'btn-danger xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('testimonials.php', 'page=' . $_GET['page'] . '&tID=' . $tInfo->testimonials_id), null, null, 'btn-light')];


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

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

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


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

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


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

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


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


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


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

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


    protected function getTestFile($fileName)
    {
        return new \Illuminate\Http\UploadedFile(base_path('tests/test-data/test-file.txt'), $fileName, 'text/plain', 55, null, true);
    }


					$dt = date('Y-m-d', strtotime($match));
					$sql = par_rep("/'$match'/", "'$dt'", $sql);
				}
			}
			if (substr($sql, 0, 6) == "BEGIN;") {
				$array = explode(";", $sql);
				foreach ($array as $value) {
					if ($value != "") {
						$result = $connection->query($value);
						if (!$result) {
							$connection->query("ROLLBACK");
							die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
						}
					}
				}
			} else {
				$result = $connection->query($sql) or die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
			}
			break;
	}


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


	public function prepare( $query, $args ) {
		if ( is_null( $query ) )
			return;

		// This is not meant to be foolproof -- but it will catch obviously incorrect usage.
		if ( strpos( $query, '%' ) === false ) {
			wp_load_translations_early();
			_doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
		}

		$args = func_get_args();
		array_shift( $args );

		// If args were passed as an array (as in vsprintf), move them up
		if ( is_array( $args[0] ) && count( $args ) == 1 ) {
			$args = $args[0];
		}

		foreach ( $args as $arg ) {
			if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
				wp_load_translations_early();
				_doing_it_wrong( 'wpdb::prepare', sprintf( __( 'Unsupported value type (%s).' ), gettype( $arg ) ), '4.8.2' );
			}
		}

		$query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
		$query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
		$query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
		$query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
		$query = preg_replace( '/%(?:%|$|([^dsF]))/', '%%\\1', $query ); // escape any unescaped percents

		// Count the number of valid placeholders in the query
		$placeholders = preg_match_all( '/(^|[^%]|(%%)+)%[sdF]/', $query, $matches );

		if ( count ( $args ) !== $placeholders ) {
			wp_load_translations_early();
			_doing_it_wrong( 'wpdb::prepare',
				/* translators: 1: number of placeholders, 2: number of arguments passed */
				sprintf( __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
					$placeholders,
					count( $args ) ),
				'4.9.0'
			);
		}

		array_walk( $args, array( $this, 'escape_by_ref' ) );
		return @vsprintf( $query, $args );
	}


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

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


    public static function ridOld($tokens) {
        $time = time();
        foreach ($tokens as $token => $value) {
            if ($time - $value['time'] > 3600) {
                unset($tokens[$token]);
            }
        }
        return $tokens;
    }


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

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

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


	public function load_from_post()
	{
		$this->codename		= $_REQUEST['codename'];
		$this->icon		    = $_REQUEST['icon'];
   		$this->lid		    = $_REQUEST['lid'];
   		$this->notes	    = $_REQUEST['notes'];
		$this->enabled		= ($_REQUEST['enabled']=='1'? '1' : '0');

		// load associated functions
		$functions = explode('#', $_REQUEST['menu-functions']);
		$this->functions = array();
		foreach($functions as $function)
		{
			if(!empty($function))
				$this->functions[] = $function;
		}
	}


    public function getQuerySelect()
    {
        return "R_{$this->id}.rank AS `$this->name`";
    }


        foreach ($data['alertred'] as $alert) {
            # code...
            echo "<li>$alert</li>\n";
        }


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