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

		$ok = $DB->execute('
 			UPDATE nv_menus
			   SET codename = :codename, icon = :icon, lid = :lid, notes = :notes,
			   	   functions = :functions, enabled = :enabled
            WHERE id = :id',
			array(
				'id' => $this->id,
				'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());

		return true;
	}


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

        parent::saveConfig();
    }


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


  function select_string($n) {
    if (!is_int($n)) {
      throw new InvalidArgumentException(
        "Select_string only accepts integers: " . $n);
    }
    $string = $this->get_plural_forms();
    $string = str_replace('nplurals',"\$total",$string);
    $string = str_replace("n",$n,$string);
    $string = str_replace('plural',"\$plural",$string);

    $total = 0;
    $plural = 0;

    eval("$string");
    if ($plural >= $total) $plural = $total - 1;
    return $plural;
  }


    function update_optiongroup_master() {
        global $db;

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

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $og->title) {
            $db->sql('UPDATE '.$db->prefix.'optiongroup SET title="'.$og->title.'" WHERE title="'.$oldtitle.'"');
        }

        expHistory::back();
    }


	public static function update_object_score($object, $object_id)
	{
		global $DB;

		list($votes, $score) = webuser_vote::calculate_object_score($object, $object_id);
		$table = array(
			'item'	=>	'nv_items',
			'structure'	=>	'nv_structure',
			'product' => 'nv_products'
		);

		if(empty($table[$object]))
			return false;

		$DB->execute('
			UPDATE '.$table[$object].'
			   SET votes = '.protect($votes).',
			   	   score = '.protect($score).'
			 WHERE id = '.protect($object_id)
		);

		return true;
	}


            $files[$key]->save();
        }

//        eDebug($files,true);
    }


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


                    }elseif($p->group == 3){
                        $grp = AUTHOR;
                    }elseif($p->group == 4){


	public function getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}


	public static function evaluate_search_tree($tree, $join = 'AND', $callback)
	{
		$matches = false;

		foreach($tree as $i => $el)
		{
			$b = false;
			if($i === 'AND' || $i === 'OR')
			{
				$b = self::evaluate_search_tree($el, $i, $callback);
			}
			else if(isset($el['query']))
			{
				$b = call_user_func($callback, $el['query']);
				if($el['not'])
				{
					$b = !$b;
				}
			}
			else if(is_array($el))
			{
				$b = self::evaluate_search_tree($el, $join, $callback);
			}

			if($join == 'AND')
			{
				if(!$b)
				{
					return false;
				}
				$matches = true;
			}
			else if($join == 'OR')
			{
				if($b)
				{
					return true;
				}

				$matches = $matches || $b;

			}

		}

		return $matches;
	}


    protected function defaultExtensions()
    {
        return [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'svg',
            'js',
            'map',
            'ico',
            'css',
            'less',
            'scss',
            'ics',
            'odt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'pdf',
            'swf',
            'txt',
            'xml',
            'ods',
            'xls',
            'xlsx',
            'eot',
            'woff',
            'woff2',
            'ttf',
            'flv',
            'wmv',
            'mp3',
            'ogg',
            'wav',
            'avi',
            'mov',
            'mp4',
            'mpeg',
            'webm',
            'mkv',
            'rar',
            'xml',
            'zip'
        ];
    }


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


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


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

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

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

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


    public function dump($value)
    {
        $dumper = $this->getDumper();

        if ($dumper) {
            // re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump.
            // exclude verbose information (e.g. exception stack traces)
            if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) {
                $cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE);
                // Symfony VarDumper 2.6 Caster class dont exist.
            } else {
                $cloneVar = $this->getCloner()->cloneVar($value);
            }

            $dumper->dump(
                $cloneVar,
                $this->htmlDumperOutput
            );

            $output = $this->htmlDumperOutput->getOutput();
            $this->htmlDumperOutput->clear();

            return $output;
        }

        return print_r($value, true);
    }


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

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

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

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

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

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

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


    public function getQueryGroupby()
    {
        return '';
    }


                return $fa->nameGlyph($icons, 'icon-');
            }
        } else {
            return array();
        }
    }


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


    function edit_section() {
        global $db, $user;

        $parent = new section($this->params['parent']);
        if (empty($parent->id)) $parent->id = 0;
        assign_to_template(array(
            'haveStandalone'  => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),
            'parent'          => $parent,
            'isAdministrator' => $user->isAdmin(),
        ));
    }


$contents = ['form' => tep_draw_form('specials', 'specials.php', 'page=' . $_GET['page'] . '&sID=' . $sInfo->specials_id . '&action=deleteconfirm')];


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


    public static function activate($thm) {
        if (Options::update('themes', $thm)) {
            new Options();
            return true;
        }else{
            return false;
        }
    }


function sell_media_ecommerce_enabled( $post_id ) {
	$status = true;
	$meta = get_post_meta( $post_id, 'sell_media_enable_ecommerce', true );
	if ( class_exists( 'VS_Platform' ) && 0 === $meta ) {
		$status = false;
	}
	return $status;
}


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


        foreach ($allowedFolders as $folder) {
            if ('/' . $folder === substr($uri, 0, 1 + strlen($folder))) {
                header('Content-Type: ' . $this->getMime($filePath));
                readfile($filePath);
                return true;
            }
        }


            throw new \InvalidArgumentException(
                'URI must be a string or Psr\Http\Message\UriInterface'
            );
        }

        $this->method = strtoupper($method);
        $this->uri = $uri;
        $this->setHeaders($headers);
        $this->protocol = $protocolVersion;

        $host = $uri->getHost();
        if ($host && !$this->hasHeader('Host')) {
            $this->updateHostFromUri($host);
        }

        if ($body) {
            $this->stream = stream_for($body);
        }
    }


	public function post_prop () {
		$file = urldecode (join ('/', func_get_args ()));
		if (! FileManager::verify_file ($file)) {
			return $this->error (__ ('Invalid file name'));
		}

		// handle multiple properties at once
		if (isset ($_POST['props'])) {
			if (! is_array ($_POST['props'])) {
				return $this->error (__ ('Invalid properties'));
			}

			foreach ($_POST['props'] as $k => $v) {
				if (FileManager::prop ($file, $k, $v) === false) {
					return $this->error (__ ('Error saving properties.'));
				}
			}

			return array (
				'file' => $file,
				'props' => $_POST['props'],
				'msg' => __ ('Properties saved.')
			);
		}

		// handle a single property
		if (! isset ($_POST['prop'])) {
			return $this->error (__ ('Missing property name'));
		}
		if (isset ($_POST['value'])) {
			// update and fetch
			$res = FileManager::prop ($file, $_POST['prop'], $_POST['value']);
		} else {
			// fetch
			$res = FileManager::prop ($file, $_POST['prop']);
		}
		return array (
			'file' => $file,
			'prop' => $_POST['prop'],
			'value' => $res,
			'msg' => __ ('Properties saved.')
		);
	}


	protected function _add_log_attachment( $action, $attachment_id ) {
		$post = get_post( $attachment_id );

		aal_insert_log( array(
			'action'         => $action,
			'object_type'    => 'Attachment',
			'object_subtype' => $post->post_type,
			'object_id'      => $attachment_id,
			'object_name'    => get_the_title( $post->ID ),
		) );
	}


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


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


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

        // Redirect the thread
        $thread->state = Thread::STATE_WAITING;
        $thread->nextAgent = 0;
        $thread->groupId = $group_id;
        $thread->agentId = 0;
        $thread->agentName = '';
        $thread->save();

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

        return true;
    }


            foreach ($allusers as $uid) {
                $u = user::getUserById($uid);
                expPermissions::grant($u, 'manage', $sloc);
            }


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


                $that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['expiry_field']]['$lt']->sec);
            }));


    protected function secure(Hostname $hostname, Request $request)
    {
        $this->emitEvent(new Secured($hostname));

        return $this->redirect->secure($request->getRequestUri());
    }


                foreach ($value as $k => $val) {
                    if ($k != 'LAST_UPDATED') {
                        if ($k != 'UPDATED_BY') {
                            if ($k == 'ID')
                                $data['data'][$i]['SCHOOL_ID'] = $val;
                            else if ($k == 'SYEAR')
                                $data['data'][$i]['SCHOOL_YEAR'] = $val;
                            else if ($k == 'TITLE')
                                $data['data'][$i]['SCHOOL_NAME'] = $val;
                            else if ($k == 'WWW_ADDRESS')
                                $data['data'][$i]['URL'] = $val;
                            else
                                $data['data'][$i][$k] = $val;
                        }
                    }
                }


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


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

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

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


    public function update() {

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

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


        foreach($course_RET as $period_day)
        {
            $period_days_append_sql .="(sp.start_time<='$period_day[END_TIME]' AND '$period_day[START_TIME]'<=sp.end_time AND DAYS LIKE '%$period_day[DAYS]%') OR ";
        }


            $section  = new section($this->params);
        } else {
            notfoundController::handle_not_found();
            exit;
        }
        if (!empty($section->id)) {
            $check_id = $section->id;
        } else {
            $check_id = $section->parent;
        }
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {
            if (empty($section->id)) {
                $section->active = 1;
                $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(),
            ));
        } else {  // User does not have permission to manage sections.  Throw a 403
            notfoundController::handle_not_authorized();
        }
    }


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

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

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


    public static function inc ($vars, $data = "") {

        $file = GX_PATH.'/gxadmin/inc/'.$vars.'.php';

        if (file_exists($file)) {

            include($file);

        }

    }


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

		}

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

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

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

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

	}


  protected function AddAnAddress($kind, $address, $name = '') {
    if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
      if ($this->exceptions) {
        throw new phpmailerException('Invalid recipient array: ' . $kind);
      }
      if ($this->SMTPDebug) {
        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
      }
      return false;
    }
    $address = trim($address);
    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    if (!$this->ValidateAddress($address)) {
      $this->SetError($this->Lang('invalid_address').': '. $address);
      if ($this->exceptions) {
        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
      }
      if ($this->SMTPDebug) {
        $this->edebug($this->Lang('invalid_address').': '.$address);
      }
      return false;
    }
    if ($kind != 'Reply-To') {
      if (!isset($this->all_recipients[strtolower($address)])) {
        array_push($this->$kind, array($address, $name));
        $this->all_recipients[strtolower($address)] = true;
        return true;
      }
    } else {
      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
        $this->ReplyTo[strtolower($address)] = array($address, $name);
      return true;
    }
  }
  return false;
}


	protected function configure() {
		// set ARGS
		$this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST'? $_POST : $_GET;
		// set thumbnails path
		$path = $this->options['tmbPath'];
		if ($path) {
			if (!file_exists($path)) {
				if (@mkdir($path)) {
					chmod($path, $this->options['tmbPathMode']);
				} else {
					$path = '';
				}
			}

			if (is_dir($path) && is_readable($path)) {
				$this->tmbPath = $path;
				$this->tmbPathWritable = is_writable($path);
			}
		}

		// set image manipulation library
		$type = preg_match('/^(imagick|gd|auto)$/i', $this->options['imgLib'])
			? strtolower($this->options['imgLib'])
			: 'auto';

		if (($type == 'imagick' || $type == 'auto') && extension_loaded('imagick')) {
			$this->imgLib = 'imagick';
		} else {
			$this->imgLib = function_exists('gd_info') ? 'gd' : '';
		}

		// check archivers
		if (empty($this->archivers['create'])) {
			$this->disabled[] ='archive';
		}
		if (empty($this->archivers['extract'])) {
			$this->disabled[] ='extract';
		}
		$_arc = $this->getArchivers();
		if (empty($_arc['create'])) {
			$this->disabled[] ='zipdl';
		}

		// check 'statOwner' for command `chmod`
		if (empty($this->options['statOwner'])) {
			$this->disabled[] ='chmod';
		}

		// check 'mimeMap'
		if (!is_array($this->options['mimeMap'])) {
			$this->options['mimeMap'] = array();
		}
	}


    public static function json() {
        $token = Options::v('tokens');
        $token = json_decode($token, true);
        $newtoken = array(
                        TOKEN => array(
                            'time' => TOKEN_TIME,
                            'ip' => TOKEN_IP,
                            'url' => TOKEN_URL
                            )
                    );
        if(is_array($token)){
            $newtoken = array_merge($token, $newtoken);
        }
        $newtoken = self::ridOld($newtoken);
        $newtoken = json_encode($newtoken);
        return $newtoken;
    }


	public function delete() {
	    global $user;

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


    public function handleRequest() {
        /* Load error handling class */
        $this->loadErrorHandler();

        $this->modx->invokeEvent('OnHandleRequest');

        /* save page to manager object. allow custom actionVar choice for extending classes. */
        $this->action = isset($_REQUEST[$this->actionVar]) ? $_REQUEST[$this->actionVar] : $this->defaultAction;

        /* invoke OnManagerPageInit event */
        $this->modx->invokeEvent('OnManagerPageInit',array('action' => $this->action));
        $this->prepareResponse();
    }


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


	public function load_template()
	{
		global $DB;
		global $website;

		$template = new template();

		if(	$this->association == 'free' ||
			($this->association == 'category' && $this->embedding == '0'))
		{
			$template->load($this->template);
		}
		else
		{
			$category_template = $DB->query_single(
                'template',
                'nv_structure',
                ' id = '.protect($this->category).' AND website = '.$website->id
            );
			$template->load($category_template);
		}

		return $template;
	}


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


	public function validateForField(App\Request $request)
	{
		$fieldModel = Vtiger_Module_Model::getInstance($request->getModule())->getFieldByName($request->getByType('fieldName', 2));
		if (!$fieldModel || !$fieldModel->isActiveField() || !$fieldModel->isViewEnabled()) {
			throw new \App\Exceptions\NoPermitted('ERR_NO_PERMISSIONS_TO_FIELD', 406);
		}
		$recordModel = \Vtiger_Record_Model::getCleanInstance($fieldModel->getModuleName());
		$fieldModel->getUITypeModel()->setValueFromRequest($request, $recordModel, 'fieldValue');
		$response = new Vtiger_Response();
		$response->setResult([
			'raw' => $recordModel->get($fieldModel->getName()),
			'display' => $recordModel->getDisplayValue($fieldModel->getName()),
		]);
		$response->emit();
	}


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

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


    function update() {
        parent::update();
        expSession::clearAllUsersSessionCache('navigation');
    }


    public function offset($value)
    {
        $this->offset = max(0, $value);

        return $this;
    }


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

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

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


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

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


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

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

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


function exception_for($reason)
{
    return $reason instanceof \Exception
        ? $reason
        : new RejectionException($reason);
}


	public function addTab($array)
	{
		if (!$array) {
			$this->setAPIResponse('error', 'no data was sent', 422);
			return null;
		}
		$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
		$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
		$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
		$array['enabled'] = ($array['enabled']) ?? 0;
		$array['default'] = ($array['default']) ?? 0;
		$array['type'] = ($array['type']) ?? 1;
		$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
		if (array_key_exists('name', $array)) {
			$array['name'] = htmlspecialchars($array['name']);
			if ($this->isTabNameTaken($array['name'])) {
				$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
				return false;
			}
		} else {
			$this->setAPIResponse('error', 'Tab name was not supplied', 422);
			return false;
		}
		if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
			$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
			return false;
		}
		if (!array_key_exists('image', $array)) {
			$this->setAPIResponse('error', 'Tab image was not supplied', 422);
			return false;
		}
		$response = [
			array(
				'function' => 'query',
				'query' => array(
					'INSERT INTO [tabs]',
					$array
				)
			),
		];
		$this->setAPIResponse(null, 'Tab added');
		$this->setLoggerChannel('Tab Management');
		$this->logger->debug('Added Tab for [' . $array['name'] . ']');
		return $this->processQueries($response);
	}


    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @psalm-suppress PossiblyNullReference */
        $command = $this->getApplication()->find('db:check');

        $arguments = array(
            'command' => 'db:check',
        );

        $cmdInput = new ArrayInput($arguments);
        $returnCode = $command->run($cmdInput, $output);

        if ($returnCode === 1) {
            $output->writeln(array(
                'Database update starting',
                '========================',
            ));

            $Config = Config::getConfig();
            $Update = new Update($Config, new Sql());
            $Update->runUpdateScript();
            $output->writeln('All done.');
        }
        return 0;
    }


function createWhereClause($owner, $filter, $search, $daterange, $ok, $warning, $critical, $unknown)
{
	$where_clause = "";

	// owner
	if($owner == "owned"){ $where_clause .= " AND owner != ''"; }
	elseif($owner == "not owned"){ $where_clause .= " AND owner = ''"; }

	// advanced search (with *)
	if($search != ""){
		$like = "";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}

		$where_clause .= " AND $filter LIKE '$like'";
	}

	// daterange
	if($daterange != ""){
		$daterange_parts = explode(" - ", $daterange);
		$start = $daterange_parts[0];
		$end = $daterange_parts[1];

		// modify start and end timestamp (1 Jan 1970 = -3600).
		// perhaps a little bug from DateRangePicker
		$start = strtotime($start);
		$start += 3600;
		$end = strtotime($end);
		$end += 86400 + 3600;
		$where_clause .= " AND o_sec > $start AND o_sec < $end";
	}

	// states
	$states_list = "";
	if($ok != "")		{ $states_list .= "0,"; }
	if($warning != "")	{ $states_list .= "1,"; }
	if($critical != "")	{ $states_list .= "2,"; }
	if($unknown != "")	{ $states_list .= "3,"; }
	$states_list = trim($states_list, ",");

	if($states_list != ""){
		$where_clause .= " AND state IN ($states_list)";
	}

	$where_clause .= " ORDER BY o_sec DESC LIMIT 500";
	return $where_clause;
}


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


function phoromatic_quit_if_invalid_input_found($input_keys = null)
{
	if(empty($input_keys))
	{
		// Check them all if not being selective about what keys to check
		$input_keys = array_keys($_REQUEST);
	}
	// backup as to sanitization and stripping elsewhere, safeguard namely check for things like < for fields that shouldn't have it
	// plus a few simple backups as safeguards for words that really have no legit relevance within Phoromatic...

	foreach(array('<', 'document.write', '../', 'onerror', 'onload', 'alert(') as $invalid_string)
	{
		foreach($input_keys as $key)
		{
			if(isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
			{
				foreach(pts_arrays::to_array($_REQUEST[$key]) as $val_to_check)
				{
					if(stripos($val_to_check, $invalid_string) !== false)
					{
						echo 'Exited due to invalid input ( ' . $invalid_string . ') attempted: ' . htmlspecialchars($val_to_check);
						exit;
					}
				}
			}
		}
	}
}


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


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

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

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

        return $comment;
    }


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

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

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

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

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


            self::removeLevel($kid->id);
        }
    }


function db_seq_nextval($seqname)
{
    global $DatabaseType;

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

    return $seq;
}


$this->admin->json_response = ['status' => 'error', 'message' => $e->getMessage()];


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

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


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

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

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

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

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

    $rval = true;
    $e = null;

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

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

    return $rval;
  }


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

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

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


    public function setBaseUri(Response $response)
    {
        $response->headers->set('Content-Security-Policy', 'base-uri \'self\'', false);
    }


    function edit_section() {
        global $db, $user;

        $parent = new section($this->params['parent']);
        if (empty($parent->id)) $parent->id = 0;
        assign_to_template(array(
            'haveStandalone'  => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),
            'parent'          => $parent,
            'isAdministrator' => $user->isAdmin(),
        ));
    }


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


    public function rules()
    {

        $ignore = Rule::unique('users')->ignore($this->id ?? 0, 'id');

        return [
            'email' => [
                $ignore,
            ],
            'username' => [
                $ignore,
            ],

        ];

    }


   private function getCriterionValue($value) {
      if ($value instanceof \AbstractQuery) {
         return $value->getQuery();
      } else if ($value instanceof \QueryExpression) {
         return $value->getValue();
      } else if (DBmysql::isNameQuoted($value)) { //FIXME: database related
         return $value;
      } else if ($value instanceof \QueryParam) {
         return $value->getValue();
      } else {
         return $this->analyseCriterionValue($value);
      }
   }


    public static function textEncode( $mix )
    {
        if ( is_array( $mix ) )
            return implode(',', array_map( array('ezjscAjaxContent', 'textEncode'), array_filter( $mix ) ) );

        return $mix;
    }


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


    public static function post($vars) {
        switch (SMART_URL) {
            case true:
                $inFold = (Options::v('permalink_use_index_php') == "on")? "/index.php/":"/";
                if (Options::v('multilang_enable') === 'on') {
                    $lang = Language::isActive();
                    $lang = !empty($lang)? $lang . '/': '';
                    $url = Site::$url.$inFold. $lang .self::slug($vars)."/{$vars}";
                }else{
                    $url = Site::$url.$inFold.self::slug($vars)."/{$vars}";
                }

                break;

            default:
                if (Options::v('multilang_enable') === 'on') {
                    $lang = Language::isActive();
                    $lang = !empty($lang)? '&lang=' . $lang: '';
                    $url = Site::$url."/?post={$vars}{$lang}";
                }else{
                    $url = Site::$url."/?post={$vars}";
                }
                break;

        }

        return $url;
    }


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


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

        $out = array();

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

        $out = $DB->result();

        return $out;
    }


    function getFontSize()
    {
        $fs = $GLOBALS['PMA_Config']->get('fontsize');
        if (!is_null($fs)) {
            return $fs;
        }
        if (isset($_COOKIE['pma_fontsize'])) {
            return $_COOKIE['pma_fontsize'];
        }
        return '82%';
    }


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


				$ip = getenv('HTTP_FORWARDED');
			}
			else {
				$ip = $_SERVER['REMOTE_ADDR'];
			}
			return $ip;
		}


    protected function getStatusCode($exception)
    {
        if ($exception instanceof HttpExceptionInterface) {
            $code = $exception->getStatusCode();
        }
        elseif ($exception instanceof AjaxException) {
            $code = 406;
        }
        else {
            $code = 500;
        }

        return $code;
    }


    private function runCallback() {
        foreach ($this->records as &$record) {
            if (isset($record->ref_type)) {
                $refType = $record->ref_type;
                if (class_exists($record->ref_type)) {
                    $type = new $refType();
                    $classinfo = new ReflectionClass($type);
                    if ($classinfo->hasMethod('paginationCallback')) {
                        $item = new $type($record->original_id);
                        $item->paginationCallback($record);
                    }
                }
            }
        }
    }


	protected function gdImage($image, $filename, $destformat, $mime, $jpgQuality = null ){

		if (!$jpgQuality) {
			$jpgQuality = $this->options['jpgQuality'];
		}
		if ($destformat == 'jpg' || ($destformat == null && $mime == 'image/jpeg')) {
			return imagejpeg($image, $filename, $jpgQuality);
		}

		if ($destformat == 'gif' || ($destformat == null && $mime == 'image/gif')) {
			return imagegif($image, $filename, 7);
		}

		return imagepng($image, $filename, 7);
	}


	public function addTab($array)
	{
		if (!$array) {
			$this->setAPIResponse('error', 'no data was sent', 422);
			return null;
		}
		$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
		$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
		$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
		$array['enabled'] = ($array['enabled']) ?? 0;
		$array['default'] = ($array['default']) ?? 0;
		$array['type'] = ($array['type']) ?? 1;
		$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
		if (array_key_exists('name', $array)) {
			$array['name'] = htmlspecialchars($array['name']);
			if ($this->isTabNameTaken($array['name'])) {
				$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
				return false;
			}
		} else {
			$this->setAPIResponse('error', 'Tab name was not supplied', 422);
			return false;
		}
		if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
			$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
			return false;
		}
		if (!array_key_exists('image', $array)) {
			$this->setAPIResponse('error', 'Tab image was not supplied', 422);
			return false;
		}
		$response = [
			array(
				'function' => 'query',
				'query' => array(
					'INSERT INTO [tabs]',
					$array
				)
			),
		];
		$this->setAPIResponse(null, 'Tab added');
		$this->setLoggerChannel('Tab Management');
		$this->logger->debug('Added Tab for [' . $array['name'] . ']');
		return $this->processQueries($response);
	}


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


            foreach ($fields as $field) {
                $fieldName = $field->fieldName;
                if ($field->type == 'date' || $field->type == 'dateTime') {
                    if (is_numeric($record->$fieldName))
                        $record->$fieldName = Formatter::formatLongDateTime($record->$fieldName);
                }elseif ($field->type == 'link') {
                    $name = $record->$fieldName;
                    if (!empty($field->linkType)) {
                        list($name, $id) = Fields::nameAndId($name);
                    }
                    if (!empty($name))
                        $record->$fieldName = $name;
                }elseif ($fieldName == 'visibility') {
                    $record->$fieldName = $record->$fieldName == 1 ? 'Public' : 'Private';
                }
            }


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

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


public function StartTLS() {
    $this->error = null; # to avoid confusion

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

    fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);

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

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

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

    // Begin encrypted connection
    if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
      return false;
    }

    return true;
  }


    public function setAuthorizedBackendSession()
    {
        $_SESSION['authorized'] = true;
        $_SESSION['lastSessionId'] = time();
        $_SESSION['tstamp'] = time();
        $_SESSION['expires'] = time() + $this->expireTimeInMinutes * 60;
        $_SESSION['isBackendSession'] = true;
        // Renew the session id to avoid session fixation
        $this->renewSession();
    }


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


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


    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 scrap($param) {
        if ($param != '') {

            foreach ($param as $k => $v) {

                if (is_array($v)) {

                    foreach ($v as $k2 => $v2) {

                        $data[$k2] = $v2;

                    }

                }else{

                    $data = '';

                }

            }

        } else {

            $data = '';

        }

        return $data;
    }


    function update() {
        parent::update();
        expSession::clearAllUsersSessionCache('navigation');
    }


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

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

        $simplenote = new expSimpleNote($this->params['id']);
        assign_to_template(array(
            'simplenote'=>$simplenote,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'tab'=>$this->params['tab']
        ));
    }


    public function admin () {
        User::secure();
        System::gZip();
        if( User::access(2) ) {
            System::versionCheck();
            Control::handler('backend');
        }else{
            Theme::admin('header');
            Control::error('noaccess');
            Theme::admin('footer');
        }
        System::Zipped();
    }


    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 setModelAttributes(&$model,&$attributeList,&$params) {
        $data = array ();
        foreach($attributeList as &$attr) {
            if(!isset($attr['name'],$attr['value']))
                continue;

            if(null !== $field = $model->getField($attr['name'])) {
                // first do variable/expression evaluation, // then process with X2Fields::parseValue()
                $type = $field->type;
                $value = $attr['value'];
                if(is_string($value)){
                    if(strpos($value, '=') === 0){
                        $evald = X2FlowFormatter::parseFormula($value, $params);
                        if(!$evald[0])
                            return false;
                        $value = $evald[1];
                    } elseif($params !== null){

                        if(is_string($value) && isset($params['model'])){
                            $value = X2FlowFormatter::replaceVariables(
                                $value, $params['model'], $type);
                        }
                    }
                }

                $data[$attr['name']] = $value;
            }
        }
        if (!isset ($model->scenario))
            $model->setScenario ('X2Flow');
        $model->setX2Fields ($data);

        if ($model instanceof Actions && isset($data['complete'])) {
            switch($data['complete']) {
                case 'Yes':
                    $model->complete();
                    break;
                case 'No':
                    $model->uncomplete();
                    break;
            }
        }

        return true;
    }


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


    public function fetchRow($sql)
    {
        // retrieve row
        $query_id = $this->query($sql);

        $record = mysql_fetch_row($this->query_id);

        $this->freeResult($query_id);

        return $record;
    }#-#fetchArray()


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


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 getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}


    public function renderAttribute ($name) {
        switch ($name) {
            case 'name':
                echo $this->relatedModel->getLink (/*array (
                    'class' => 'quick-read-link',
                    'data-id' => $this->relatedModel->id,
                    'data-class' => get_class ($this->relatedModel),
                    'data-name' => CHtml::encode ($this->relatedModel->name),
                )*/);
                break;
            case 'relatedModelName':
                echo $this->getRelatedModelName ();
                break;
            case 'assignedTo':
                echo $this->relatedModel->renderAttribute ('assignedTo');
                break;
            case 'label':
                echo $this->getLabel ();
                break;
            case 'createDate':
                echo X2Html::dynamicDate ($this->relatedModel->createDate);
                break;
        }
    }


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

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


            return !isset($thisstaff) || $f->isRequiredForStaff();
        };
        if (!$form->isValid($filter))
            $valid  = false;

        //Make sure the email is not in-use
        if (($field=$form->getField('email'))
                && $field->getClean()
                && User::lookup(array('emails__address'=>$field->getClean()))) {
            $field->addError(__('Email is assigned to another user'));
            $valid = false;
        }

        return $valid ? self::fromVars($form->getClean(), $create) : null;
    }


    public static function meta($cont_title='', $cont_desc='', $pre =''){
        global $data;
        //print_r($data);
        //if(empty($data['posts'][0]->title)){

        if(is_array($data) && isset($data['posts'][0]->title)){

            $sitenamelength = strlen(Options::get('sitename'));
            $limit = 70-$sitenamelength-6;
            $cont_title = substr(Typo::Xclean(Typo::strip($data['posts'][0]->title)),0,$limit);
            $titlelength = strlen($data['posts'][0]->title);
            if($titlelength > $limit+3) { $dotted = "...";} else {$dotted = "";}
            $cont_title = "{$pre} {$cont_title}{$dotted} - ";
        }else{
            $cont_title = "";
        }
        if(is_array($data)  && isset($data['posts'][0]->content)){
            $desc = Typo::strip($data['posts'][0]->content);
        }else{
            $desc = "";
        }

        $meta = "
    <!--// Start Meta: Generated Automaticaly by GeniXCMS -->
    <!-- SEO: Title stripped 70chars for SEO Purpose -->
    <title>{$cont_title}".Options::get('sitename')."</title>
    <meta name=\"Keyword\" content=\"".Options::get('sitekeywords')."\">
    <!-- SEO: Description stripped 150chars for SEO Purpose -->
    <meta name=\"Description\" content=\"".self::desc($desc)."\">
    <meta name=\"Author\" content=\"Puguh Wijayanto | MetalGenix IT Solutions - www.metalgenix.com\">
    <meta name=\"Generator\" content=\"GeniXCMS\">
    <meta name=\"robots\" content=\"".Options::get('robots')."\">
    <meta name=\"revisit-after\" content=\" days\">
    <link rel=\"shortcut icon\" href=\"".Options::get('siteicon')."\" />
        ";

        $meta .= "
    <!-- Generated Automaticaly by GeniXCMS :End Meta //-->";
        echo $meta;
    }


    public function getTrackingId()
    {
        if(isset($this->ectid)) return $this->ectid;
        else return '';
    }


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

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


	public function __construct() {
		$this->options['alias']    = '';              // alias to replace root dir name
		$this->options['dirMode']  = 0755;            // new dirs mode
		$this->options['fileMode'] = 0644;            // new files mode
		$this->options['quarantine'] = '.quarantine';  // quarantine folder name - required to check archive (must be hidden)
		$this->options['rootCssClass'] = 'elfinder-navbar-root-local';
		$this->options['followSymLinks'] = true;
	}


	protected function _fopen($path, $mode='rb') {

		if (($mode == 'rb' || $mode == 'r')) {
			try {
				$res = $this->dropbox->media($path);
				$url = parse_url($res['url']);
 				$fp = stream_socket_client('ssl://'.$url['host'].':443');
 				fputs($fp, "GET {$url['path']} HTTP/1.0\r\n");
 				fputs($fp, "Host: {$url['host']}\r\n");
 				fputs($fp, "\r\n");
 				while(trim(fgets($fp)) !== ''){};
 				return $fp;
			} catch (Dropbox_Exception $e) {
				return false;
			}
		}

		if ($this->tmp) {
			$contents = $this->_getContents($path);

			if ($contents === false) {
				return false;
			}

			if ($local = $this->getTempFile($path)) {
				if (file_put_contents($local, $contents, LOCK_EX) !== false) {
					return @fopen($local, $mode);
				}
			}
		}

		return false;
	}


    public function search() {
//        global $db, $user;
        global $db;

        $sql = "select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "addresses as a "; //R JOIN " .
        //$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
        $sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
            "*' IN BOOLEAN MODE) ";
        $sql .= "order by match (a.firstname,a.lastname,a.email,a.organization)  against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
        $res = $db->selectObjectsBySql($sql);
        foreach ($res as $key=>$record) {
            $res[$key]->title = $record->firstname . ' ' . $record->lastname;
        }
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    public function __construct () {

    }


                $banner->increaseImpressions();
            }
        }

        // assign banner to the template and show it!
        assign_to_template(array(
            'banners'=>$banners
        ));
    }


	public function save()
	{
		global $DB;

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


public function get() {
		$r = '
'.$this->stack_name.'
';
		for ($i = 0; $i < count($this->tiles_array); $i++) {
			$top = rand(-5, 5);
			$left = rand(-5, 5);
			$img_w = $this->tiles_array[$i]->getWidth();
			$extra = '';
			if ($img_w < IMAGE_WIDTH) {
				$extra = 'width:'.$img_w.'px;';
			}
			$r .= '
tiles_array[$i]->getMiniatureSrc().'\');margin-top:'.$top.'px; margin-left:'.$left.'px;'.$extra.'">
';
		}
		return $r;
	}


    function preview()
    {
        if ($this->params['id'] == 0) { // we want the default editor
            $demo = new stdClass();
            $demo->id = 0;
            $demo->name = "Default";
            if ($this->params['editor'] == 'ckeditor') {
                $demo->skin = 'kama';
            } elseif ($this->params['editor'] == 'tinymce') {
                $demo->skin = 'lightgray';
            }
        } else {
            $demo = self::getEditorSettings($this->params['id'], expString::escape($this->params['editor']));
        }
        assign_to_template(
            array(
                'demo' => $demo,
                'editor' => $this->params['editor']
            )
        );
    }


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


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

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

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


    public function setContainer($container)
    {
        $this->container = $container;
        $container->setType('ctBanner');
    }


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

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


function critere_where_dist($idb, &$boucles, $crit) {
	$boucle = &$boucles[$idb];
	if (isset($crit->param[0])) {
		$_where = calculer_liste($crit->param[0], $idb, $boucles, $boucle->id_parent);
	} else {
		$_where = '@$Pile[0]["where"]';
	}

	if ($crit->cond) {
		$_where = "(($_where) ? ($_where) : '')";
	}

	if ($crit->not) {
		$_where = "array('NOT',$_where)";
	}

	$boucle->where[] = $_where;
}


    public function getQueryGroupby()
    {
        return "a.id";
    }


function cleanCSV($string)
{
    $check = '/^[=@]/';
    if (!is_numeric($string)) {
        $check = '/^[=@+-]/';
    }

    return preg_replace($check, "", $string);
}


				$this->{$callback[0]}->{$callback[1]}($objPage, $objLayout, $this);
			}
		}

		$headBag = $this->responseContext->get(HtmlHeadBag::class);

		// Set the page title and description AFTER the modules have been generated
		$this->Template->mainTitle = $objPage->rootPageTitle;
		$this->Template->pageTitle = htmlspecialchars($headBag->getTitle());

		// Remove shy-entities (see #2709)
		$this->Template->mainTitle = str_replace('[-]', '', $this->Template->mainTitle);
		$this->Template->pageTitle = str_replace('[-]', '', $this->Template->pageTitle);

		// Meta robots tag
		$this->Template->robots = $headBag->getMetaRobots();

		// Canonical
		if ($objPage->enableCanonical)
		{
			$this->Template->canonical = $headBag->getCanonicalUriForRequest($request);
		}

		// Fall back to the default title tag
		if (!$objLayout->titleTag)
		{
			$objLayout->titleTag = '{{page::pageTitle}} - {{page::rootPageTitle}}';
		}

		// Assign the title and description
		$this->Template->title = strip_tags(System::getContainer()->get('contao.insert_tag.parser')->replaceInline($objLayout->titleTag));
		$this->Template->description = htmlspecialchars($headBag->getMetaDescription());

		// Body onload and body classes
		$this->Template->onload = trim($objLayout->onload);
		$this->Template->class = trim($objLayout->cssClass . ' ' . $objPage->cssClass);

		// Execute AFTER the modules have been generated and create footer scripts first
		$this->createFooterScripts($objLayout, $objPage);
		$this->createHeaderScripts($objPage, $objLayout);
	}


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

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

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


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

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


                $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));
                $ret .= scan_container($cLoc, $page->id);
                $ret .= scan_page($page->id);
            }


    public static function title($id){
        $sql = sprintf("SELECT `title` FROM `posts` WHERE `id` = '%d'", $id);
        try
        {
            $r = Db::result($sql);
            if(isset($r['error'])){
                $title['error'] = $r['error'];
                //echo $title['error'];
            }else{
                $title = $r[0]->title;
            }

        }
        catch (Exception $e)
        {
            $title = $e->getMessage();
        }

        return $title;
    }


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


    public function getQuerySelect()
    {
        $R1 = 'R1_' . $this->field->id;
        $R2 = 'R2_' . $this->field->id;
        return "$R2.id AS `" . $this->field->name . "`";
    }


            $q->close();

        }

        self::$num_rows = $n;
        return $r;
    }


    function edit() {
        global $user;

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

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

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

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


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

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


					$args['name'][$i] = $this->normalize($name, $opts);
				}
			} else {
				$args['name'] = $this->normalize($args['name'], $opts);
			}
		}
		return true;
	}


	public function remove($key)
	{
		$session =& $this->getSessionRef($key);
		unset($session);

		return $this;
	}


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

		}

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

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

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

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

	}


                $section = new section(intval($page));
                if ($section) {
//                    self::deleteLevel($section->id);
                    $section->delete();
                }
            }
        }


    public function getQueryOrderby()
    {
        $uh = UserHelper::instance();
        $R1 = 'R1_' . $this->field->id;
        $R2 = 'R2_' . $this->field->id;
        return "$R2.ugroup_id";
    }


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

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


			$stat = $this->stat($p);

			if (!$stat) { // invalid links
				continue;
			}

			if (!empty($stat['hidden']) || !$this->mimeAccepted($stat['mime'], $mimes)) {
				continue;
			}

			$name = $stat['name'];

			if ((!$mimes || $stat['mime'] !== 'directory') && $this->stripos($name, $q) !== false) {
				$stat['path'] = $this->path($stat['hash']);
				if ($this->URL && !isset($stat['url'])) {
					$path = str_replace($this->separator, '/', substr($p, strlen($this->root) + 1));
					if ($this->encoding) {
						$path = str_replace('%2F', '/', rawurlencode($this->convEncIn($path, true)));
					}
					$stat['url'] = $this->URL . $path;
				}

				$result[] = $stat;
			}
			if ($stat['mime'] == 'directory' && $stat['read'] && !isset($stat['alias'])) {
				$result = array_merge($result, $this->doSearch($p, $q, $mimes));
			}
		}

		return $result;
	}


    public function popupnewsitem($id)
    {
        $query = 'SELECT *
                 FROM ' . TABLE_PREFIX .'news
                 WHERE id=' . $id . ' ';

        return DB::get_row($query);
    }


public static function generated(){
        $end_time = microtime(TRUE);
        $time_taken = $end_time - $GLOBALS['start_time'];
        $time_taken = round($time_taken,5);
        echo 'Page generated in '.$time_taken.' seconds.';
    }


    public function __construct () {

    }


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

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


    public function store($zdb)
    {
        try {
            $values = array(
                self::PK        => $this->id,
                'model_fields'  => serialize($this->fields)
            );

            if (!isset($this->id) || $this->id == '') {
                //we're inserting a new model
                unset($values[self::PK]);
                $this->creation_date = date("Y-m-d H:i:s");
                $values['model_creation_date'] = $this->creation_date;

                $insert = $zdb->insert(self::TABLE);
                $insert->values($values);
                $results = $zdb->execute($insert);

                if ($results->count() > 0) {
                    return true;
                } else {
                    throw new \Exception(
                        'An error occurred inserting new import model!'
                    );
                }
            } else {
                //we're editing an existing model
                $update = $zdb->update(self::TABLE);
                $update->set($values);
                $update->where(self::PK . '=' . $this->id);
                $zdb->execute($update);
                return true;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Something went wrong storing import model :\'( | ' .
                $e->getMessage() . "\n" . $e->getTraceAsString(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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


						unset($return[$key]);
				}
			}
			break;
	}
	return @array_change_key_case($return, CASE_UPPER);
}


    protected function fsock_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp)
    {
        $connect_timeout = 3;
        $connect_try = 3;
        $method = 'GET';
        $readsize = 4096;
        $ssl = '';

        $getSize = null;
        $headers = '';

        $arr = parse_url($url);
        if (!$arr) {
            // Bad request
            return false;
        }
        if ($arr['scheme'] === 'https') {
            $ssl = 'ssl://';
        }

        // query
        $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : '';
        // port
        $port = isset($arr['port']) ? $arr['port'] : '';
        $arr['port'] = $port ? $port : ($ssl ? 443 : 80);

        $url_base = $arr['scheme'] . '://' . $arr['host'] . ($port ? (':' . $port) : '');


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

		$args = array();
		$args[] = $this->hash;
		$args[] = '--no-merges';

		$canSkip = true;
		if ($this->skip > 0)
			$canSkip = $this->exe->CanSkip();

		if ($canSkip) {
			if ($this->limit > 0) {
				$args[] = '--max-count=' . $this->limit;
			}
			if ($this->skip > 0) {
				$args[] = '--skip=' . $this->skip;
			}
		} else {
			if ($this->limit > 0) {
				$args[] = '--max-count=' . ($this->limit + $this->skip);
			}
		}


    function delete_option_master() {
        global $db;

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

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


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

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


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


    public static function insert($vars) {
        if(is_array($vars)) {
            $slug = Typo::slugify($vars['title']);
            $vars = array_merge($vars, array('slug' => $slug));
            //print_r($vars);
            $ins = array(
                        'table' => 'options',
                        'key' => $vars
                    );
            $post = Db::insert($ins);
        }
        return $post;
    }


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


    public static function getParent($id){
        $q = self::getId($id);
        return $q[0]->parent;
    }


function teampass_decrypt_pw($encrypted, $salt, $rand_key, $itcount = 2072)
{
    $encrypted = base64_decode($encrypted);
    $pass_salt = substr($encrypted, -64);
    $encrypted = substr($encrypted, 0, -64);
    $key       = teampass_pbkdf2_hash($salt, $pass_salt, $itcount, 16, 32);
    $iv        = base64_decode(substr($encrypted, 0, 43) . '==');
    $encrypted = substr($encrypted, 43);
    $mac       = substr($encrypted, -64);
    $encrypted = substr($encrypted, 0, -64);
    if ($mac !== hash_hmac('sha256', $encrypted, $salt)) return null;
    return substr(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, 'ctr', $iv), "\0\4"), strlen($rand_key));
}