    public function breadcrumb() {
        global $sectionObj;

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


	function unlockTables() {
        $sql = "UNLOCK TABLES";

        $res = mysqli_query($this->connection, $sql);
        return $res;
    }


	protected function removeNetVolume($key) {
		$netVolumes = $this->getNetVolumes();
		if (is_string($key) && isset($netVolumes[$key])) {
			unset($netVolumes[$key]);
			$this->saveNetVolumes($netVolumes);
		}
	}


    protected function __construct() {
        parent::__construct();
        self::$locale = fusion_get_locale('', LOCALE.LOCALESET.'search.php');
    }


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


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

//        eDebug($files,true);
    }


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

        $sql = "select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "external_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 static function isHadSub($parent, $menuid =''){
        $sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
    }


function html_escape_request_var($string) {
	return htmlspecialchars(get_request_var($string), ENT_QUOTES, 'UTF-8');
}


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

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

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

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

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


    public function getChart($renderer, $id, $store_in_session = true)
    {
        $c          = null;
        $chart_data = null;
        if ($renderer != null && $store_in_session) {
            $session = new Tracker_Report_Session($renderer->report->id);
            $session->changeSessionNamespace("renderers.{$renderer->id}");

            // look for the chart in the session
            $chart_data = $session->get("charts.$id");
        }

        if (! $chart_data) {
            // not found. look in the db
            $dao        = new GraphOnTrackersV5_ChartDao(CodendiDataAccess::instance());
            $chart_data = $dao->searchById($id)->getRow();
        }

        if ($chart_data) {
            if (! $renderer) {
                $report   = null; //We don't know the report
                $renderer = Tracker_Report_RendererFactory::instance()->getReportRendererById($chart_data['report_graphic_id'], $report, $store_in_session);
            }
            if ($renderer) {
                $c = $this->instanciateChart($chart_data, $renderer, $store_in_session);
            }
        }
        return $c;
    }


    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 __construct($page, $file = null) {

    $this->page      = $page;
    $this->file      = $file;
    $this->blueprint = $page->blueprint();
    $this->filename  = $this->blueprint->files()->sanitize() ? '{safeFilename}' : '{filename}';

    if($this->file) {
      $this->replace();
    } else {
      $this->upload();
    }

  }


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


                    $expanded = implode($joiner, $kvp);
                    if ($isAssoc) {
                        // Don't prepend the value name when using the explode
                        // modifier with an associative array.
                        $actuallyUseQuery = false;
                    }
                } else {
                    if ($isAssoc) {
                        // When an associative array is encountered and the
                        // explode modifier is not set, then the result must be
                        // a comma separated list of keys followed by their
                        // respective values.
                        foreach ($kvp as $k => &$v) {
                            $v = $k . ',' . $v;
                        }
                    }
                    $expanded = implode(',', $kvp);
                }

            } else {
                if ($value['modifier'] == ':') {
                    $variable = substr($variable, 0, $value['position']);
                }
                $expanded = rawurlencode($variable);
                if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
                    $expanded = $this->decodeReserved($expanded);
                }
            }

            if ($actuallyUseQuery) {
                if (!$expanded && $joiner != '&') {
                    $expanded = $value['value'];
                } else {
                    $expanded = $value['value'] . '=' . $expanded;
                }
            }

            $replacements[] = $expanded;
        }

        $ret = implode($joiner, $replacements);
        if ($ret && $prefix) {
            return $prefix . $ret;
        }

        return $ret;
    }


    public function testCanTransformAndRetrievePartsIndividually()
    {
        $uri = (new Uri(''))
            ->withFragment('#test')
            ->withHost('example.com')
            ->withPath('path/123')
            ->withPort(8080)
            ->withQuery('?q=abc')
            ->withScheme('http')
            ->withUserInfo('user', 'pass');

        // Test getters.
        $this->assertEquals('user:pass@example.com:8080', $uri->getAuthority());
        $this->assertEquals('test', $uri->getFragment());
        $this->assertEquals('example.com', $uri->getHost());
        $this->assertEquals('path/123', $uri->getPath());
        $this->assertEquals(8080, $uri->getPort());
        $this->assertEquals('q=abc', $uri->getQuery());
        $this->assertEquals('http', $uri->getScheme());
        $this->assertEquals('user:pass', $uri->getUserInfo());
    }


    public function rules()
    {
        $rules = [];
        $inputs = $this->all();

        $validateEmail = false;
        $validateUsername = false;

        if (!isset($inputs['username']) || !isset($inputs['email'])) {
            $validateUsername = true;
        }

        if (isset($inputs['email']) && !isset($inputs['username'])) {
            $validateUsername = false;
            $validateEmail = true;
        }

        if (isset($inputs['email']) && isset($inputs['username'])) {
            $validateUsername = true;
            $validateEmail = true;
        }

        if ($validateEmail) {
            $rules['email'] = 'email|string|min:3|required|string|max:255|unique:users';
        }

        if ($validateUsername) {
            $rules['username'] = 'alpha_dash|string|min:1|required|string|max:255|unique:users';
        }
        if (isset($inputs['confirm_password'])) {
            $rules['confirm_password'] = 'required|min:1|same:password';
        }

        if (get_option('captcha_disabled', 'users') !== 'y') {
            $rules['captcha'] = 'captcha';
        }

        if (isset($inputs['email']) && $inputs['email'] != false && ((get_option('disable_registration_with_temporary_email', 'users') == 'y'))) {
            $rules['email'] = $rules['email'] . '|temporary_email_check';
        }

        if (get_option('require_terms', 'users') == 'y') {
            $rules['terms'] = 'terms:terms_user';
            if (isset($inputs['newsletter_subscribe']) and $inputs['newsletter_subscribe']) {
                $rules['terms'] = $rules['terms'] . ', terms_newsletter';
            }
        }
        $rules['password'] = 'required|min:1';

        return $rules;
    }


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

        $id = isset($this->params['id']) ? $this->params['id'] : null;
        $record = new optiongroup_master($id);
        assign_to_template(array(
            'record'=>$record
        ));
    }


    public function onKernelResponse(ResponseEvent $event)
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();

        if (!$request->hasSession() || !$request->attributes->get('_security_firewall_run', false)) {
            return;
        }

        if ($this->dispatcher) {
            $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);
        }
        $this->registered = false;
        $session = $request->getSession();
        $sessionId = $session->getId();
        $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : null;
        $token = $this->tokenStorage->getToken();

        if (null === $token || $this->trustResolver->isAnonymous($token)) {
            if ($request->hasPreviousSession()) {
                $session->remove($this->sessionKey);
            }
        } else {
            $session->set($this->sessionKey, serialize($token));

            if (null !== $this->logger) {
                $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
            }
        }

        if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
            $usageIndexReference = $usageIndexValue;
        }
    }


	public static function simple($input)
	{
		return empty($str) ? '' : pts_strings::keep_in_string($input, pts_strings::CHAR_LETTER | pts_strings::CHAR_NUMERIC | pts_strings::CHAR_DASH | pts_strings::CHAR_DECIMAL | pts_strings::CHAR_SPACE | pts_strings::CHAR_UNDERSCORE | pts_strings::CHAR_COMMA | pts_strings::CHAR_AT | pts_strings::CHAR_COLON);
	}


    public function toolbar() {
//        global $user;

        $menu = array();
		$dirs = array(
			BASE.'framework/modules/administration/menus',
			BASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'
		);

		foreach ($dirs as $dir) {
		    if (is_readable($dir)) {
			    $dh = opendir($dir);
			    while (($file = readdir($dh)) !== false) {
				    if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {
					    $menu[substr($file,0,-4)] = include($dir.'/'.$file);
                        if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);
				    }
			    }
		    }
		}

        // sort the top level menus alphabetically by filename
		ksort($menu);
		$sorted = array();
		foreach($menu as $m) $sorted[] = $m;

        // slingbar position
        if (isset($_COOKIE['slingbar-top'])){
            $top = $_COOKIE['slingbar-top'];
        } else {
            $top = SLINGBAR_TOP;
        }

		assign_to_template(array(
            'menu'=>(bs3()) ? $sorted : json_encode($sorted),
            "top"=>$top
        ));
    }


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


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

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

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


	public function isAllowedFilename($filename){
		$allow_array = array(
			'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',
			'.mp3','.wav','.mp4',
			'.mov','.webmv','.flac','.mkv',
			'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso',
			'.pdf','.ofd','.swf','.epub','.xps',
			'.doc','.docx','.wps',
			'.ppt','.pptx','.xls','.xlsx','.txt','.psd','.csv',
			'.cer','.ppt','.pub','.json','.css',
			) ;

		$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名（转为小写后）
		if(in_array( $ext , $allow_array ) ){
			return true ;
		}
		return false;
	}


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


    public function testPopBeforeSmtpBad()
    {
        //Start a fake POP server on a different port
        //so we don't inadvertently connect to the previous instance
        $pid = shell_exec('nohup ./runfakepopserver.sh 1101 >/dev/null 2>/dev/null & printf "%u" $!');
        $this->pids[] = $pid;

        sleep(2);
        //Test a known-bad login
        $this->assertFalse(
            POP3::popBeforeSmtp('localhost', 1101, 10, 'user', 'xxx', $this->Mail->SMTPDebug),
            'POP before SMTP should have failed'
        );
        shell_exec('kill -TERM '.escapeshellarg($pid));
        sleep(2);
    }


			return "__NOTOC____NOEDITSECTION__" . \CategoryViewer::shortList( $articleLinks, $articleStartChars );
		}
		return '';
	}


    public function testResolvesUris($base, $rel, $expected)
    {
        $uri = new Uri($base);
        $actual = Uri::resolve($uri, $rel);
        $this->assertEquals($expected, (string) $actual);
    }


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


  public function AddReplyTo($address, $name = '') {
    return $this->AddAnAddress('Reply-To', $address, $name);
  }


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


			$return[$index] = strip_tags($value);
			if($return[$index] == 'zero')
				$return[$index] = '0';
		}
	}
	elseif($type == ARG_MULTISTRING) {
		foreach($return as $index => $value) {
			$return[$index] = strip_tags($value);
		}
	}
	else
		$return = strip_tags($return);

	if(! empty($return) && $type == ARG_NUMERIC) {
		if(! is_numeric($return)) {
			return preg_replace('([^\d])', '', $return);
		}
	}
	elseif(! empty($return) && $type == ARG_STRING) {
		if(! is_string($return))
			$return = $defaultvalue;
	}
	elseif(! empty($return) && $type == ARG_MULTINUMERIC) {
		foreach($return as $index => $value) {
			if(! is_numeric($value)) {
				$return[$index] = preg_replace('([^\d])', '', $value);
			}
		}
		return $return;
	}
	elseif(! empty($return) && $type == ARG_MULTISTRING) {
		foreach($return as $index => $value) {
			if(! is_string($value))
				$return[$index] = $defaultvalue;
			elseif($addslashes)
				$return[$index] = addslashes($value);
		}
		return $return;
	}

	if(is_string($return)) {
		if(strlen($return) == 0)
			$return = $defaultvalue;
		elseif($addslashes)
			$return = addslashes($return);
	}

	return $return;
}


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 static function DragnDropReRank2() {
        global $router, $db;

        $id = $router->params['id'];
        $page = new section($id);
        $old_rank = $page->rank;
        $old_parent = $page->parent;
        $new_rank = $router->params['position'] + 1;  // rank
        $new_parent = intval($router->params['parent']);

        $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent);  // close in hole
        $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent);  // make room

        $params = array();
        $params['parent'] = $new_parent;
        $params['rank'] = $new_rank;
        $page->update($params);

        self::checkForSectionalAdmins($id);
        expSession::clearAllUsersSessionCache('navigation');
    }


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

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

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

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

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

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


    private function decryptContentEncryptionKey($private_key_or_secret) {
        switch ($this->header['alg']) {
            case 'RSA1_5':
                $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);
                $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);
                break;
            case 'RSA-OAEP':
                $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_OAEP);
                $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);
                break;
            case 'dir':
                $this->content_encryption_key = $private_key_or_secret;
                break;
            case 'A128KW':
            case 'A256KW':
            case 'ECDH-ES':
            case 'ECDH-ES+A128KW':
            case 'ECDH-ES+A256KW':
                throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');
            default:
                throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');
        }
        if (!$this->content_encryption_key) {
            # NOTE:
            #  Not to disclose timing difference between CEK decryption error and others.
            #  Mitigating Bleichenbacher Attack on PKCS#1 v1.5
            #  ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303
            $this->generateContentEncryptionKey(null);
        }
    }


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


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


function _makeExtra($value, $title = '') {
    global $THIS_RET;

    if ($THIS_RET['WITH_TEACHER_ID'])
        $return .= ''._with.': ' . GetTeacher($THIS_RET['WITH_TEACHER_ID']) . '
';
    if ($THIS_RET['NOT_TEACHER_ID'])
        $return .= ''._notWith.': ' . GetTeacher($THIS_RET['NOT_TEACHER_ID']) . '
';
    if ($THIS_RET['WITH_PERIOD_ID'])
        $return .= ''._on.': ' . GetPeriod($THIS_RET['WITH_PERIOD_ID']) . '
';
    if ($THIS_RET['NOT_PERIOD_ID'])
        $return .= ''._notOn.': ' . GetPeriod($THIS_RET['NOT_PERIOD_ID']) . '
';
    if ($THIS_RET['PRIORITY'])
        $return .= ''._priority.': ' . $THIS_RET['PRIORITY'] . '
';
    if ($THIS_RET['MARKING_PERIOD_ID'])
        $return .= ''._markingPeriod.': ' . GetMP($THIS_RET['MARKING_PERIOD_ID']) . '
';

    return $return;
}


function PMA_linkURL($url)
{
    if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
        return $url;
    }

    if (!function_exists('PMA_URL_getCommon')) {
        include_once './libraries/url_generating.lib.php';
    }
    $params = array();
    $params['url'] = $url;

    $url = PMA_URL_getCommon($params);
    //strip off token and such sensitive information. Just keep url.
    $arr = parse_url($url);
    parse_str($arr["query"], $vars);
    $query = http_build_query(array("url" => $vars["url"]));
    $url = './url.php?' . $query;

    return $url;
}


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


    public function countFilesInFolder(Folder $folder, $useFilters = true, $recursive = false)
    {
        $this->assureFolderReadPermission($folder);
        $filters = $useFilters ? $this->fileAndFolderNameFilters : [];
        return $this->driver->countFilesInFolder($folder->getIdentifier(), $recursive, $filters);
    }


    private function isWindows()
    {
        return DIRECTORY_SEPARATOR !== '/';
    }


	private function setFooter( $footer ) {
		if ( \DynamicPageListHooks::getDebugLevel() == 5 ) {
			$footer .= '</nowiki></pre>';
		}
		$this->footer = $this->replaceVariables( $footer );
	}


    public static function exist($cat)
    {
        $cat = Typo::int($cat);
        $sql = "SELECT `id` FROM `cat` WHERE `id` = '{$cat}' AND `type` = 'post'";
        $q = Db::result($sql);
        // echo Db::$num_rows;
        if (Db::$num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }


                foreach ($grpusers as $u) {
                    $emails[$u->email] = trim(user::getUserAttribution($u->id));
                }


				} elseif ( $sSecLabel[0] == '{' ) {
					// Uses LST::includeTemplate() from LabeledSectionTransclusion extension to include templates from the page
					// primary syntax {template}suffix
					$template1 = trim( substr( $sSecLabel, 1, strpos( $sSecLabel, '}' ) - 1 ) );
					$template2 = trim( str_replace( '}', '', substr( $sSecLabel, 1 ) ) );
					// alternate syntax: {template|surrogate}
					if ( $template2 == $template1 && strpos( $template1, '|' ) > 0 ) {
						$template1 = preg_replace( '/\|.*/', '', $template1 );
						$template2 = preg_replace( '/^.+\|/', '', $template2 );
					}
					//Why the hell was defaultTemplateSuffix be passed all over the place for just fucking here?  --Alexia
					$secPieces    = LST::includeTemplate( $this->parser, $this, $s, $article, $template1, $template2, $template2 . $this->getTemplateSuffix(), $mustMatch, $mustNotMatch, $this->includePageParsed, implode( ', ', $article->mCategoryLinks ) );
					$secPiece[$s] = implode( isset( $this->multiSectionSeparators[$s] ) ? $this->replaceTagCount( $this->multiSectionSeparators[$s], $filteredCount ) : '', $secPieces );
					if ( $this->getDominantSectionCount() >= 0 && $s == $this->getDominantSectionCount() && count( $secPieces ) > 1 ) {
						$dominantPieces = $secPieces;
					}
					if ( ( $mustMatch != '' || $mustNotMatch != '' ) && count( $secPieces ) <= 1 && $secPieces[0] == '' ) {
						$matchFailed = true; // NOTHING MATCHED
						break;
					}
				} else {


                        echo '<LANGUAGE>' . htmlentities($value_arr['LANGUAGE']) . '</LANGUAGE>';
                        foreach ($value_arr['ENROLLMENT_INFO'] as $eid => $ed) {
                            echo '<ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                            echo '<SCHOOL_ID>' . htmlentities($ed['SCHOOL_ID']) . '</SCHOOL_ID>';
                            echo '<CALENDAR>' . htmlentities($ed['CALENDAR']) . '</CALENDAR>';
                            echo '<GRADE>' . htmlentities($ed['GRADE']) . '</GRADE>';
                            echo '<SECTION>' . htmlentities($ed['SECTION']) . '</SECTION>';
                            echo '<START_DATE>' . htmlentities($ed['START_DATE']) . '</START_DATE>';
                            echo '<DROP_DATE>' . htmlentities($ed['DROP_DATE']) . '</DROP_DATE>';
                            echo '<ENROLLMENT_CODE>' . htmlentities($ed['ENROLLMENT_CODE']) . '</ENROLLMENT_CODE>';
                            echo '<DROP_CODE>' . htmlentities($ed['DROP_CODE']) . '</DROP_CODE>';
                            echo '</ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                        }
                        echo '</STUDENT>';
                    }
                    echo '</SCHOOL>';
                }


function editEvent($selected_events, $queue, $comments)
{
	global $database_ged;

	// get all needed infos into variables
	$value_parts = explode(":", $selected_events);
	$id = $value_parts[0];
	$ged_type = $value_parts[1];

	// format comment string to avoid errors
	$comments = str_replace("'", "\'", $comments);
	$comments = str_replace("#", "\#", $comments);

	$sql = "UPDATE ".$ged_type."_queue_".$queue." SET comments='$comments' WHERE id = $id";
	$result = sqlrequest($database_ged, $sql);
	if($result){
		message(11, " : ".getLabel("message.event_edited"), "ok");
	} else {
		message(11, " : ".getLabel("message.event_edited_error"), "danger");
	}
}


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


$contents = ['form' => tep_draw_form('countries', 'countries.php', 'page=' . $_GET['page'] . '&action=insert')];


    public function getMailingVoucher($id)
    {
        trigger_error(sprintf('%s:%s is deprecated since Shopware 5.6 and will be private with 5.8.', __CLASS__, __METHOD__), E_USER_DEPRECATED);

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

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


	public function editspeed() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        assign_to_template(array(
            'calculator'=>$calc
        ));

    }


    public function testResource()
    {
        $stream = Psr7\stream_for('foo');
        $handle = StreamWrapper::getResource($stream);
        $this->assertSame('foo', fread($handle, 3));
        $this->assertSame(3, ftell($handle));
        $this->assertSame(3, fwrite($handle, 'bar'));
        $this->assertSame(0, fseek($handle, 0));
        $this->assertSame('foobar', fread($handle, 6));
        $this->assertSame('', fread($handle, 1));
        $this->assertTrue(feof($handle));

        // This fails on HHVM for some reason
        if (!defined('HHVM_VERSION')) {
            $this->assertEquals([
                'dev'     => 0,
                'ino'     => 0,
                'mode'    => 33206,
                'nlink'   => 0,
                'uid'     => 0,
                'gid'     => 0,
                'rdev'    => 0,
                'size'    => 6,
                'atime'   => 0,
                'mtime'   => 0,
                'ctime'   => 0,
                'blksize' => 0,
                'blocks'  => 0,
                0         => 0,
                1         => 0,
                2         => 33206,
                3         => 0,
                4         => 0,
                5         => 0,
                6         => 0,
                7         => 6,
                8         => 0,
                9         => 0,
                10        => 0,
                11        => 0,
                12        => 0,
            ], fstat($handle));
        }

        $this->assertTrue(fclose($handle));
        $this->assertSame('foobar', (string) $stream);
    }


    public function pending() {
//        global $db;

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

        // find the subscriber and their pending subscriptions
        $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);
        $subscriber = new subscribers($this->params['id']);

        // render the template
        assign_to_template(array(
            'subscriber'=>$subscriber,
            'ealerts'=>$ealerts
        ));
    }


                foreach ($page as $pageperm) {
                    if (!empty($pageperm['manage'])) return true;
                }


    public static function remove($var) {
        unset($_SESSION['gxsess']['val'][$var]);
    }


    function searchName() {
        return gt("Calendar Event");
    }


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

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


static function description() { return gt("Places navigation links/menus on the page."); }


    function insertObject($object, $table) {
        //if ($table=="text") eDebug($object,true);
        $sql = "INSERT INTO `" . $this->prefix . "$table` (";
        $values = ") VALUES (";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            if ($var{0} != '_') {
                $sql .= "`$var`,";
                if ($values != ") VALUES (") {
                    $values .= ",";
                }
                $values .= "'" . $this->escapeString($val) . "'";
            }
        }
        $sql = substr($sql, 0, -1) . substr($values, 0) . ")";
        //if($table=='text')eDebug($sql,true);
        if (@mysqli_query($this->connection, $sql) != false) {
            $id = mysqli_insert_id($this->connection);
            return $id;
        } else
            return 0;
    }


public static function BBCode2Html($text) {
    	$text = trim($text);

       $text = self::parseEmoji($text);

       // Smileys to find...
       $in = array(
       );

       // And replace them by...
       $out = array(
       );

    	$in[] = '[/*]';
    	$in[] = '[*]';
    	$out[] = '
';
    	$out[] = '
';

    	$text = str_replace($in, $out, $text);

    	// BBCode to find...
    	$in = array( 	 '/\[b\](.*?)\[\/b\]/ms',
    					 '/\[i\](.*?)\[\/i\]/ms',
    					 '/\[u\](.*?)\[\/u\]/ms',
    					 '/\[mark\](.*?)\[\/mark\]/ms',
    					 '/\[s\](.*?)\[\/s\]/ms',
    					 '/\[list\=(.*?)\](.*?)\[\/list\]/ms',
    					 '/\[list\](.*?)\[\/list\]/ms',
    					 '/\[\*\]\s?(.*?)\n/ms',
    					 '/\[fs(.*?)\](.*?)\[\/fs(.*?)\]/ms',
    					 '/\[color\=(.*?)\](.*?)\[\/color\]/ms'
    	);

    	// And replace them by...
    	$out = array(	 '\1',
    					 '\1',
    					 '\1',
    					 '\1',
    					 '\1',
    					 '
\2
',
    					 '
\1
',
    					 '
\1
',
    					 '\2',
    					 '\2'
    	);

    	$text = preg_replace($in, $out, $text);

    	// Prepare quote's
    	$text = str_replace("\r\n","\n",$text);

    	// paragraphs
    	$text = str_replace("\r", "", $text);
    	$text = nl2br($text);

    	// clean some tags to remain strict
    	// not very elegant, but it works. No time to do better ;)
    	if (!function_exists('removeBr')) {
    		function removeBr($s) {
    			return str_replace("
", "", $s[0]);
    		}
    	}

    	$text = preg_replace_callback('/
(.*?)<\/pre>/ms', "removeBr", $text);
    	$text = preg_replace('/

(.*?)<\/pre><\/p>/ms', "
\\1
", $text);

    	$text = preg_replace_callback('/
(.*?)<\/ul>/ms', "removeBr", $text);
    	$text = preg_replace('/

(.*?)<\/ul><\/p>/ms', "
\\1
", $text);

    	return $text;
    }


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

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

        return $subtask;
    }


    public function getAuthority()
    {
        if (empty($this->host)) {
            return '';
        }

        $authority = $this->host;
        if (!empty($this->userInfo)) {
            $authority = $this->userInfo . '@' . $authority;
        }

        if ($this->isNonStandardPort($this->scheme, $this->host, $this->port)) {
            $authority .= ':' . $this->port;
        }

        return $authority;
    }


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


				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques",
					"lang='" . $GLOBALS['spip_lang'] . "' AND id_parent=$id_parent");
				if ($row_rub) {
					$row['id_rubrique'] = $row_rub['id_rubrique'];
				}
			}
		}
	}

	return $row;
}


	private function _stablepages( $option ) {
		if ( function_exists( 'efLoadFlaggedRevs' ) ) {
			//Do not add this again if 'qualitypages' has already added it.
			if ( !$this->parametersProcessed['qualitypages'] ) {
				$this->addJoin(
					'flaggedpages',
					[
						"LEFT JOIN",
						"page_id = fp_page_id"
					]
				);
			}
			switch ( $option ) {
				case 'only':
					$this->addWhere(
						[
							'fp_stable IS NOT NULL'
						]
					);
					break;
				case 'exclude':
					$this->addWhere(
						[
							'fp_stable'	=> null
						]
					);
					break;
			}
		}
	}


        function scan_page($parent_id) {
            global $db;

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


    private function _verify($public_key_or_secret, $expected_alg = null) {
        $segments = explode('.', $this->raw);
        $signature_base_string = implode('.', array($segments[0], $segments[1]));
        if (!$expected_alg) {
            # NOTE: might better to warn here
            $expected_alg = $this->header['alg'];
        }
        switch ($expected_alg) {
            case 'HS256':
            case 'HS384':
            case 'HS512':
                return $this->signature === hash_hmac($this->digest(), $signature_base_string, $public_key_or_secret, true);
            case 'RS256':
            case 'RS384':
            case 'RS512':
                return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PKCS1)->verify($signature_base_string, $this->signature);
            case 'ES256':
            case 'ES384':
            case 'ES512':
                throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');
            case 'PS256':
            case 'PS384':
            case 'PS512':
                return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PSS)->verify($signature_base_string, $this->signature);
            default:
                throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');
        }
    }


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

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

        return $drop;
    }


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

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

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

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


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

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

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


    public function logout()
    {
        if ($this->Session->check('Auth.User')) {
            $this->__extralog("logout");
        }
        $this->Flash->info(__('Good-Bye'));
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $this->Auth->user('id')
            ),
            'recursive' => -1
        ));
        unset($user['User']['password']);
        $user['User']['action'] = 'logout';
        $this->User->save($user['User'], true, array('id'));
        $this->redirect($this->Auth->logout());
    }


    public function withUri(UriInterface $uri, $preserveHost = false)
    {
        if ($uri === $this->uri) {
            return $this;
        }

        $new = clone $this;
        $new->uri = $uri;

        if (!$preserveHost) {
            if ($host = $uri->getHost()) {
                $new->updateHostFromUri($host);
            }
        }

        return $new;
    }


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


function XMLRPCgetResourceGroupPrivs($name, $type, $nodeid){
    require_once(".ht-inc/privileges.php");
    global $user;

    if(! checkUserHasPriv("resourceGrant", $user['id'], $nodeid)){
        return array('status' => 'error',
                     'errorcode' => 53,
                     'errormsg' => 'Unable to add resource group to this node');
    }

    if($typeid = getResourceTypeID($type)){
        if(!checkForGroupName($name, 'resource', '', $typeid)){
            return array('status' => 'error',
                         'errorcode' => 28,
                         'errormsg' => 'resource group does not exist');
        }
        $nodePrivileges = getNodePrivileges($nodeid, 'resources');
        $nodePrivileges = getNodeCascadePrivileges($nodeid, 'resources', $nodePrivileges);
        foreach($nodePrivileges['resources'] as $resource => $privs){
            if(strstr($resource, "$type/$name")){
                return array(
                    'status' => 'success',
                    'privileges' => $privs);
            }
        }
        return array(
            'status' => 'error',
            'errorcode' => 29,
            'errormsg' => 'could not find resource name in privilege list');
    } else {
        return array('status' => 'error',
                     'errorcode' => 56,
                     'errormsg' => 'Invalid resource type');
    }
}


}elseif($p->status == 1){
                        $status = "id}&token=".TOKEN."\" class=\"label label-primary\">Active";
                    }


function phpAds_SessionDataFetch()
{
    global $session;
    $dal = new MAX_Dal_Admin_Session();

    // Guard clause: Can't fetch a session without an ID
	if (empty($_COOKIE['sessionID'])) {
        return;
    }

    $serialized_session = $dal->getSerializedSession($_COOKIE['sessionID']);

    // This is required because 'sessionID' cookie is set to new during logout.
    // According to comments in the file it is because some servers do not
    // support setting cookies during redirect.
    if (empty($serialized_session)) {
        return;
    }

    $loaded_session = unserialize($serialized_session);
	if (!$loaded_session) {
        // XXX: Consider raising an error
        return;
    }
	$session = $loaded_session;
    $dal->refreshSession($_COOKIE['sessionID']);
}


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

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


    public static function returnChildrenAsJSON() {
        global $db;

        //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));
        $id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        $nav        = $db->selectObjects('section', 'parent=' . $id, 'rank');
        //FIXME $manage_all is moot w/ cascading perms now?
        $manage_all = false;
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {
            $manage_all = true;
        }
        //FIXME recode to use foreach $key=>$value
        $navcount = count($nav);
        for ($i = 0; $i < $navcount; $i++) {
            if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {
                $nav[$i]->manage = 1;
                $view = true;
            } else {
                $nav[$i]->manage = 0;
                $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));
            }
            $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);
            if (!$view) unset($nav[$i]);
        }
        $nav= array_values($nav);
//        $nav[$navcount - 1]->last = true;
        if (count($nav)) $nav[count($nav) - 1]->last = true;
//        echo expJavascript::ajaxReply(201, '', $nav);
        $ar = new expAjaxReply(201, '', $nav);
        $ar->send();
    }


function db_case($array)
{
    global $DatabaseType;

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

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

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

            $counter++;
        }
    }

    return $string;
}


	function test_allowed_anon_comments() {
		add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );

		$comment_args = array(
			1,
			'',
			'',
			self::$post->ID,
			array(
				'author'       => 'WordPress',
				'author_email' => 'noreply@wordpress.org',
				'content'      => 'Test Anon Comments',
			),
		);

		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$this->assertNotIXRError( $result );
		$this->assertInternalType( 'int', $result );
	}


    public static function generatePass(){
        $vars = microtime().Site::$name.rand();
        $hash = sha1($vars.SECURITY_KEY);
        $pass = substr($hash, 5, 8);
        return $pass;
    }


		public function createBranch($name, $checkout = FALSE)
		{
			// git branch $name
			$this->run('branch', $name);

			if ($checkout) {
				$this->checkout($name);
			}

			return $this;
		}


function twig_array_filter(Environment $env, $array, $arrow)
{
    if (!twig_test_iterable($array)) {
        throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array)));
    }

    if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
        throw new RuntimeError('The callable passed to "filter" filter must be a Closure in sandbox mode.');
    }

    if (\is_array($array)) {
        return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH);
    }

    // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator
    return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow);
}


    private function generateTempFileData()
    {
        return [
            'name' => md5(mt_rand()),
            'tmp_name' => tempnam(sys_get_temp_dir(), ''),
            'type' => 'image/jpeg',
            'size' => mt_rand(1000, 10000),
            'error' => '0',
        ];
    }


        foreach ($this->_to_convert as $error) {

            $message = $this->getMessage($error['field'], $error['rule'], $error['fallback']);

            // If there is no generic `message()` set or the translated message is not equal to generic message
            // we can continue without worrying about duplications
            if ($this->_message === null || ($message != $this->_message && !in_array($message, $this->_errors))) {
                $this->_errors[] = $message;
                continue;
            }

            // If this new error is the generic message AND it has not already been added, add it
            if ($message == $this->_message && !in_array($this->_message, $this->_errors)) {
                $this->_errors[] = $this->_message;
            }
        }


            $loc = expCore::makeLocation('navigation', '', $standalone->id);
            if (expPermissions::check('manage', $loc)) return true;
        }
        return false;
    }


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


   static function cronCheckUpdate($task) {

      $result = Toolbox::checkNewVersionAvailable(1);
      $task->log($result);

      return 1;
   }


    public function getFlashCookieObject($name)
    {
        if (isset($_COOKIE[$name])) {
            $object = json_decode($_COOKIE[$name], false);
            setcookie($name, '', time() - 3600, '/');
            return $object;
        }

        return null;
    }


            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }


    public function subscriptions() {
        global $db;

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

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

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

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


				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques",
					"lang='" . $GLOBALS['spip_lang'] . "' AND id_parent=$id_parent");
				if ($row_rub) {
					$row['id_rubrique'] = $row_rub['id_rubrique'];
				}
			}
		}
	}

	return $row;
}


    public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment)
    {
        if (!$attachment->external) {
            $this->deleteFileInStorage($attachment);
        }

        $attachmentName = $uploadedFile->getClientOriginalName();
        $attachmentPath = $this->putFileInStorage($uploadedFile);

        $attachment->name = $attachmentName;
        $attachment->path = $attachmentPath;
        $attachment->external = false;
        $attachment->extension = $uploadedFile->getClientOriginalExtension();
        $attachment->save();

        return $attachment;
    }


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


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


    public function actionGetItems(){
        // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.
        $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';
        $command = Yii::app()->db->createCommand($sql);
        $qterm = $_GET['term'].'%';
        $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
        $result = $command->queryAll();
        echo CJSON::encode($result);
        exit;
    }


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

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

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


function db_case($array)
{
    global $DatabaseType;

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

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

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

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


    public function __construct() {
    }


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


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


$instance->schema = ${($_ = isset($this->services['App\Schema']) ? $this->services['App\Schema'] : $this->getSchemaService()) && false ?: '_'};


    function remove() {
        global $db;

        $section = $db->selectObject('section', 'id=' . $this->params['id']);
        if ($section) {
            section::removeLevel($section->id);
            $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);
            $section->parent = -1;
            $db->updateObject($section, 'section');
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_authorized();
        }
    }


    public function pending() {
//        global $db;

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

        // find the subscriber and their pending subscriptions
        $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);
        $subscriber = new subscribers($this->params['id']);

        // render the template
        assign_to_template(array(
            'subscriber'=>$subscriber,
            'ealerts'=>$ealerts
        ));
    }


function VerifyBlockedSchedule($columns,$course_period_id,$sec,$edit=false)
{
    if($course_period_id!='new')
    {
    $cp_det_RET=  DBGet(DBQuery("SELECT * FROM course_periods WHERE course_period_id=$course_period_id"));

        $cp_det_RET=$cp_det_RET[1];
        $teacher=$cp_det_RET['TEACHER_ID'];
        $secteacher=$cp_det_RET['SECONDARY_TEACHER_ID'];
         $all_teacher=$teacher.($secteacher!=''?$secteacher:'');
    }


public function anyData()
    {
        $tasks = Task::with(['user', 'status', 'client'])->select(
            collect(['external_id', 'title', 'created_at', 'deadline', 'user_assigned_id', 'status_id', 'client_id'])
                ->map(function ($field) {
                    return (new Task())->qualifyColumn($field);
                })
                ->all()
        );

        return Datatables::of($tasks)
            ->addColumn('titlelink', '{{$title}}')
            ->editColumn('client', function ($projects) {
                return $projects->client->company_name;
            })
            ->editColumn('created_at', function ($tasks) {
                return $tasks->created_at ? with(new Carbon($tasks->created_at))
                    ->format(carbonDate()) : '';
            })
            ->editColumn('deadline', function ($tasks) {
                return $tasks->created_at ? with(new Carbon($tasks->deadline))
                    ->format(carbonDate()) : '';
            })
            ->editColumn('user_assigned_id', function ($tasks) {
                return $tasks->user->name;
            })
            ->editColumn('status_id', function ($tasks) {
                return 'status->color . '"> ' .
                    $tasks->status->title . '';
            })
            ->addColumn('view', function ($tasks) {
                return 'external_id) . '" class="btn btn-link">' . __('View') .''
                . 'external_id) . '" data-title="'. $tasks->title . '" data-target="#deletion" class="btn btn-link">' . __('Delete') .''
                ;
            })
            ->rawColumns(['titlelink','view', 'status_id'])
            ->make(true);
    }


    public static function install ($var) {
        include(GX_PATH.'/gxadmin/themes/install/'.$var.'.php');
    }


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

        $params = isset($this->params['id']) ? $this->params['id'] : $this->params;
        $record = new option_master($params);
        assign_to_template(array(
            'record'=>$record
        ));
    }


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

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

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

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


function new_pass_form()
{
    pagetop(gTxt('tab_site_admin'), '');

    echo form(
        hed(gTxt('change_password'), 2).
        inputLabel(
            'new_pass',
            fInput('password', 'new_pass', '', '', '', '', INPUT_REGULAR, '', 'new_pass'),
            'new_password', '', array('class' => 'txp-form-field edit-admin-new-password')
        ).
        graf(
            checkbox('mail_password', '1', true, '', 'mail_password').
            n.tag(gTxt('mail_it'), 'label', array('for' => 'mail_password')), array('class' => 'edit-admin-mail-password')).
        graf(fInput('submit', 'change_pass', gTxt('submit'), 'publish')).
        eInput('admin').
        sInput('change_pass'),
    '', '', 'post', 'txp-edit', '', 'change_password');
}


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


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


	private function _notlinksto( $option ) {
		if ( $this->parameters->getParameter( 'distinct' ) == 'strict' ) {
			$this->addGroupBy( 'page_title' );
		}
		if ( count( $option ) ) {
			$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['pagelinks'] . '.pl_from FROM ' . $this->tableNames['pagelinks'] . ' WHERE ';
			$ors = [];
			foreach ( $option as $linkGroup ) {
				foreach ( $linkGroup as $link ) {
					$_or = '(' . $this->tableNames['pagelinks'] . '.pl_namespace=' . intval( $link->getNamespace() );
					if ( strpos( $link->getDbKey(), '%' ) >= 0 ) {
						$operator = 'LIKE';
					} else {
						$operator = '=';
					}
					if ( $this->parameters->getParameter( 'ignorecase' ) ) {
						$_or .= ' AND LOWER(CAST(' . $this->tableNames['pagelinks'] . '.pl_title AS char)) ' . $operator . ' LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';
					} else {
						$_or .= ' AND ' . $this->tableNames['pagelinks'] . '.pl_title ' . $operator . ' ' . $this->DB->addQuotes( $link->getDbKey() ) . ')';
					}
					$ors[] = $_or;
				}
			}
			$where .= '(' . implode( ' OR ', $ors ) . '))';
		}
		$this->addWhere( $where );
	}


	public static function getStylesheet($styleName)
	{
		// Get custom stylesheet, of the default stylesheet if the custom stylesheet does not exist
		$stylesheet = get_option($styleName, '');

		if (strlen($stylesheet) <= 0)
		{
			$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . $styleName . '.css';

			if (!file_exists($stylesheetFile))
			{
				$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . 'style-light.css';
			}

			// Get contents of stylesheet
			ob_start();
			include($stylesheetFile);
			$stylesheet .= ob_get_clean();
		}

		// Replace the URL placeholders with actual URLs and add a unique identifier to separate stylesheets
		$stylesheet = str_replace('%plugin-url%', SlideshowPluginMain::getPluginUrl(), $stylesheet);
		$stylesheet = str_replace('%site-url%', get_bloginfo('url'), $stylesheet);
		$stylesheet = str_replace('%stylesheet-url%', get_stylesheet_directory_uri(), $stylesheet);
		$stylesheet = str_replace('%template-url%', get_template_directory_uri(), $stylesheet);
		$stylesheet = str_replace('.slideshow_container', '.slideshow_container_' . $styleName, $stylesheet);

		return $stylesheet;
	}


    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 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 testSetSaveHandler54()
    {
        $this->iniSet('session.save_handler', 'files');
        $storage = $this->getStorage();
        $storage->setSaveHandler();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(null);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NullSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
    }


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

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


    public function actionGetItems(){
        $sql =
            'SELECT id, name as value
            FROM x2_templates
            WHERE name
            LIKE :qterm
            ORDER BY name ASC';

        $command = Yii::app()->db->createCommand($sql);
        $qterm = $_GET['term'].'%';
        $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
        $result = $command->queryAll();
        echo CJSON::encode($result); exit;
    }


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


  private function checkResponse ($string) {
    if (substr($string, 0, 3) !== '+OK') {
      $this->error = array(
        'error' => "Server reported an error: $string",
        'errno' => 0,
        'errstr' => ''
      );

      if ($this->do_debug >= 1) {
        $this->displayErrors();
      }

      return false;
    } else {
      return true;
    }

  }


	public function delete() {
	    global $user;

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


    function insertObject($object, $table) {
        //if ($table=="text") eDebug($object,true);
        $sql = "INSERT INTO `" . $this->prefix . "$table` (";
        $values = ") VALUES (";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            if ($var{0} != '_') {
                $sql .= "`$var`,";
                if ($values != ") VALUES (") {
                    $values .= ",";
                }
                $values .= "'" . $this->escapeString($val) . "'";
            }
        }
        $sql = substr($sql, 0, -1) . substr($values, 0) . ")";
        //if($table=='text')eDebug($sql,true);
        if (@mysqli_query($this->connection, $sql) != false) {
            $id = mysqli_insert_id($this->connection);
            return $id;
        } else
            return 0;
    }


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


	protected function fsock_get_contents( &$url, $timeout, $redirect_max, $ua, $outfp ) {

		$connect_timeout = 3;
		$connect_try = 3;
		$method = 'GET';
		$readsize = 4096;

		$getSize = null;
		$headers = '';

		$arr = parse_url($url);
		if (!$arr){
			// Bad request
			return false;
		}

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

		$url_base = $arr['scheme'].'://'.$arr['host'].':'.$arr['port'];
		$url_path = isset($arr['path']) ? $arr['path'] : '/';
		$uri = $url_path.$arr['query'];

		$query = $method.' '.$uri." HTTP/1.0\r\n";
		$query .= "Host: ".$arr['host']."\r\n";
		if (!empty($ua)) $query .= "User-Agent: ".$ua."\r\n";
		if (!is_null($getSize)) $query .= 'Range: bytes=0-' . ($getSize - 1) . "\r\n";


    private function updateModificationDate()
    {
        try {
            $modif_date = date('Y-m-d');
            $update = $this->zdb->update(self::TABLE);
            $update->set(
                array('date_modif_adh' => $modif_date)
            )->where(self::PK . '=' . $this->_id);

            $edit = $this->zdb->execute($update);
            $this->_modification_date = $modif_date;
        } catch (Throwable $e) {
            Analog::log(
                'Something went wrong updating modif date :\'( | ' .
                $e->getMessage() . "\n" . $e->getTraceAsString(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    static function author() {
        return "Dave Leffler";
    }


	protected function parseRaw($raw, $base, $nameOnly = false) {
		$info = preg_split("/\s+/", $raw, 9);
		$stat = array();

		if (!isset($this->ftpOsUnix)) {
			$this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
		}
		if (!$this->ftpOsUnix) {
			$info = $this->normalizeRawWindows($raw);
		}

		if (count($info) < 9 || $info[8] == '.' || $info[8] == '..') {
			return false;
		}

		$name = $info[8];

		if (preg_match('|(.+)\-\>(.+)|', $name, $m)) {
			$name   = trim($m[1]);
			// check recursive processing
			if ($this->cacheDirTarget && $this->_joinPath($base, $name) !== $this->cacheDirTarget) {
				return array();
			}
			if (!$nameOnly) {
				$target = trim($m[2]);
				if (substr($target, 0, 1) !== $this->separator) {
					$target = $this->getFullPath($target, $base);
				}
				$target = $this->_normpath($target);
				$stat['name']   = $name;
				$stat['target'] = $target;
				return $stat;
			}
		}

		if ($nameOnly) {
			return array('name' => $name);
		}

		if (is_numeric($info[5]) && !$info[6] && !$info[7]) {
			// by normalizeRawWindows()
			$stat['ts'] = $info[5];
		} else {
			$stat['ts'] = strtotime($info[5].' '.$info[6].' '.$info[7]);
			if (empty($stat['ts'])) {
				$stat['ts'] = strtotime($info[6].' '.$info[5].' '.$info[7]);
			}
		}

		$stat['owner'] = '';
		if ($this->options['statOwner']) {
			$stat['owner'] = $info[2];
			$stat['group'] = $info[3];
			$stat['perm']  = substr($info[0], 1);
			$stat['isowner'] = $stat['owner']? ($stat['owner'] == $this->options['user']) : $this->options['owner'];
		}

		$perm = $this->parsePermissions($info[0], $stat['owner']);
		$stat['name']  = $name;
		$stat['mime']  = substr(strtolower($info[0]), 0, 1) == 'd' ? 'directory' : $this->mimetype($stat['name']);
		$stat['size']  = $stat['mime'] == 'directory' ? 0 : $info[4];
		$stat['read']  = $perm['read'];
		$stat['write'] = $perm['write'];

		return $stat;
	}


    public static function incFunc($var) {
        if (self::functionExist($var)) {
            include(GX_THEME.$var.'/function.php');
        }

    }


	protected function getItemsInHand($hashes, $dir = null) {
		static $totalSize = 0;
		if (is_null($dir)) {
			$totalSize = 0;
			if (! $tmpDir = $this->getTempPath()) {
				return false;
			}
			$dir = tempnam($tmpDir, 'elf');
			if (!unlink($dir) || !mkdir($dir, 0700, true)) {
				return false;
			}
			register_shutdown_function(array($this, 'rmdirRecursive'), $dir);
		}
		$res = true;
		$files = array();
		foreach ($hashes as $hash) {
			if (($file = $this->file($hash)) == false) {
				continue;
			}
			if (!$file['read']) {
				continue;
			}

			$name = $file['name'];
			// for call from search results
			if (isset($files[$name])) {
				$name = preg_replace('/^(.*?)(\..*)?$/', '$1_'.$files[$name]++.'$2', $name);
			} else {
				$files[$name] = 1;
			}
			$target = $dir.DIRECTORY_SEPARATOR.$name;

			if ($file['mime'] === 'directory') {
				$chashes = array();
				$_files = $this->scandir($hash);
				foreach($_files as $_file) {
					if ($file['read']) {
						$chashes[] = $_file['hash'];
					}
				}
				if ($chashes) {
					mkdir($target, 0700, true);
					$res = $this->getItemsInHand($chashes, $target);
				}
				if (!$res) {
					break;
				}
				!empty($file['ts']) && @touch($target, $file['ts']);
			} else {
				$path = $this->decode($hash);
				if ($fp = $this->fopenCE($path)) {
					if ($tfp = fopen($target, 'wb')) {
						$totalSize += stream_copy_to_stream($fp, $tfp);
						fclose($tfp);
					}
					!empty($file['ts']) && @touch($target, $file['ts']);
					$this->fcloseCE($fp, $path);
				}
				if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $totalSize) {
					$res = $this->setError(elFinder::ERROR_ARC_MAXSIZE);
				}
			}
		}
		return $res? $dir : false;
	}


    public function destroy(PaymentMethod $paymentMethod)
    {
        $this->authorize('delete', $paymentMethod);

        $payments = $paymentMethod->payments;

        if ($payments->count() > 0) {
            return respondJson('payments_attached', 'Payments Attached.');
        }

        $paymentMethod->delete();

        return response()->json([
            'success' => 'Payment method deleted successfully',
        ]);
    }


$this->headers = ['host' => [$host]] + $this->headers;


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

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

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


function draw_cdef_preview($cdef_id) {
	?>

cdef=<?php print get_cdef($cdef_id, true);?>

	<?php
}


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

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

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

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

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

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

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


    public function actionEditDropdown() {
        $model = new Dropdowns;

        if (isset($_POST['Dropdowns'])) {
            $model = Dropdowns::model()->findByPk(
                    $_POST['Dropdowns']['id']);
            if ($model->id == Actions::COLORS_DROPDOWN_ID) {
                if (AuxLib::issetIsArray($_POST['Dropdowns']['values']) &&
                        AuxLib::issetIsArray($_POST['Dropdowns']['labels']) &&
                        count($_POST['Dropdowns']['values']) ===
                        count($_POST['Dropdowns']['labels'])) {

                    if (AuxLib::issetIsArray($_POST['Admin']) &&
                            isset($_POST['Admin']['enableColorDropdownLegend'])) {

                        Yii::app()->settings->enableColorDropdownLegend =
                            $_POST['Admin']['enableColorDropdownLegend'];
                        Yii::app()->settings->save();
                    }

                    $options = array_combine(
                            $_POST['Dropdowns']['values'], $_POST['Dropdowns']['labels']);
                    $temp = array();
                    foreach ($options as $value => $label) {
                        if ($value != "")
                            $temp[$value] = $label;
                    }
                    $model->options = json_encode($temp);
                    $model->save();
                }
            } else {
                $model->attributes = $_POST['Dropdowns'];
                $temp = array();
                if (is_array($model->options) && count($model->options) > 0) {
                    foreach ($model->options as $option) {
                        if ($option != "")
                            $temp[$option] = $option;
                    }
                    $model->options = json_encode($temp);
                    if ($model->save()) {

                    }
                }
            }
        }
        $this->redirect(
                'manageDropDowns'
        );
    }


function VerifyFixedSchedule($columns,$columns_var,$update=false)
{

    $qr_teachers=  DBGet(DBQuery('select TEACHER_ID,SECONDARY_TEACHER_ID from course_periods where course_period_id=\''.$_REQUEST['course_period_id'].'\''));
    $teacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']:$qr_teachers[1]['TEACHER_ID']);
    $secteacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']:$qr_teachers[1]['SECONDARY_TEACHER_ID']);
//    $secteacher=$qr_teachers[1]['SECONDARY_TEACHER_ID'];

    if($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!='')
     $all_teacher=$teacher.($secteacher!=''?','.$secteacher:'');


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

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

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

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


public function display_sdm_stats_meta_box($post) {  //Stats metabox
	$old_count = get_post_meta($post->ID, 'sdm_count_offset', true);
	$value = isset($old_count) && $old_count != '' ? $old_count : '0';

	// Get checkbox for "disable download logging"
	$no_logs = get_post_meta($post->ID, 'sdm_item_no_log', true);
	$checked = isset($no_logs) && $no_logs === 'on' ? 'checked="checked"' : '';

	_e('These are the statistics for this download item.', 'simple-download-monitor');
	echo '

';

	global $wpdb;
	$wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'sdm_downloads WHERE post_id=%s', $post->ID));

	echo '
';
	_e('Number of Downloads:', 'simple-download-monitor');
	echo ' ' . $wpdb->num_rows . '';
	echo '
';

	echo '
';
	_e('Offset Count: ', 'simple-download-monitor');
	echo '
';
	echo ' <input type="text" size="10" name="sdm_count_offset" value="' . $value . '" />';
	echo '
' . __('Enter any positive or negative numerical value; to offset the download count shown to the visitors (when using the download counter shortcode).', 'simple-download-monitor') . '
';
	echo '
';

	echo '
';
	echo '
';
	echo '<input type="checkbox" name="sdm_item_no_log" ' . $checked . ' />';
	echo '';
	_e('Disable download logging for this item.', 'simple-download-monitor');
	echo '
';

	wp_nonce_field('sdm_count_offset_nonce', 'sdm_count_offset_nonce_check');
    }


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

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

        return $category;
    }


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


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

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


	function test_anon_comments_require_email() {
		add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );

		$comment_args = array(
			1,
			'',
			'',
			self::$post->ID,
			array(
				'author'       => 'WordPress',
				'author_email' => 'noreply at wordpress.org',
				'content'      => 'Test Anon Comments',
			),
		);

		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$this->assertIXRError( $result );
		$this->assertSame( 403, $result->code );
	}


function parse_request($message)
{
    $data = _parse_message($message);
    $matches = [];
    if (!preg_match('/^[a-zA-Z]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
        throw new \InvalidArgumentException('Invalid request string');
    }
    $parts = explode(' ', $data['start-line'], 3);
    $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';

    $request = new Request(
        $parts[0],
        $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],
        $data['headers'],
        $data['body'],
        $version
    );

    return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
}


    public function save() {
        $data = $_POST['file'];

        // security (remove all ..)
        $data['name'] = str_replace('..', '', $data['name']);
        $file = FILES_DIR . DS . $data['name'];

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

        if (file_exists($file)) {
            if (file_put_contents($file, $data['content']) !== false) {
                Flash::set('success', __('File has been saved with success!'));
            } else {
                Flash::set('error', __('File is not writable! File has not been saved!'));
            }
        } else {
            if (file_put_contents($file, $data['content'])) {
                Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));
            } else {
                Flash::set('error', __('Directory is not writable! File has not been saved!'));
            }
        }

        // save and quit or save and continue editing ?
        if (isset($_POST['commit'])) {
            redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));
        } else {
            redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));
        }


    protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 20) {
            $this->maxLength = 20;
        }
        $length = mt_rand($this->minLength, $this->maxLength);

        $letters = 'bcdfghjklmnpqrstvwxyz';
        $vowels = 'aeiou';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
                $code .= $vowels[mt_rand(0, 4)];
            } else {
                $code .= $letters[mt_rand(0, 20)];
            }
        }

        return $code;
    }


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

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


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


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


            $db->insertObject($obj, 'expeAlerts_subscribers');
        }

        $count = count($this->params['ealerts']);

        if ($count > 0) {
            flash('message', gt("Your subscriptions have been updated.  You are now subscriber to")." ".$count.' '.gt('E-Alerts.'));
        } else {
            flash('error', gt("You have been unsubscribed from all E-Alerts."));
        }

        expHistory::back();
    }


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


    protected function _tempdir($dir, $prefix = '', $mode = 0700)
    {
        if (substr($dir, -1) != DIRECTORY_SEPARATOR) {
            $dir .= DIRECTORY_SEPARATOR;
        }

        do {
            $path = $dir.$prefix.mt_rand(0, 9999999);
        } while (!mkdir($path, $mode));

        return $path;
    }


function mci_account_get_array_by_id( $p_user_id ) {
	$t_result = array();
	$t_result['id'] = $p_user_id;

	if( user_exists( $p_user_id ) ) {
		$t_result['name'] = user_get_field( $p_user_id, 'username' );
		$t_dummy = user_get_field( $p_user_id, 'realname' );

		if( !empty( $t_dummy ) ) {
			$t_result['real_name'] = $t_dummy;
		}

		$t_dummy = user_get_field( $p_user_id, 'email' );

		if( !empty( $t_dummy ) ) {
			$t_result['email'] = $t_dummy;
		}
	}
	return $t_result;
}


    public function dispatch($messages, $final)
    {
        $targetErrors = [];
        foreach ($this->targets as $target) {
            if ($target->enabled) {
                try {
                    $target->collect($messages, $final);
                } catch (\Exception $e) {
                    $target->enabled = false;
                    $targetErrors[] = [
                        'Unable to send log via ' . get_class($target) . ': ' . ErrorHandler::convertExceptionToString($e),
                        Logger::LEVEL_WARNING,
                        __METHOD__,
                        microtime(true),
                        [],
                    ];
                }
            }
        }

        if (!empty($targetErrors)) {
            $this->dispatch($targetErrors, true);
        }
    }


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

        $out = array();

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

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

        return $out;
    }