    public function testConfigurationCookieCreate()
    {
        $_SERVER['REQUEST_METHOD'] = 'GET';

        $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
        $controller->request = new Request(['webroot' => '/dir/']);
        $controller->response = new Response();

        $component = new CsrfComponent($this->registry, [
            'cookieName' => 'token',
            'expiry' => '+1 hour',
            'secure' => true,
            'httpOnly' => true
        ]);

        $event = new Event('Controller.startup', $controller);
        $component->startup($event);

        $this->assertEmpty($controller->response->cookie('csrfToken'));
        $cookie = $controller->response->cookie('token');
        $this->assertNotEmpty($cookie, 'Should set a token.');
        $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
        $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');
        $this->assertEquals('/dir/', $cookie['path'], 'session path.');
        $this->assertTrue($cookie['secure'], 'cookie security flag missing');
        $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');
    }


public function html() {
		switch( $this->type ) {
			case FILE_ADDED:
				$t_string = 'timeline_issue_file_added';
				break;
			case FILE_DELETED:
				$t_string = 'timeline_issue_file_deleted';
				break;
			default:
				throw new ServiceException( 'Unknown Event Type', ERROR_GENERIC );
		}

		$t_bug_link = string_get_bug_view_link( $this->issue_id );

		$t_html = $this->html_start( 'fa-file-o' );
		$t_html .= '
'
			. sprintf( lang_get( $t_string ),
				prepare_user_name( $this->user_id ),
				$t_bug_link,
				$this->filename
			)
			. '
';
		$t_html .= $this->html_end();

		return $t_html;
	}


    private function _includeFiles($files)
    {
        $dynamic_scripts = "";
        $scripts = array();
        foreach ($files as $value) {
            if (strpos($value['filename'], "?") !== false) {
                $dynamic_scripts .= "<script type='text/javascript' src='js/"
                    . $value['filename'] . "'></script>";
                continue;
            }
            $include = true;
            if ($value['conditional_ie'] !== false
                && PMA_USR_BROWSER_AGENT === 'IE'
            ) {
                if ($value['conditional_ie'] === true) {
                    $include = true;
                } else if ($value['conditional_ie'] == PMA_USR_BROWSER_VER) {
                    $include = true;
                } else {
                    $include = false;
                }
            }
            if ($include) {
                $scripts[] = "scripts[]=" . $value['filename'];
            }
        }
        $separator = PMA_URL_getArgSeparator();
        $url = 'js/get_scripts.js.php'
            . PMA_URL_getCommon(array(), 'none')
            . $separator . implode($separator, $scripts);

        $static_scripts = sprintf(
            '<script type="text/javascript" src="%s"></script>',
            htmlspecialchars($url)
        );
        return $static_scripts . $dynamic_scripts;
    }


    public function testAuthHeader()
    {
        $restoreInstance = PMA\libraries\Response::getInstance();

        $mockResponse = $this->getMockBuilder('PMA\libraries\Response')
            ->disableOriginalConstructor()
            ->setMethods(array('isAjax', 'headersSent', 'header'))
            ->getMock();

        $mockResponse->expects($this->once())
            ->method('isAjax')
            ->with()
            ->will($this->returnValue(false));

        $mockResponse->expects($this->any())
            ->method('headersSent')
            ->with()
            ->will($this->returnValue(false));

        $mockResponse->expects($this->once())
            ->method('header')
            ->with('Location: http://www.phpmyadmin.net/logout' . ((SID) ? '?' . SID : ''));


function PMA_findExistingColNames($db, $cols, $allFields=false)
{
    $cfgCentralColumns = PMA_centralColumnsGetParams();
    if (empty($cfgCentralColumns)) {
        return array();
    }
    $pmadb = $cfgCentralColumns['db'];
    $GLOBALS['dbi']->selectDb($pmadb, $GLOBALS['controllink']);
    $central_list_table = $cfgCentralColumns['table'];
    if ($allFields) {
        $query = 'SELECT * FROM ' . Util::backquote($central_list_table) . ' '
            . 'WHERE db_name = \'' . $db . '\' AND col_name IN (' . $cols . ');';
        $has_list = (array) $GLOBALS['dbi']->fetchResult(
            $query, null, null, $GLOBALS['controllink']
        );
        PMA_handleColumnExtra($has_list);
    } else {
        $query = 'SELECT col_name FROM '
            . Util::backquote($central_list_table) . ' '
            . 'WHERE db_name = \'' . $db . '\' AND col_name IN (' . $cols . ');';
        $has_list = (array) $GLOBALS['dbi']->fetchResult(
            $query, null, null, $GLOBALS['controllink']
        );
    }

    return $has_list;
}


    public function render($ignoreCli = false)
    {
        if (!$ignoreCli && php_sapi_name() == 'cli') {
            $this->log();
            file_put_contents('php://stderr', $this->getException()->__toString()."\n");
            exit(1);
        }

        $view = Kwf_Debug::getView();
        $view->exception = $this->getException();
        $view->message = $this->getException()->getMessage();
        $view->requestUri = isset($_SERVER['REQUEST_URI']) ?
            $_SERVER['REQUEST_URI'] : '' ;
        $view->debug = Kwf_Exception::isDebug();
        $header = $this->getHeader();
        $template = $this->getTemplate();
        $template = strtolower(Zend_Filter::filterStatic($template, 'Word_CamelCaseToDash').'.tpl');
        $this->log();

        if (!headers_sent()) {
            header($header);
            header('Content-Type: text/html; charset=utf-8');
        }

        try {
            echo $view->render($template);
        } catch (Exception $e) {
            echo '<pre>';
            echo $this->__toString();
            echo "\n\n\nError happened while handling exception:";
            echo $e->__toString();
            echo '</pre>';
        }
        Kwf_Benchmark::shutDown();
        Kwf_Benchmark::output();
   }


	function updateCommandCategorieInDB(){
		global $pearDB;

		$DBRESULT = $pearDB->query("UPDATE `command_categories` SET `category_name` = '".$_POST["category_name"]."' , `category_alias` = '".$_POST["category_alias"]."' , `category_order` = '".$_POST["category_order"]."' WHERE `cmd_category_id` = '".$_POST["cmd_category_id"]."'");
	}


	function testCommandCategorieExistence ($name = NULL)	{
		global $pearDB, $form;
		$id = NULL;

		if (isset($form))
			$id = $form->getSubmitValue('cmd_category_id');

		$DBRESULT = $pearDB->query("SELECT `category_name`, `cmd_category_id` FROM `command_categories` WHERE `category_name` = '".htmlentities($name, ENT_QUOTES, "UTF-8")."'");
		$cat = $DBRESULT->fetchRow();

		if ($DBRESULT->numRows() >= 1 && $cat["cmd_category_id"] == $id)
			return true;
		else if ($DBRESULT->numRows() >= 1 && $cat["cmd_category_id"] != $id)
			return false;
		else
			return true;
	}


function getTypes($subtype="both") {
	$types = array("users" => array(),
	               "resources" => array());
	if($subtype == "users" || $subtype == "both") {
		$query = "SELECT id, name FROM userprivtype";
		$qh = doQuery($query, 365);
		while($row = mysql_fetch_assoc($qh)) {
			if($row["name"] == "block" || $row["name"] == "cascade")
				continue;
			$types["users"][$row["id"]] = $row["name"];
		}
	}
	if($subtype == "resources" || $subtype == "both") {
		$query = "SELECT id, name FROM resourcetype";
		$qh = doQuery($query, 366);
		while($row = mysql_fetch_assoc($qh)) {
			if($row["name"] == "block" || $row["name"] == "cascade")
				continue;
			$types["resources"][$row["id"]] = $row["name"];
		}
	}
	return $types;
}


function XMLRPCtest($string) {
	$string = processInputData($string, ARG_STRING);
	return array('status' => 'success',
	             'message' => 'RPC call worked successfully',
	             'string' => $string);
}


function XMLRPCblockAllocation($imageid, $start, $end, $numMachines,
                               $usergroupid, $ignoreprivileges=0) {
	global $user, $xmlrpcBlockAPIUsers;
	if(! in_array($user['id'], $xmlrpcBlockAPIUsers)) {
		return array('status' => 'error',
		             'errorcode' => 34,
		             'errormsg' => 'access denied for managing block allocations');
	}
	$ownerid = getUserlistID('vclreload@Local');
	$name = "API:$start";
	$managementnodes = getManagementNodes('future');
	if(empty($managementnodes)) {
		return array('status' => 'error',
		             'errorcode' => 12,
		             'errormsg' => 'could not allocate a management node to handle block allocation');
	}
	$mnid = array_rand($managementnodes);
	$query = "INSERT INTO blockRequest "
	       .        "(name, "
	       .        "imageid, "
	       .        "numMachines, "
	       .        "groupid, "
	       .        "repeating, "
	       .        "ownerid, "
	       .        "admingroupid, "
	       .        "managementnodeid, "
	       .        "expireTime, "
	       .        "status) "
	       . "VALUES "
	       .        "('$name', "
	       .        "$imageid, "
	       .        "$numMachines, "
	       .        "$usergroupid, "
	       .        "'list', "
	       .        "$ownerid, "
	       .        "0, "
	       .        "$mnid, "
	       .        "'$end', "
	       .        "'accepted')";
	doQuery($query, 101);
	$brid = dbLastInsertID();
	$query = "INSERT INTO blockTimes "
	       .        "(blockRequestid, "
	       .        "start, "
	       .        "end) "
	       . "VALUES "
	       .        "($brid, "
	       .        "'$start', "
	       .        "'$end')";
	doQuery($query, 101);
	$btid = dbLastInsertID();
	$return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);
	$return['blockTimesid'] = $btid;
	return $return;
}


function XMLRPCendRequest($requestid) {
	global $user;
	$requestid = processInputData($requestid, ARG_NUMERIC);
	$userRequests = getUserRequests('all', $user['id']);
	$found = 0;
	foreach($userRequests as $req) {
		if($req['id'] == $requestid) {
			$request = getRequestInfo($requestid);
			$found = 1;
			break;
		}
	}
	if(! $found)
		return array('status' => 'error',
		             'errorcode' => 1,
		             'errormsg' => 'unknown requestid');

	deleteRequest($request);
	return array('status' => 'success');
}


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

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


	private function _finishUp($callFrom = '') {

        $this->logger->setLogInfo('Call from: ' . $callFrom);

		if (function_exists('mw_post_update')) {
			mw_post_update();
		}

        $this->logger->setLogInfo('Cleaning up system cache');

		mw()->cache_manager->clear();

        $zipReader = new ZipReader();
        $zipReader->clearCache();

        $this->logger->setLogInfo('Done!');
	}


function test1Controller($hphpdOutput, $hphpdProcessId, $serverPort) {
  // Request a page so that the client can debug it.
  waitForClientToOutput($hphpdOutput, "Waiting for server response");
  $url = "http://".php_uname('n').':'.$serverPort.'/test1.php';
  echo "Requesting test1.php\n";
  request(php_uname('n'), $serverPort, 'test1.php', 10); // ignore response

  // Let client run until script quits
  waitForClientToOutput($hphpdOutput, "quit");
}


                    $chrootPath = realpath($chrootPath);
                    if ($chrootPath !== false && strpos($realfile, $chrootPath) === 0) {
                        $chrootValid = true;
                        break;
                    }
                }
                if ($chrootValid !== true) {
                    Helpers::record_warnings(E_USER_WARNING, "Permission denied on $remoteFile. The file could not be found under the paths specified by Options::chroot.", __FILE__, __LINE__);
                    return false;
                }
            }

            if (!$realfile) {
                Helpers::record_warnings(E_USER_WARNING, "File '$realfile' not found.", __FILE__, __LINE__);
                return false;
            }

            $remoteFile = $realfile;
        }
        list($remoteFileContent, $http_response_header) = @Helpers::getFileContent($remoteFile, $context);
        if ($remoteFileContent === null) {
            return false;
        }

        $localTempFile = @tempnam($this->options->get("tempDir"), "dompdf-font-");
        file_put_contents($localTempFile, $remoteFileContent);

        $font = Font::load($localTempFile);

        if (!$font) {
            unlink($localTempFile);
            return false;
        }

        $font->parse();
        $font->saveAdobeFontMetrics("$localFilePath.ufm");
        $font->close();

        unlink($localTempFile);

        if ( !file_exists("$localFilePath.ufm") ) {
            return false;
        }

        $fontExtension = ".ttf";
        switch ($font->getFontType()) {
            case "TrueType":
            default:
                $fontExtension = ".ttf";
                break;
        }

        // Save the changes
        file_put_contents($localFilePath.$fontExtension, $remoteFileContent);

        if ( !file_exists($localFilePath.$fontExtension) ) {
            unlink("$localFilePath.ufm");
            return false;
        }

        $this->setFontFamily($fontname, $entry);

        return true;
    }


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


		public function init()
		{

			if(!e_QUERY)
			{
				e107::getPlug()->clearCache();
			}

			if($this->getMode()=== 'avail')
			{
				$this->listQry  = "SELECT * FROM `#plugin` WHERE plugin_installflag = 0 AND plugin_category != 'menu'  ";
			}

			// Set drop-down values (if any).

		}


function _getEntityString($entityIds)
{
    $entity = '';
    if (!empty($entityIds)) {
        $entityArr = array();
        foreach ($entityIds as $entityId => $entityValue) {
            $entityArr[] = "$entityId=$entityValue";
        }
        $entity = implode('&',$entityArr) . '&';
    }

    return $entity;
}


public function notify_edge_mode() {
        w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/ui.php');
        w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/admin_ui.php');
        $message = sprintf(__('
You can now keep W3 Total Cache up-to-date without having to worry about new features breaking your website. There will be more releases with bug fixes, security fixes and settings updates.

Also, you can now try out our new features as soon as they\'re ready. %s to enable "edge mode" and unlock pre-release features. %s
', 'w3-total-cache')
            ,'_page .'&w3tc_edge_mode_enable').'" class="button">' . __('Click Here', 'w3-total-cache') . ''
            , w3_button_hide_note(__('Hide this message', 'w3-total-cache'), 'edge_mode', '', true,'','w3tc_default_hide_note_custom')
        );
        w3_e_notification_box($message, 'edge-mode');
    }


    function load() {
        w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/admin.php');
        $this->_page = w3tc_get_current_page();

        /**
         * Run plugin action
         */
        $action = false;

        foreach ($_REQUEST as $key => $value) {
            if (strpos($key, 'w3tc_') === 0) {
                $action = 'action_' . substr($key, 5);
                break;
            }
        }
        $flush = false;
        $cdn = false;
        $support = false;
        $action_handler = w3_instance('W3_AdminActions_ActionHandler');
        $action_handler->set_default($this);
        $action_handler->set_current_page($this->_page);
        if ($action && $action_handler->exists($action)) {
            if (strpos($action, 'view') !== false)
                if (!wp_verify_nonce(W3_Request::get_string('_wpnonce'), 'w3tc'))
                    wp_nonce_ays('w3tc');
            else
                check_admin_referer('w3tc');

            try {
                $action_handler->execute($action);
            } catch (Exception $e) {
                w3_admin_redirect_with_custom_messages(array(), array($e->getMessage()));
            }

            exit();
        }
    }


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


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


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


    public function __construct () {

    }


            $vars = self::$mysqli->escape_string($vars);
        }else{
            $vars = $vars;
        }
        return $vars;
    }


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

        return $html;
    }


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


}elseif($vars['paging'] < $limit  || $vars['paging'] = $limit ){
                    $prev = ($vars['paging'])-1;
                    if($smart == true){
                    $url = $vars['url']."/paging/".$prev;
                    }else{
                        $url = $vars['url']."&paging=".$prev;
                    }
                    $r .= "
Previous
";
                }


    public function __construct() {
    }


    public static function insert($vars) {
        if(is_array($vars)) {
            $slug = Typo::slugify($vars['title']);
            $vars = array_merge($vars, array('slug' => $slug));
            //print_r($vars);
            $ins = array(
                        'table' => 'posts',
                        'key' => $vars
                    );
            $post = Db::insert($ins);
            self::$last_id = Db::$last_id;
            Hooks::run('post_sqladd_action', $vars, self::$last_id);
            $pinger = Options::v('pinger');
            if ($pinger != "") {
                Pinger::run($pinger);
            }

        }
        return $post;
    }


            $regx = str_replace('/','\/', $k);

            if ( preg_match('/^'.$regx.'$/Usi', $uri, $m) ) {
                $result = [$v,$m];
                return $result;

            }

        }
    }


    public static function add($var) {

        $route = self::$_route;

        self::$_route = array_merge($route, $var);

        return self::$_route;

    }


    public static function extract ($var, $m) {

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

            if ($k2 != '0') {

                $va[] = [$k2 => $m[$v2]];

            }elseif($k2 == ''){

                $va = ['default'];

            }else{

                $va = array($k2) ;

            }
        }

        return $va;

    }


    public static function set($vars) {
        self::set_session($vars);
    }


public static function versionReport() {

        $v = self::latestVersion();

        $html = "

             Warning: Your CMS version is different with our latest version ($v).
            Please upgrade your system.

        ";

        return $html;
    }


    public static function getParent($id=''){

        return Categories::getParent($id);

    }


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

    }


    public static function thmList(){
        //$mod = '';
        $handle = dir(GX_THEME);
        while (false !== ($entry = $handle->read())) {
            if ($entry != "." && $entry != ".." ) {
                    $dir = GX_THEME.$entry;
                    if(is_dir($dir) == true){
                        $thm[] = basename($dir);
                    }
            }
        }

        $handle->close();
        return $thm;
    }


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


    public static function cleanX ($c) {
        $val = self::strip_tags_content($c, '<script>', TRUE);
        $val = htmlspecialchars(
                $val,
                ENT_QUOTES|ENT_HTML5,
                "utf-8"
            );
        // $val = htmlentities(
        //             $c,
        //             ENT_QUOTES | ENT_IGNORE, "UTF-8");
        return $val;
    }


    public static function is_loggedin () {
        $username = Session::val('username');
        if(isset($username)) {
            $v = true;
        }else{
            $v = false;
        }
        return $v;
    }


    public static function create($vars) {
        if(is_array($vars)){

            //print_r($vars['user']);
            $u = $vars['user'];
            $sql = array(
                            'table' => 'user',
                            'key' => $u,
                        );
            $db = Db::insert($sql);

            if(!isset($vars['detail']) || $vars['detail'] == ''){
                Db::insert("INSERT INTO `user_detail` (`userid`) VALUES ('{$vars['user']['userid']}')");
            }else{
                $u = $vars['detail'];
                $sql = array(
                                'table' => 'user_detail',
                                'key' => $u,
                            );
                Db::insert($sql);
            }
            Hooks::run('user_sqladd_action', $vars);
        }

        return $db;
    }


    public static function randpass($vars){
        if(is_array($vars)){
            $hash = sha1($vars['passwd'].SECURITY_KEY.$vars['userid']);
        }else{
            $hash = sha1($vars.SECURITY_KEY);
        }

        $hash = substr($hash, 5, 16);
        $pass = md5($hash);
        return $pass;
    }


    public static function delete($id){
        $vars = array(
                'table' => 'user',
                'where' => array(
                            'id' => $id
                            )
            );
        Db::delete($vars);

        $vars = array(
                'table' => 'user_detail',
                'where' => array(
                            'id' => $id
                            )
            );
        Db::delete($vars);
        Hooks::run('user_sqldel_action', $vars);
    }


    public static function userid($id){
        $usr = Db::result(
            sprintf("SELECT * FROM `user` WHERE `id` = '%d' LIMIT 1",
                Typo::int($id)
                )
            );
        return $usr[0]->userid;
    }


            composerRequire57fe33d7077d32d85bc5d5df10c056df($file);
        }

        return $loader;
    }


    public static function getCookieValue($value)
    {
        if (substr($value, 0, 1) !== '"' &&
            substr($value, -1, 1) !== '"' &&
            strpbrk($value, ';,=')
        ) {
            $value = '"' . $value . '"';
        }

        return $value;
    }


    private function timeToNext()
    {
        $currentTime = microtime(true);
        $nextTime = PHP_INT_MAX;
        foreach ($this->delays as $time) {
            if ($time < $nextTime) {
                $nextTime = $time;
            }
        }

        return max(0, $currentTime - $nextTime);
    }


                $resource = fopen($request->getUri(), 'r', null, $context);
                $this->lastHeaders = $http_response_header;
                return $resource;
            }
        );


                $v = trim($v);
            }
        }

        // Remove the header lines.
        foreach (array_keys($new->headerLines) as $key) {
            if (strtolower($key) === $name) {
                unset($new->headerLines[$key]);
            }
        }

        // Add the header line.
        $new->headerLines[$header] = $new->headers[$name];

        return $new;
    }


    private function updateHostFromUri($host)
    {
        // Ensure Host is the first header.
        // See: http://tools.ietf.org/html/rfc7230#section-5.4
        if ($port = $this->uri->getPort()) {
            $host .= ':' . $port;
        }

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


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

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

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

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


    public function withScheme($scheme)
    {
        $scheme = $this->filterScheme($scheme);

        if ($this->scheme === $scheme) {
            return $this;
        }

        $new = clone $this;
        $new->scheme = $scheme;
        $new->port = $new->filterPort($new->scheme, $new->host, $new->port);
        return $new;
    }


    public function testConvertsResponsesToStrings()
    {
        $response = new Psr7\Response(200, [
            'Baz' => 'bar',
            'Qux' => ' ipsum'
        ], 'hello', '1.0', 'FOO');
        $this->assertEquals(
            "HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
            Psr7\str($response)
        );
    }


    public function testAggregatesHeaders()
    {
        $r = new Request('GET', 'http://foo.com', [
            'ZOO' => 'zoobar',
            'zoo' => ['foobar', 'zoobar']
        ]);
        $this->assertEquals('zoobar, foobar, zoobar', $r->getHeaderLine('zoo'));
    }


    public function testSameInstanceWhenSameBody()
    {
        $r = new Response(200, [], 'foo');
        $b = $r->getBody();
        $this->assertSame($r, $r->withBody($b));
    }


    public function pathTestProvider()
    {
        return [
            // Percent encode spaces.
            ['http://foo.com/baz bar', 'http://foo.com/baz%20bar'],
            // Don't encoding something that's already encoded.
            ['http://foo.com/baz%20bar', 'http://foo.com/baz%20bar'],
            // Percent encode invalid percent encodings
            ['http://foo.com/baz%2-bar', 'http://foo.com/baz%252-bar'],
            // Don't encode path segments
            ['http://foo.com/baz/bar/bam?a', 'http://foo.com/baz/bar/bam?a'],
            ['http://foo.com/baz+bar', 'http://foo.com/baz+bar'],
            ['http://foo.com/baz:bar', 'http://foo.com/baz:bar'],
            ['http://foo.com/baz@bar', 'http://foo.com/baz@bar'],
            ['http://foo.com/baz(bar);bam/', 'http://foo.com/baz(bar);bam/'],
            ['http://foo.com/a-zA-Z0-9.-_~!$&\'()*+,;=:@', 'http://foo.com/a-zA-Z0-9.-_~!$&\'()*+,;=:@'],
        ];
    }


            $attvalue = str_replace($quotchar, "", $attvalue);
            switch ($attname){
                case 'background':
                    $styledef .= "background-image: url('$trans_image_path'); ";
                    break;
                case 'bgcolor':
                    $has_bgc_stl = true;
                    $styledef .= "background-color: $attvalue; ";
                    break;
                case 'text':
                    $has_txt_stl = true;
                    $styledef .= "color: $attvalue; ";
                    break;
            }
        }
        // Outlook defines a white bgcolor and no text color. This can lead to
        // white text on a white bg with certain themes.
        if ($has_bgc_stl && !$has_txt_stl) {
            $styledef .= "color: $text; ";
        }
        if (strlen($styledef) > 0){
            $divattary{"style"} = "\"$styledef\"";
        }
    }
    return $divattary;
}


	protected function get_remote_contents( &$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null ) {
		$method = (function_exists('curl_exec') && !ini_get('safe_mode'))? 'curl_get_contents' : 'fsock_get_contents';
		return $this->$method( $url, $timeout, $redirect_max, $ua, $fp );
	}


	protected function info($args) {
		$files = array();
		$sleep = 0;
		$compare = null;
		// long polling mode
		if ($args['compare'] && count($args['targets']) === 1) {
			$compare = intval($args['compare']);
			$hash = $args['targets'][0];
			if ($volume = $this->volume($hash)) {
				$standby = (int)$volume->getOption('plStandby');
				$_compare = false;
				if (($syncCheckFunc = $volume->getOption('syncCheckFunc')) && is_callable($syncCheckFunc)) {
					$_compare = call_user_func_array($syncCheckFunc, array($volume->realpath($hash), $standby, $compare, $volume, $this));
				}
				if ($_compare !== false) {
					$compare = $_compare;
				} else {
					$sleep = max(1, (int)$volume->getOption('tsPlSleep'));
					$limit = max(1, $standby / $sleep) + 1;
					$timelimit = ini_get('max_execution_time');
					do {
						$timelimit && @ set_time_limit($timelimit + $sleep);
						$volume->clearstatcache();
						if (($info = $volume->file($hash)) != false) {
							if ($info['ts'] != $compare) {
								$compare = $info['ts'];
								break;
							}
						} else {
							$compare = 0;
							break;
						}
						if (--$limit) {
							sleep($sleep);
						}
					} while($limit);
				}
			}
		} else {
			foreach ($args['targets'] as $hash) {
				if (($volume = $this->volume($hash)) != false
				&& ($info = $volume->file($hash)) != false) {
					$info['path'] = $volume->path($hash);
					$files[] = $info;
				}
			}
		}

		$result = array('files' => $files);
		if (!is_null($compare)) {
			$result['compare'] = strval($compare);
		}
		return $result;
	}


	protected function mkdir($args) {
		$target = $args['target'];
		$name   = $args['name'];

		if (($volume = $this->volume($target)) == false) {
			return array('error' => $this->error(self::ERROR_MKDIR, $name, self::ERROR_TRGDIR_NOT_FOUND, '#'.$target));
		}

		return ($dir = $volume->mkdir($target, $name)) == false
			? array('error' => $this->error(self::ERROR_MKDIR, $name, $volume->error()))
			: array('added' => array($dir));
	}


  	protected function imgCrop($path, $width, $height, $x, $y, $destformat = null, $jpgQuality = null) {
		if (($s = @getimagesize($path)) == false) {
			return false;
		}

		$result = false;

		if (!$jpgQuality) {
			$jpgQuality = $this->options['jpgQuality'];
		}

		switch ($this->imgLib) {
			case 'imagick':

				try {
					$img = new imagick($path);
				} catch (Exception $e) {
					return false;
				}

				$ani = ($img->getNumberImages() > 1);
				if ($ani && is_null($destformat)) {
					$img = $img->coalesceImages();
					do {
						$img->setImagePage($s[0], $s[1], 0, 0);
						$img->cropImage($width, $height, $x, $y);
						$img->setImagePage($width, $height, 0, 0);
					} while ($img->nextImage());
					$img = $img->optimizeImageLayers();
					$result = $img->writeImages($path, true);
				} else {
					if ($ani) {
						$img->setFirstIterator();
					}
					$img->setImagePage($s[0], $s[1], 0, 0);
					$img->cropImage($width, $height, $x, $y);
					$img->setImagePage($width, $height, 0, 0);
					$result = $this->imagickImage($img, $path, $destformat, $jpgQuality);
				}

				$img->clear();

				return $result ? $path : false;

				break;

			case 'gd':
				$img = $this->gdImageCreate($path,$s['mime']);

				if ($img &&  false != ($tmp = imagecreatetruecolor($width, $height))) {

					$this->gdImageBackground($tmp,$this->options['tmbBgColor']);

					$size_w = $width;
					$size_h = $height;

					if ($s[0] < $width || $s[1] < $height) {
						$size_w = $s[0];
						$size_h = $s[1];
					}

					if (!imagecopy($tmp, $img, 0, 0, $x, $y, $size_w, $size_h)) {
						return false;
					}

					$result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);

					imagedestroy($img);
					imagedestroy($tmp);

					return $result ? $path : false;

				}
				break;
		}

		return false;
	}


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


	protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null, $jpgQuality = null) {
		if (($s = @getimagesize($path)) == false || $degree % 360 === 0) {
			return false;
		}

		$result = false;

		// try lossless rotate
		if ($degree % 90 === 0 && in_array($s[2], array(IMAGETYPE_JPEG, IMAGETYPE_JPEG2000))) {
			$count = ($degree / 90) % 4;
			$exiftran = array(
				1 => '-9',
				2 => '-1',
				3 => '-2'
			);
			$jpegtran = array(
				1 => '90',
				2 => '180',
				3 => '270'
			);
			$quotedPath = escapeshellarg($path);
			$cmds = array(
				'exiftran -i '.$exiftran[$count].' '.$path,
				'jpegtran -rotate '.$jpegtran[$count].' -copy all -outfile '.$quotedPath.' '.$quotedPath
			);
			foreach($cmds as $cmd) {
				if ($this->procExec($cmd) === 0) {
					$result = true;
					break;
				}
			}
			if ($result) {
				return $path;
			}
		}

		if (!$jpgQuality) {
			$jpgQuality = $this->options['jpgQuality'];
		}

		switch ($this->imgLib) {
			case 'imagick':
				try {
					$img = new imagick($path);
				} catch (Exception $e) {
					return false;
				}

				if ($img->getNumberImages() > 1) {
					$img = $img->coalesceImages();
					do {
						$img->rotateImage(new ImagickPixel($bgcolor), $degree);
					} while ($img->nextImage());
					$img = $img->optimizeImageLayers();
					$result = $img->writeImages($path, true);
				} else {
					$img->rotateImage(new ImagickPixel($bgcolor), $degree);
					$result = $this->imagickImage($img, $path, $destformat, $jpgQuality);
				}
				$img->clear();
				return $result ? $path : false;

				break;

			case 'gd':
				$img = $this->gdImageCreate($path,$s['mime']);

				$degree = 360 - $degree;
				list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
				$bgcolor = imagecolorallocate($img, $r, $g, $b);
				$tmp = imageRotate($img, $degree, (int)$bgcolor);

				$result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);

				imageDestroy($img);
				imageDestroy($tmp);

				return $result ? $path : false;

				break;
		}

		return false;
	}


	protected function imagickImage($img, $filename, $destformat, $jpgQuality = null ){

		if (!$jpgQuality) {
			$jpgQuality = $this->options['jpgQuality'];
		}

		try {
			if ($destformat) {
				if ($destformat === 'gif') {
					$img->setImageFormat('gif');
				} else if ($destformat === 'png') {
					$img->setImageFormat('png');
				} else if ($destformat === 'jpg') {
					$img->setImageFormat('jpeg');
				}
			}
			if (strtoupper($img->getImageFormat()) === 'JPEG') {
				$img->setImageCompression(imagick::COMPRESSION_JPEG);
				$img->setImageCompressionQuality($jpgQuality);
				try {
					$orientation = $img->getImageOrientation();
				} catch (ImagickException $e) {
					$orientation = 0;
				}
				$img->stripImage();
				if ($orientation) {
					$img->setImageOrientation($orientation);
				}
			}
			$result = $img->writeImage($filename);
		} catch (Exception $e) {
			$result = false;
		}

		return $result;

		if ($destformat == 'jpg' || ($destformat == null && $mime == 'image/jpeg')) {
			return imagejpeg($image, $filename, $jpgQuality);
		}

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

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


	public function __construct() {

		//ini_set('memory_limit', '128M');
		@ include_once 'Dropbox/autoload.php';
		$this->dropbox_phpFound = in_array('Dropbox_autoload', spl_autoload_functions());

		$opts = array(
			'consumerKey'       => '',
			'consumerSecret'    => '',
			'accessToken'       => '',
			'accessTokenSecret' => '',
			'dropboxUid'        => '',
			'root'              => 'dropbox',
			'path'              => '/',
			'separator'         => '/',
			'PDO_DSN'           => '', // if empty use 'sqlite:(metaCachePath|tmbPath)/elFinder_dropbox_db_(hash:dropboxUid+consumerSecret)'
			'PDO_User'          => '',
			'PDO_Pass'          => '',
			'PDO_Options'       => array(),
			'PDO_DBName'        => 'dropbox',
			'treeDeep'          => 0,
			'tmbPath'           => '',
			'tmbURL'            => '',
			'tmpPath'           => '',
			'getTmbSize'        => 'large', // small: 32x32, medium or s: 64x64, large or m: 128x128, l: 640x480, xl: 1024x768
			'metaCachePath'     => '',
			'metaCacheTime'     => '600', // 10m
			'acceptedName'      => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
			'rootCssClass'      => 'elfinder-navbar-root-dropbox'
		);
		$this->options = array_merge($this->options, $opts);
		$this->options['mimeDetect'] = 'internal';
	}


	protected function _fclose($fp, $path='') {
		@fclose($fp);
		if ($path) {
			@unlink($this->getTempFile($path));
		}
	}


	public function localFileSystemSearchIteratorFilter($file, $key, $iterator) {
		if ($iterator->hasChildren()) {
			return (bool)$this->attr($key, 'read', null, true);
		}
		return ($this->stripos($file->getFilename(), $this->doSearchCurrentQuery) === false)? false : true;
	}


	protected function _unlink($path) {
		$ret = @unlink($path);
		$ret && clearstatcache();
		return $ret;
	}


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

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

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

		return $target;
	}


	protected function _copy($source, $targetDir, $name) {
		$ret = copy($source, $this->_joinPath($targetDir, $name));
		$ret && clearstatcache();
		return $ret;
	}


	protected function _move($source, $targetDir, $name) {
		$sql = 'UPDATE %s SET parent_id=%d, name="%s" WHERE id=%d LIMIT 1';
		$sql = sprintf($sql, $this->tbf, $targetDir, $this->db->real_escape_string($name), $source);
		return $this->query($sql) && $this->db->affected_rows > 0 ? $source : false;
	}


	protected function _fopen($path, $mode='rb') {
		$fp = $this->tmbPath
			? @fopen($this->getTempFile($path), 'w+')
			: @tmpfile();

		if ($fp) {
			if (($res = $this->query('SELECT content FROM '.$this->tbf.' WHERE id="'.$path.'"'))
			&& ($r = $res->fetch_assoc())) {
				fwrite($fp, $r['content']);
				rewind($fp);
				return $fp;
			} else {
				$this->_fclose($fp, $path);
			}
		}

		return false;
	}


	protected function configure() {
		parent::configure();

		if (($tmp = $this->options['tmpPath'])) {
			if (!file_exists($tmp)) {
				if (@mkdir($tmp)) {
					@chmod($tmp, $this->options['tmbPathMode']);
				}
			}

			$this->tmpPath = is_dir($tmp) && is_writable($tmp) ? $tmp : false;
		}
		if (!$this->tmpPath && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
			$this->tmpPath = $tmp;
		}

		if (!$this->tmpPath && $this->tmbPath && $this->tmbPathWritable) {
			$this->tmpPath = $this->tmbPath;
		}

		$this->mimeDetect = 'internal';
	}


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

		$res = $this->query($sql);

		if ($res) {
			$stat = $res->fetch_assoc();
			if ($stat['parent_id']) {
				$stat['phash'] = $this->encode($stat['parent_id']);
			}
			if ($stat['mime'] == 'directory') {
				unset($stat['width']);
				unset($stat['height']);
			} else {
				unset($stat['dirs']);
			}
			unset($stat['id']);
			unset($stat['parent_id']);
			return $stat;

		}
		return array();
	}


	public function onUpLoadPreSave(&$path, &$name, $src, $elfinder, $volume) {

		$opts = $this->opts;
		$volOpts = $volume->getOptionsPlugin('Watermark');
		if (is_array($volOpts)) {
			$opts = array_merge($this->opts, $volOpts);
		}

		if (! $opts['enable']) {
			return false;
		}

		$srcImgInfo = @getimagesize($src);
		if ($srcImgInfo === false) {
			return false;
		}

		// check Animation Gif
		if (elFinder::isAnimationGif($src)) {
			return false;
		}

		// check water mark image
		if (! file_exists($opts['source'])) {
			$opts['source'] = dirname(__FILE__) . "/" . $opts['source'];
		}
		if (is_readable($opts['source'])) {
			$watermarkImgInfo = @getimagesize($opts['source']);
			if (! $watermarkImgInfo) {
				return false;
			}
		} else {
			return false;
		}

		$watermark = $opts['source'];
		$marginLeft = $opts['marginRight'];
		$marginBottom = $opts['marginBottom'];
		$quality = $opts['quality'];
		$transparency = $opts['transparency'];

		// check target image type
		$imgTypes = array(
			IMAGETYPE_GIF  => IMG_GIF,
			IMAGETYPE_JPEG => IMG_JPEG,
			IMAGETYPE_PNG  => IMG_PNG,
			IMAGETYPE_BMP  => IMG_WBMP,
			IMAGETYPE_WBMP => IMG_WBMP
		);
		if (! ($opts['targetType'] & @$imgTypes[$srcImgInfo[2]])) {
			return false;
		}

		// check target image size
		if ($opts['targetMinPixel'] > 0 && $opts['targetMinPixel'] > min($srcImgInfo[0], $srcImgInfo[1])) {
			return false;
		}

		$watermark_width = $watermarkImgInfo[0];
		$watermark_height = $watermarkImgInfo[1];
		$dest_x = $srcImgInfo[0] - $watermark_width - $marginLeft;
		$dest_y = $srcImgInfo[1] - $watermark_height - $marginBottom;

		if (class_exists('Imagick', false)) {
			return $this->watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo);
		} else {
			return $this->watermarkPrint_gd($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo, $srcImgInfo);
		}
	}


    public function getInt($key, $default = 0, $deep = false)
    {
        return (int) $this->get($key, $default, $deep);
    }


    public function destroy($sessionId)
    {
        $this->getCollection()->remove(array(
            $this->options['id_field'] => $sessionId,
        ));

        return true;
    }


    private function createMongoCollectionMock()
    {
        $collection = $this->getMockBuilder('MongoCollection')
            ->disableOriginalConstructor()
            ->getMock();

        return $collection;
    }


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

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

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


    public function testConstruct()
    {
        $handler = new NativeSessionHandler();

        // note for PHPUnit optimisers - the use of assertTrue/False
        // here is deliberate since the tests do not require the classes to exist - drak
        if (PHP_VERSION_ID < 50400) {
            $this->assertFalse($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        } else {
            $this->assertTrue($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        }
    }


    public function testPhpSession54()
    {
        $storage = $this->getStorage();

        $this->assertFalse($storage->getSaveHandler()->isActive());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        // in PHP 5.4 we can reliably detect a session started
        $this->assertTrue($storage->getSaveHandler()->isActive());
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
        $this->assertTrue(isset($_SESSION[$key]));
    }


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


    private static function verifySignature($signature, $input, $key, $algo = 'HS256')
    {
        switch ($algo) {
            case'HS256':
            case'HS384':
            case'HS512':
                return JWT::sign($input, $key, $algo) === $signature;

            case 'RS256':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA256);

            case 'RS384':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA384);

            case 'RS512':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA512);

            default:
                throw new Exception("Unsupported or invalid signing algorithm.");
        }
    }


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

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

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

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

        $this->validatePathLength();
    }


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


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


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


  public function SetFrom($address, $name = '', $auto = 1) {
    $address = trim($address);
    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    if (!$this->ValidateAddress($address)) {
      $this->SetError($this->Lang('invalid_address').': '. $address);
      if ($this->exceptions) {
        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
      }
      if ($this->SMTPDebug) {
        $this->edebug($this->Lang('invalid_address').': '.$address);
      }
      return false;
    }
    $this->From = $address;
    $this->FromName = $name;
    if ($auto) {
      if (empty($this->ReplyTo)) {
        $this->AddAnAddress('Reply-To', $address, $name);
      }
      if (empty($this->Sender)) {
        $this->Sender = $address;
      }
    }
    return true;
  }


  public function IsMail() {
    $this->Mailer = 'mail';
  }


  public function IsHTML($ishtml = true) {
    if ($ishtml) {
      $this->ContentType = 'text/html';
    } else {
      $this->ContentType = 'text/plain';
    }
  }


  public function IsSendmail() {
    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
      $this->Sendmail = '/var/qmail/bin/sendmail';
    }
    $this->Mailer = 'sendmail';
  }


public function Mail($from) {
    $this->error = null; // so no confusion is caused

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

    $useVerp = ($this->do_verp ? " XVERP" : "");
    fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $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 != 250) {
      $this->error =
        array("error" => "MAIL 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;
    }
    return true;
  }


  public function Turn() {
    $this->error = array("error" => "This method, TURN, of the SMTP ".
                                    "is not implemented");
    if($this->do_debug >= 1) {
      $this->edebug("SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />');
    }
    return false;
  }


private function get_lines() {
    $data = "";
    $endtime = 0;
    /* If for some reason the fp is bad, don't inf loop */
    if (!is_resource($this->smtp_conn)) {
      return $data;
    }
    stream_set_timeout($this->smtp_conn, $this->Timeout);
    if ($this->Timelimit > 0) {
      $endtime = time() + $this->Timelimit;
    }
    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
      $str = @fgets($this->smtp_conn,515);
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
');
        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
');
      }
      $data .= $str;
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
');
      }
      // if 4th character is a space, we are done reading, break the loop
      if(substr($str,3,1) == " ") { break; }
      // Timed-out? Log and break
      $info = stream_get_meta_data($this->smtp_conn);
      if ($info['timed_out']) {
        if($this->do_debug >= 4) {
          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds)
");
        }
        break;
      }
      // Now check if reads took too long
      if ($endtime) {
        if (time() > $endtime) {
          if($this->do_debug >= 4) {
            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds)
");
          }
          break;
        }
      }
    }
    return $data;
  }


public function SendAndMail($from) {
    $this->error = null; // so no confusion is caused

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

    fputs($this->smtp_conn,"SAML FROM:" . $from . $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 != 250) {
      $this->error =
        array("error" => "SAML 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;
    }
    return true;
  }


    public function execute(&$params){
        $options = &$this->config['options'];

        $event = new Events;
        $notif = new Notification;

        $user = $this->parseOption('user', $params);

        $type = $this->parseOption('type', $params);

        if($type === 'auto'){
            if(!isset($params['model']))
                return array (false, '');
            $notif->modelType = get_class($params['model']);
            $notif->modelId = $params['model']->id;
            $notif->type = $this->getNotifType();

            $event->associationType = get_class($params['model']);
            $event->associationId = $params['model']->id;
            $event->type = $this->getEventType();
            if($params['model']->hasAttribute('visibility'))
                $event->visibility = $params['model']->visibility;
            // $event->user = $this->parseOption('user',$params);
        } else{
            $text = $this->parseOption('text', $params);

            $notif->type = 'custom';
            $notif->text = $text;

            $event->type = 'feed';
            $event->subtype = $type;
            $event->text = $text;
            if($user == 'auto' && isset($params['model']) &&
                $params['model']->hasAttribute('assignedTo') &&
                !empty($params['model']->assignedTo)){

                $event->user = $params['model']->assignedTo;
            }elseif(!empty($user)){
                $event->user = $user;
            }else{
                $event->user = 'admin';
            }
        }
        if(!$this->parseOption('createNotif', $params)) {
            if (!$notif->save()) {
                return array(false, array_shift($notif->getErrors()));
            }
        }

        if ($event->save()) {
            return array (true, "");
        } else {
            return array(false, array_shift($event->getErrors()));
        }

    }


            $layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair
            $changed = true;
        }

        // remove obsolete widgets
        $arrayDiff =
                array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));
        foreach($arrayDiff as $elem){
            if(in_array ($elem, array_keys ($layout[$position]))) {
                unset($layout[$position][$elem]);
                $changed = true;
            } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {
                unset($layout['hidden'][$elem]);
                $changed = true;
            }
        }

        // ensure that widget properties are the same as those in the default layout
        foreach($layout[$position] as $name=>$arr){
            if (in_array ($name, array_keys ($initLayout[$position])) &&
                $initLayout[$position][$name]['title'] !== $arr['title']) {

                $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];
                $changed = true;
            }
        }
        if ($position === 'center') {
            foreach($layout['hidden'] as $name=>$arr){
                if (in_array ($name, array_keys ($initLayout[$position])) &&
                    $initLayout[$position][$name]['title'] !== $arr['title']) {

                    $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];
                    $changed = true;
                }
            }
        }

        if($changed){
            $this->layout = json_encode($layout);
            $this->update(array('layout'));
        }
    }


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


                    $modelNames[ucfirst($module->name)] = self::getModelTitle($modelName);
            }
            asort ($modelNames);
            if ($criteria !== null) {
                return $modelNames;
            } else {
                self::$_modelNames = $modelNames;
            }
        }
        return self::$_modelNames;
    }


    public function actionGetItems() {
        $sql = 'SELECT id, name as value FROM x2_accounts 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 actionGetItems(){
        $model = X2Model::model ($this->modelClass);
        if (isset ($model)) {
            $tableName = $model->tableName ();
            $sql =
                'SELECT id, subject as value
                 FROM '.$tableName.' WHERE subject LIKE :qterm ORDER BY subject 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 rules() {
        $parentRules = parent::rules();
        $parentRules[] = array(
            'firstName,lastName', 'required', 'on' => 'webForm');
        return $parentRules;
    }


    public function getDisplayName ($plural=true) {
        return Yii::t('marketing', 'Web Form');
    }


    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 static function restoreX2WebUser () {
        if (isset (self::$_oldUserComponent)) {
            Yii::app()->setComponent ('user', self::$_oldUserComponent);
        } else {
            throw new CException ('X2WebUser component could not be restored');
        }
    }


    public function session() {
        // Test if logged in, log in if not, log in.
        try {
            $this->assertElementPresent('css=ul#user-menu');
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            /* If this isn't the first time we've logged in, we have a problem;
             * the user should have been logged in throughout the life of the
             * test case class. Append t
             */
            if (!$this->firstLogin)
                array_push($this->verificationErrors, $e->toString());
            $this->firstLogin = false;
            $this->login();
            return 0;
        }
        try {
            $this->assertCorrectUser();
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            /**
             * The browser is logged in but not as the correct user.
             */
            $this->logout();
            $this->login();
            $this->firstLogin = false;
            return 0;
        }
        // Indicator of whether the session was already initialized properly
        return 1;
    }


    protected function prepareImport($model, $csvName) {
        $this->openX2 ('/admin/importModels?model='.ucfirst($model));
        $csv = implode(DIRECTORY_SEPARATOR, array(
            Yii::app()->basePath,
            'tests',
            'data',
            'csvs',
            $csvName
        ));
        $this->type ('data', $csv);
        $this->clickAndWait ("dom=document.querySelector ('input[type=\"submit\"]')");
        $this->assertCsvUploaded ($csv);
    }


function compression_test() {
?>
	<script type="text/javascript">
	var testCompression = {
		get : function(test) {
			var x;
			if ( window.XMLHttpRequest ) {
				x = new XMLHttpRequest();
			} else {
				try{x=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{x=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){};}
			}

			if (x) {
				x.onreadystatechange = function() {
					var r, h;
					if ( x.readyState == 4 ) {
						r = x.responseText.substr(0, 18);
						h = x.getResponseHeader('Content-Encoding');
						testCompression.check(r, h, test);
					}
				};

				x.open('GET', ajaxurl + '?action=wp-compression-test&test='+test+'&'+(new Date()).getTime(), true);
				x.send('');
			}
		},

		check : function(r, h, test) {
			if ( ! r && ! test )
				this.get(1);

			if ( 1 == test ) {
				if ( h && ( h.match(/deflate/i) || h.match(/gzip/i) ) )
					this.get('no');
				else
					this.get(2);

				return;
			}

			if ( 2 == test ) {
				if ( '"wpCompressionTest' == r )
					this.get('yes');
				else
					this.get('no');
			}
		}
	};
	testCompression.check();
	</script>
<?php
}


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

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

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

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

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

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

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

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

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


    public function setHomePage()
    {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException(__('This endpoint only aaccepts POST requests.'));
        }
        if (empty($this->request->data['path'])) {
            $this->request->data = array('path' => $this->request->data);
        }
        if (empty($this->request->data['path'])) {
            throw new InvalidArgumentException(__('No path POSTed.'));
        }
        $setting = array(
            'UserSetting' => array(
                'user_id' => $this->Auth->user('id'),
                'setting' => 'homepage',
                'value' => json_encode(array('path' => $this->request->data['path']))
            )
        );
        $result = $this->UserSetting->setSetting($this->Auth->user(), $setting);
        return $this->RestResponse->saveSuccessResponse('UserSettings', 'setHomePage', false, $this->response->type(), 'Homepage set to ' . $this->request->data['path']);
    }


    public function checkAuthorisation($id, $user, $write)
    {
        // fetch the bare template
        $template = $this->find('first', array(
            'conditions' => array('id' => $id),
            'recursive' => -1,
        ));

        // if not found return false
        if (empty($template)) {
            return false;
        }

        //if the user is a site admin, return the template withoug question
        if ($user['Role']['perm_site_admin']) {
            return $template;
        }

        if ($write) {
            // if write access is requested, check if template belongs to user's org and whether the user is authorised to edit templates
            if ($user['Organisation']['name'] == $template['Template']['org'] && $user['Role']['perm_template']) {
                return $template;
            }
            return false;
        } else {

            // if read access is requested, check if the template belongs to the user's org or alternatively whether the template is shareable
            if ($user['Organisation']['name'] == $template['Template']['org'] || $template['Template']['share']) {
                return $template;
            }
            return false;
        }
    }


    public function isBlacklisted($ip, $username)
    {
        // first remove old expired rows
        $this->clean();
        // count
        $params = array('conditions' => array(
                        'Bruteforce.ip' => $ip,
                        'Bruteforce.username' => $username),);
        $count = $this->find('count', $params);
        if ($count >= Configure::read('SecureAuth.amount')) {
            return true;
        } else {
            return false;
        }
    }


	public function Archive() {

		// Update "main" ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = "1" WHERE `id` = :tid'
		);
		Database::pexecute($upd_stmt, array('tid' => $this->tid));

		// Update "answers" to ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = "1" WHERE `answerto` = :tid'
		);
		Database::pexecute($upd_stmt, array('tid' => $this->tid));
		return true;
	}


    public function browse() {
        $params = func_get_args();

        $this->path = join('/', $params);
        // make sure there's a / at the end
        if (substr($this->path, -1, 1) != '/')
            $this->path .= '/';

        //security
        // we dont allow back link
        if (strpos($this->path, '..') !== false) {
            /*
            if (Plugin::isEnabled('statistics_api')) {
                $user = null;
                if (AuthUser::isLoggedIn())
                    $user = AuthUser::getUserName();
                $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);
                $event = array('event_type' => 'hack_attempt', // simple event type identifier
                    'description' => __('A possible hack attempt was detected.'), // translatable description
                    'ipaddress' => $ip,
                    'username' => $user);
                Observer::notify('stats_file_manager_hack_attempt', $event);
            }
             */
        }
        $this->path = str_replace('..', '', $this->path);

        // clean up nicely
        $this->path = str_replace('//', '', $this->path);

        // we dont allow leading slashes
        $this->path = preg_replace('/^\//', '', $this->path);

        $this->fullpath = FILES_DIR . '/' . $this->path;

        // clean up nicely
        $this->fullpath = preg_replace('/\/\//', '/', $this->fullpath);

        $this->display('file_manager/views/index', array(
            'dir' => $this->path,
            //'files' => $this->_getListFiles()
            'files' => $this->_listFiles()
        ));
    }


    public function delete() {
        if (!AuthUser::hasPermission('file_manager_delete')) {
            Flash::set('error', __('You do not have sufficient permissions to delete a file or directory.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $paths = func_get_args();

        $file = urldecode(join('/', $paths));

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

        $file = FILES_DIR . '/' . str_replace('..', '', $file);
        $filename = array_pop($paths);
        $paths = join('/', $paths);

        if (is_file($file)) {
            if (!unlink($file))
                Flash::set('error', __('Permission denied!'));
        }
        else {
            if (!$this->_rrmdir($file))
                Flash::set('error', __('Permission denied!'));
        }

        redirect(get_url('plugin/file_manager/browse/' . $paths));
    }


$object->size = convert_size($cur->getSize());
                $object->mtime = date('D, j M, Y', $cur->getMTime());
                list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());

                // Find the file type
                $object->type = $this->_getFileType($cur);

                // make the link depending on if it's a file or a dir
                if ($cur->isDir()) {
                    $object->link = 'path . $object->name) . '">' . $object->name . '';
                } else {
                    $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '">' . $object->name . '';
                }

                $files[$object->name] = $object;
            }


$user = db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($check['user']), 'username');
			form_alternate_row('line' . $check['id']);
			$name = get_data_source_title($check['datasource']);
			$title = $name;
			if (strlen($name) > 50) {
				$name = substr($name, 0, 50);
			}
			form_selectable_cell('' . $name . '', $check['id']);
			form_selectable_cell($user, $check['id']);
			form_selectable_cell(date('F j, Y, G:i', $check['started']), $check['id']);
			form_selectable_cell($check['datasource'], $check['id']);
			form_selectable_cell(debug_icon(($check['done'] ? (strlen($issue_line) ? 'off' : 'on' ) : '')), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_writable']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_exists']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['active']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['rrd_match']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon($info['valid_data']), $check['id'], '', 'text-align: center;');
			form_selectable_cell(debug_icon(($info['rra_timestamp2'] != '' ? 1 : '')), $check['id'], '', 'text-align: center;');
			form_selectable_cell('' . html_escape(strlen(trim($issue_line)) ? $issue_line : '<none>') . '', $check['id']);
			form_checkbox_cell($check['id'], $check['id']);
			form_end_row();
		}
	}else{


			form_selectable_cell(filter_value($vdef['name'], get_request_var('filter'), 'vdef.php?action=edit&id=' . $vdef['id']), $vdef['id']);
            form_selectable_cell($disabled ? __('No'):__('Yes'), $vdef['id'], '', 'text-align:right');
            form_selectable_cell(number_format_i18n($vdef['graphs'], '-1'), $vdef['id'], '', 'text-align:right');
            form_selectable_cell(number_format_i18n($vdef['templates'], '-1'), $vdef['id'], '', 'text-align:right');
            form_checkbox_cell($vdef['name'], $vdef['id'], $disabled);
            form_end_row();
        }


function html_split_string($string, $length = 70, $forgiveness = 10) {
	$new_string = '';
	$j    = 0;
	$done = false;

	while (!$done) {
		if (strlen($string) > $length) {
			for($i = 0; $i < $forgiveness; $i++) {
				if (substr($string, $length-$i, 1) == " ") {
					$new_string .= substr($string, 0, $length-$i) . "<br>";

					break;
				}
			}

			$string = substr($string, $length-$i);
		} else {
			$new_string .= $string;
			$done        = true;
		}

		$j++;
		if ($j > 4) break;
	}

	return $new_string;
}


		} elseif (strtolower($icon) == 'desc') {
			$icon = 'fa fa-sort-desc';
		} else {
			$icon = 'fa fa-unsorted';
		}

		if (($db_column == '') || (substr_count($db_column, 'nosort'))) {
			print '<th ' . ($tip != '' ? "title='" . htmlspecialchars($tip, ENT_QUOTES, 'UTF-8') . "'":'') . " class='$nohide $align' " . ((($i+1) == count($header_items)) ? "colspan='$last_item_colspan' " : '') . '>' . $display_text . "</th>\n";


            $fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');
            if (empty($fileName)) {
                continue;
            }
            $templateBase = $inflector->filter(array(
                'module' => $moduleName,
                'controller' => $controllerName,
                'file' => $fileName)
            );

            $templateExtend = $inflector->filter(array(
                'module' => $moduleName,
                'controller' => $this->Request()->getControllerName(),
                'file' => $fileName)
            );
            if ($this->View()->templateExists($templateBase)) {
                $template .= '{include file="' . $templateBase. '"}' . "\n";
            }
            if ($this->View()->templateExists($templateExtend)) {
                $template .= '{include file="' . $templateExtend. '"}' . "\n";
            }
        }


    public function testDeleteRoutes($uri, $expectedVersion, $expectedController, $expectedAction, $expectedId, $expectedCode)
    {
        $request = new Enlight_Controller_Request_RequestTestCase();
        $request->setMethod('DELETE');

        $response = new Enlight_Controller_Response_ResponseTestCase();

        $request->setPathInfo($uri);
        $this->router->assembleRoute($request, $response);

        static::assertEquals($expectedController, $request->getControllerName());
        static::assertEquals($expectedAction, $request->getActionName());
        static::assertEquals($expectedVersion, $request->getParam('version'));
        static::assertEquals($expectedId, $request->getParam('id'));
        static::assertEquals($expectedCode, $response->getHttpResponseCode());
    }


    public function routePutProvider()
    {
        return [
            ['/api/articles/',     1, 'articles', 'batch',  false, 200],
            ['/api/v1/articles/',  1, 'articles', 'batch',  false, 200],
            ['/api/v2/articles/',  2, 'articles', 'batch',  false, 200],
            ['/api/articles/5',    1, 'articles', 'put',      5,     200],
            ['/api/v1/articles/5', 1, 'articles', 'put',      5,     200],
            ['/api/v2/articles/5', 2, 'articles', 'put',      5,     200],
        ];
    }


  function npgettext($context, $singular, $plural, $number) {
    $key = $context . chr(4) . $singular;
    $ret = $this->ngettext($key, $plural, $number);
    if (strpos($ret, "\004") !== FALSE) {
      return $singular;
    } else {
      return $ret;
    }

  }


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


	function lockTable($table,$lockType="WRITE") {
        $sql = "LOCK TABLES `" . $this->prefix . "$table` $lockType";

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


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


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


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


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


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


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

        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace('"',""",$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","’",$str);
        $str = str_replace("‘","‘",$str);
        $str = str_replace("®","®",$str);
        $str = str_replace("–","-", $str);
        $str = str_replace("—","—", $str);
        $str = str_replace("”","”", $str);
        $str = str_replace("“","“", $str);
        $str = str_replace("¼","¼",$str);
        $str = str_replace("½","½",$str);
        $str = str_replace("¾","¾",$str);
		$str = str_replace("™","™", $str);
		$str = trim($str);

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

        return $str;
    }


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


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


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


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

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

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


	public function update() {
        global $user;

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


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


	public function fixsessions() {
	    global $db;

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


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

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


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


                $banner->increaseImpressions();
            }
        }

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


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

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

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


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

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

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

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

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


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

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

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


	public function delete() {
	    global $db;

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

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

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

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

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


    function edit() {
        global $user;

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

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

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

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


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

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

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

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