    public function testSmtpConnect()
    {
        $this->Mail->SMTPDebug = 4; //Show connection-level errors
        $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed');
        $this->Mail->smtpClose();
        $this->Mail->Host = "ssl://localhost:12345;tls://localhost:587;10.10.10.10:54321;localhost:12345;10.10.10.10";
        $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded');
        $this->Mail->smtpClose();
        $this->Mail->Host = "localhost:12345;10.10.10.10:54321;" . $_REQUEST['mail_host'];
        $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed');
        $this->Mail->smtpClose();
        $this->Mail->Host = " localhost:12345 ; " . $_REQUEST['mail_host'] . ' ';
        $this->assertTrue($this->Mail->smtpConnect(), 'SMTP hosts with stray spaces failed');
        $this->Mail->smtpClose();
        $this->Mail->Host = $_REQUEST['mail_host'];
        //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI
        $this->assertTrue(
            $this->Mail->smtpConnect(array('ssl' => array('verify_depth' => 10))),
            'SMTP connect with options failed'
        );
    }

The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.


function PMA_getErrorReportForm()
{
    $html = "";
    $html .= '<form action="error_report.php" method="post" name="report_frm"'
            . ' id="report_frm" class="ajax">'
            . '<fieldset style="padding-top:0px">';

    $html .= '
' . __(
        'phpMyAdmin has encountered an error. We have collected data about'
        . ' this error as well as information about relevant configuration'
        . ' settings to send to the phpMyAdmin team to help us in'
        . ' debugging the problem.'
    ) . '
';

    $html .= '

'
            . __('You may examine the data in the error report:')
            . '

'
            . '
'
            . htmlspecialchars(PMA_getReportData())
            . '
';

    $html .= '

'
            . __('Please explain the steps that lead to the error:')
            . '

'
            . '<textarea class="report-description" name="description"'
            . 'id="report_description"></textarea>';

    $html .= '<input type="checkbox" name="always_send"'
            . ' id="always_send_checkbox"/>'
            . ''
            . __('Automatically send report next time')
            . '';

    $html .= '</fieldset>';

    $html .= PMA_URL_getHiddenInputs();

    $reportData = PMA_getReportData(false);
    if (! empty($reportData)) {
        $html .= PMA_getHiddenFields($reportData);
    }

    $html .= '</form>';

    return $html;
}

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


function PMA_Process_formset(FormDisplay $form_display)
{
    if (isset($_GET['mode']) && $_GET['mode'] == 'revert') {
        // revert erroneous fields to their default values
        $form_display->fixErrors();
        PMA_generateHeader303();
    }

    if (!$form_display->process(false)) {
        // handle form view and failed POST
        $form_display->display(true, true);
        return;
    }

    // check for form errors
    if (!$form_display->hasErrors()) {
        PMA_generateHeader303();
        return;
    }

    // form has errors, show warning
    $separator = PMA_URL_getArgSeparator('html');
    $page = isset($_GET['page']) ? $_GET['page'] : null;
    $formset = isset($_GET['formset']) ? $_GET['formset'] : null;
    $formset = $formset ? "{$separator}formset=$formset" : '';
    $formId = PMA_isValid($_GET['id'], 'numeric') ? $_GET['id'] : null;
    if ($formId === null && $page == 'servers') {
        // we've just added a new server, get its id
        $formId = $form_display->getConfigFile()->getServerCount();
    }
    $formId = $formId ? "{$separator}id=$formId" : '';
    ?>

<?php echo __('Warning') ?>

        <?php echo __('Submitted form contains errors') ?>

        <a href="<?php echo PMA_URL_getCommon() . $separator ?>
            page=<?php echo $page . $formset . $formId . $separator ?>mode=revert">
            <?php echo __('Try to revert erroneous fields to their default values')
            ?>

    <?php $form_display->displayErrors() ?>
    <a class="btn" href="index.php<?php echo PMA_URL_getCommon() ?>">
        <?php echo __('Ignore errors') ?>

    <a class="btn" href="<?php echo PMA_URL_getCommon() . $separator ?>
        page=<?php echo $page . $formset . $formId
        . $separator ?>mode=edit"><?php echo __('Show form') ?>
    <?php
}

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.


    function setKey($key)
    {
        if (!$this->explicit_key_length) {
            $this->setKeyLength(strlen($key) << 3);
            $this->explicit_key_length = false;
        }

        $this->key = $key;
        $this->changed = true;
        $this->_setEngine();
    }

Exposure of Sensitive Information to an Unauthorized Actor

The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.


    public function testCheckHTTP()
    {
        if (! function_exists('curl_init')) {
            $this->markTestSkipped('Missing curl extension!');
        }
        $this->assertTrue(
            $this->object->checkHTTP("https://www.phpmyadmin.net/test/data")
        );
        $this->assertContains(
            "TEST DATA",
            $this->object->checkHTTP("https://www.phpmyadmin.net/test/data", true)
        );
        $this->assertFalse(
            $this->object->checkHTTP("https://www.phpmyadmin.net/test/nothing")
        );
        // Use rate limit API as it's not subject to rate limiting
        $this->assertContains(
            '"resources"',
            $this->object->checkHTTP("https://api.github.com/rate_limit", true)
        );
    }


    public static function validateNumber(
        $path,
        $values,
        $allow_neg,
        $allow_zero,
        $max_value,
        $error_string
    ) {
        if (empty($values[$path])) {
            return '';
        }

        $value = Util::requestString($values[$path]);

        if (intval($value) != $value
            || (! $allow_neg && $value < 0)
            || (! $allow_zero && $value == 0)
            || $value > $max_value
        ) {
            return $error_string;
        }

        return '';
    }


    public function testCheckLoginPassEntity()
    {
        $login=checkLoginPassEntity('loginbidon', 'passwordbidon', 1, array('dolibarr'));
        print __METHOD__." login=".$login."\n";
        $this->assertEquals($login, '');

        $login=checkLoginPassEntity('admin', 'passwordbidon', 1, array('dolibarr'));
        print __METHOD__." login=".$login."\n";
        $this->assertEquals($login, '');

        $login=checkLoginPassEntity('admin', 'admin', 1, array('dolibarr'));            // Should works because admin/admin exists
        print __METHOD__." login=".$login."\n";
        $this->assertEquals($login, 'admin', 'The test to check if pass of user "admin" is "admin" has failed');

        $login=checkLoginPassEntity('admin', 'admin', 1, array('http','dolibarr'));    // Should work because of second authetntication method
        print __METHOD__." login=".$login."\n";
        $this->assertEquals($login, 'admin');

        $login=checkLoginPassEntity('admin', 'admin', 1, array('forceuser'));
        print __METHOD__." login=".$login."\n";
        $this->assertEquals($login, '');    // Expected '' because should failed because login 'auto' does not exists
    }

Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')

The software constructs a string for a command to executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string.


function barcode_print($code, $encoding="ANY", $scale = 2 ,$mode = "png")
{
    // DOLCHANGE LDR Add log
    dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode");

    $bars=barcode_encode($code,$encoding);
    if (! $bars || ! empty($bars['error']))
    {
        // DOLCHANGE LDR Return error message instead of array
        if (empty($bars['error'])) $error='Bad Value '.$code.' for encoding '.$encoding;
        else $error=$bars['error'];
        dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);
        return $error;
    }
    if (! $mode) $mode="png";
    //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']);
    //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);
    //else
    barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);
    return $bars;
}


	public function execute()
	{
		parent::execute();

		// get parameters
		$searchTerm = SpoonFilter::getPostValue('term', null, '');
		$term = (SPOON_CHARSET == 'utf-8') ? SpoonFilter::htmlspecialchars($searchTerm) : SpoonFilter::htmlentities($searchTerm);

		// validate
		if($term == '') $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.');

		// previous search result
		$previousTerm = SpoonSession::exists('searchTerm') ? SpoonSession::get('searchTerm') : '';
		SpoonSession::set('searchTerm', '');

		// save this term?
		if($previousTerm != $term)
		{
			// format data
			$this->statistics = array();
			$this->statistics['term'] = $term;
			$this->statistics['language'] = FRONTEND_LANGUAGE;
			$this->statistics['time'] = FrontendModel::getUTCDate();
			$this->statistics['data'] = serialize(array('server' => $_SERVER));
			$this->statistics['num_results'] = FrontendSearchModel::getTotal($term);

			// save data
			FrontendSearchModel::save($this->statistics);
		}

		// save current search term in cookie
		SpoonSession::set('searchTerm', $term);

		// output
		$this->output(self::OK);
	}


	public function check_forgot_password_token($token)
	{
		$salt = substr($token, 0, 32);
		return $this->_forgot_password_token($salt) == $token;
	}

Weak Password Recovery Mechanism for Forgotten Password

The software contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.


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


	public function getOnClickAction() {
		return 'javascript:openNewGal(\''.htmlentities($this->stack_name).'\');';
	}


	function insertCommandCategorieInDB(){
		global $pearDB;

		if (testCommandCategorieExistence($_POST["category_name"])){
			$DBRESULT = $pearDB->query("INSERT INTO `command_categories` (`category_name` , `category_alias`, `category_order`) VALUES ('".$pearDB->escape($_POST["category_name"])."', '".$pearDB->escape($_POST["category_alias"])."', '1')");
		}
	}

Improper Control of Generation of Code ('Code Injection')

The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.


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))
			$types["resources"][$row["id"]] = $row["name"];
	}
	return $types;
}

Permissions, Privileges, and Access Controls

Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.


function XMLRPCaddNode($nodeName, $parentNode) {
	require_once(".ht-inc/privileges.php");
	global $user;
	if(! is_numeric($parentNode)) {
		return array('status' => 'error',
		             'errorcode' => 78,
		             'errormsg' => 'Invalid nodeid specified');
	}
	if(in_array("nodeAdmin", $user['privileges'])) {
		$nodeInfo = getNodeInfo($parentNode);
		if(is_null($tmp)) {
			return array('status' => 'error',
			             'errorcode' => 78,
			             'errormsg' => 'Invalid nodeid specified');
		}

		if(! validateNodeName($nodeName, $tmp)) {
			return array('status' => 'error',
			             'errorcode' => 81,
			             'errormsg' => 'Invalid node name');
		}

		if(checkUserHasPriv("nodeAdmin", $user['id'], $parentNode)) {
			$query = "SELECT id "
			       . "FROM privnode "
			       . "WHERE name = '$nodeName' AND parent = $parentNode";
			$qh = doQuery($query);
			if(mysql_num_rows($qh)) {
				return array('status' => 'error',
				             'errorcode' => 82,
				             'errormsg' => 'A node of that name already exists under ' . $nodeInfo['name']);
			}
			$query = "INSERT IGNORE INTO privnode "
			       .        "(parent, name) "
			       . "VALUES "
			       .        "($parentNode, '$nodeName')";
			doQuery($query);
			$qh = doQuery("SELECT LAST_INSERT_ID() FROM privnode", 101);
			if(! $row = mysql_fetch_row($qh)) {
				return array('status' => 'error',
				             'errorcode' => 85,
				             'errormsg' => 'Could not add node to database');
			}
			$nodeid = $row[0];
			return array('status' => 'success',
			             'nodeid' => $nodeid);
		}
		else {
			return array('status' => 'error',
			             'errorcode' => 49,
			             'errormsg' => 'Unable to add node at this location');
		}
	}
	else {
		return array('status' => 'error',
		             'errorcode' => 70,
		             'errormsg' => 'User cannot access node content');
	}
}


				array_push($images, array('id' => $imageid, 'name' => $image));
		}
		return array('status' => 'success',
		             'images' => $images);

	}


			$privs = array_unique($allprivs);
		}
		elseif(array_key_exists($key, $cnp['resources']))
			$privs = $cnp['resources'][$key];
		else
			$privs = array();
		return array('status' => 'success',
		             'privileges' => $privs);
	}
	else {
		return array('status' => 'error',
		             'errorcode' => 71,
		             'errormsg' => 'Invalid resource type');
	}
}


function XMLRPCgetResourceGroups($type) {
	global $user;
	$resources = getUserResources(array("groupAdmin"), array("manageGroup"), 1);
	if(array_key_exists($type, $resources)) {
		return array('status' => 'success',
		             'groups' => $resources[$type]);
	}
	else {
		return array('status' => 'error',
		             'errorcode' => 73,
		             'errormsg' => 'invalid resource group type');
	}
}


function HTMLPurifier($html, $config = null) {
    static $purifier = false;
    if (!$purifier) {
        $purifier = new HTMLPurifier();
    }
    return $purifier->purify($html, $config);
}


        foreach ($attributes as $attribute => $x) {
            $allowed_attributes["$element.$attribute"] = true;
        }


    protected function mungeRgb($string) {
        return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string);
    }


            $value    = trim($value);
            $ok = false;
            do {
                if (isset($definition->info[$property])) {
                    $ok = true;
                    break;
                }
                if (ctype_lower($property)) break;
                $property = strtolower($property);
                if (isset($definition->info[$property])) {
                    $ok = true;
                    break;
                }
            } while(0);
            if (!$ok) continue;
            // inefficient call, since the validator will do this again
            if (strtolower(trim($value)) !== 'inherit') {
                // inherit works for everything (but only on the base property)
                $result = $definition->info[$property]->validate(
                    $value, $config, $context );
            } else {
                $result = 'inherit';
            }
            if ($result === false) continue;
            $propvalues[$property] = $result;
        }

        $context->destroy('CurrentCSSProperty');

        // procedure does not write the new CSS simultaneously, so it's
        // slightly inefficient, but it's the only way of getting rid of
        // duplicates. Perhaps config to optimize it, but not now.

        $new_declarations = '';
        foreach ($propvalues as $prop => $value) {
            $new_declarations .= "$prop:$value;";
        }

        return $new_declarations ? $new_declarations : false;

    }


            $r = $this->percentage->validate($bit, $config, $context);
            if ($r !== false) {
                $measures[] = $r;
                $i++;
            }

        }

        if (!$i) return false; // no valid values were caught

        $ret = array();

        // first keyword
        if     ($keywords['h'])     $ret[] = $keywords['h'];
        elseif ($keywords['ch']) {
            $ret[] = $keywords['ch'];
            $keywords['cv'] = false; // prevent re-use: center = center center
        }
        elseif (count($measures))   $ret[] = array_shift($measures);

        if     ($keywords['v'])     $ret[] = $keywords['v'];
        elseif ($keywords['cv'])    $ret[] = $keywords['cv'];
        elseif (count($measures))   $ret[] = array_shift($measures);

        if (empty($ret)) return false;
        return implode(' ', $ret);

    }


    public function __construct() {
        $this->mask = '_- ';
        for ($c = 'a'; $c <= 'z'; $c++) $this->mask .= $c;
        for ($c = 'A'; $c <= 'Z'; $c++) $this->mask .= $c;
        for ($c = '0'; $c <= '9'; $c++) $this->mask .= $c; // cast-y, but should be fine
        // special bytes used by UTF-8
        for ($i = 0x80; $i <= 0xFF; $i++) {
            // We don't bother excluding invalid bytes in this range,
            // because the our restriction of well-formed UTF-8 will
            // prevent these from ever occurring.
            $this->mask .= chr($i);
        }

        /*
            PHP's internal strcspn implementation is
            O(length of string * length of mask), making it inefficient
            for large masks.  However, it's still faster than
            preg_match 8)
          for (p = s1;;) {
            spanp = s2;
            do {
              if (*spanp == c || p == s1_end) {
                return p - s1;
              }
            } while (spanp++ < (s2_end - 1));
            c = *++p;
          }
         */
        // possible optimization: invert the mask.
    }


    public function __construct($min = null, $max = null) {
        $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;
        $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;
    }


            foreach ($caught as $key => $status) {
                if ($status !== false) continue;
                $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);
                if ($r === false) continue;
                if ($r === 'none') {
                    if ($none) continue;
                    else $none = true;
                    if ($key == 'image') continue;
                }
                $caught[$key] = $r;
                $i++;
                break;
            }


    public function __construct($max = null) {
        $this->max = $max;
    }


                array_splice($first, 8 - count($second), 8, $second);
                $aIP = $first;
                unset($first,$second);
        }


    public function __construct() {
        $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();
    }


    public function __construct($name, $css_name = null) {
        $this->name = $name;
        $this->cssName = $css_name ? $css_name : $name;
    }


    public function set($type, $impl) {
        $this->info[$type] = $impl;
    }


    protected function doSetupTricky($config) {
        $this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(
            'inline', 'block', 'list-item', 'run-in', 'compact',
            'marker', 'table', 'inline-block', 'inline-table', 'table-row-group',
            'table-header-group', 'table-footer-group', 'table-row',
            'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'
        ));
        $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(
            'visible', 'hidden', 'collapse'
        ));
        $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));
    }


            } elseif ($token instanceof HTMLPurifier_Token_End) {
                $nesting--;
            }


    protected function _compileRegex() {
        $raw = str_replace(' ', '', $this->dtd_regex);
        if ($raw{0} != '(') {
            $raw = "($raw)";
        }
        $el = '[#a-zA-Z0-9_.-]+';
        $reg = $raw;

        // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M
        // DOING! Seriously: if there's problems, please report them.

        // collect all elements into the $elements array
        preg_match_all("/$el/", $reg, $matches);
        foreach ($matches[0] as $match) {
            $this->elements[$match] = true;
        }

        // setup all elements as parentheticals with leading commas
        $reg = preg_replace("/$el/", '(,\\0)', $reg);

        // remove commas when they were not solicited
        $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg);

        // remove all non-paranthetical commas: they are handled by first regex
        $reg = preg_replace("/,\(/", '(', $reg);

        $this->_pcre_regex = $reg;
    }


                                $result[] = new HTMLPurifier_Token_Start('li', $t->attr, $t->line, $t->col, $t->armor);
                                break;
                            } else {
                                if (!$t->is_whitespace) {
                                    trigger_error("Only whitespace present invariant violated in List ChildDef", E_USER_ERROR);
                                    return false;
                                }
                            }
                        }
                    }
                } else {
                    // start wrapping (this doesn't precisely mimic
                    // browser behavior, but what browsers do is kind of
                    // hard to mimic in a standards compliant way
                    // XXX Actually, this has no impact in practice,
                    // because this gets handled earlier. Arguably,
                    // we should rip out all of that processing
                    $result[] = new HTMLPurifier_Token_Start('li');
                    $nesting++;
                    $seen_li = true;
                    $need_close_li = true;
                }
            }
            $result[] = $token;
        }
        if ($need_close_li) {
            $result[] = new HTMLPurifier_Token_End('li');
        }
        if (empty($result)) return false;
        if ($all_whitespace) {
            return false;
        }
        if ($tokens_of_children == $result) return true;
        return $result;
    }


                if (empty($i)) unset($elements[$i]); // remove blank
            }
        }
        $this->elements = $elements;
    }


                $ret = array_merge($ret, $token_array);
            }
        }

        if (!empty($collection) && $is_collecting == false){
            // grab the trailing space
            $ret = array_merge($ret, $collection);
        }

        array_pop($tokens_of_children); // remove phantom token

        return ($ret === $tokens_of_children) ? true : $ret;

    }


    public function __construct($definition, $parent = null) {
        $parent = $parent ? $parent : $definition->defaultPlist;
        $this->plist = new HTMLPurifier_PropertyList($parent);
        $this->def = $definition; // keep a copy around for checking
        $this->parser = new HTMLPurifier_VarParser_Flexible();
    }


    public function getBatchSerial($namespace) {
        if (empty($this->serials[$namespace])) {
            $batch = $this->getBatch($namespace);
            unset($batch['DefinitionRev']);
            $this->serials[$namespace] = sha1(serialize($batch));
        }
        return $this->serials[$namespace];
    }


                    $this->set($namespace .'.'. $directive, $value);
                }
            }
        }
    }


    private function _listify($lookup) {
        $list = array();
        foreach ($lookup as $name => $b) $list[] = $name;
        return implode(', ', $list);
    }


    protected function _findUnused($hash) {
        $accessed = $hash->getAccessed();
        foreach ($hash as $k => $v) {
            if (!isset($accessed[$k])) {
                trigger_error("String hash key '$k' not used by builder", E_USER_NOTICE);
            }
        }
    }


    protected function evalArray($contents) {
        return eval('return array('. $contents .');');
    }


    protected function error($target, $msg) {
        if ($target !== false) $prefix = ucfirst($target) . ' in ' .  $this->getFormattedContext();
        else $prefix = ucfirst($this->getFormattedContext());
        throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));
    }


    public function assertIsString() {
        if (!is_string($this->contents)) $this->error('must be a string');
        return $this;
    }


    protected function error($msg) {
        throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);
    }


    public function getChildDef($def, $module) {
        $value = $def->content_model;
        if (is_object($value)) {
            trigger_error(
                'Literal object child definitions should be stored in '.
                'ElementDef->child not ElementDef->content_model',
                E_USER_NOTICE
            );
            return $value;
        }
        switch ($def->content_model_type) {
            case 'required':
                return new HTMLPurifier_ChildDef_Required($value);
            case 'optional':
                return new HTMLPurifier_ChildDef_Optional($value);
            case 'empty':
                return new HTMLPurifier_ChildDef_Empty();
            case 'custom':
                return new HTMLPurifier_ChildDef_Custom($value);
        }
        // defer to its module
        $return = false;
        if ($module->defines_child_def) { // save a func call
            $return = $module->getChildDef($def);
        }
        if ($return !== false) return $return;
        // error-out
        trigger_error(
            'Could not determine which ChildDef class to instantiate',
            E_USER_ERROR
        );
        return false;
    }


    public function register($name, &$ref) {
        if (isset($this->_storage[$name])) {
            trigger_error("Name $name produces collision, cannot re-register",
                          E_USER_ERROR);
            return;
        }
        $this->_storage[$name] =& $ref;
    }


    public function __construct($type) {
        $this->type = $type;
    }


    public function get($config) {
        return $this->cache->get($config);
    }


    public function cleanup($config) {
        return $this->cache->cleanup($config);
    }


    public function set($def, $config) {
        $status = parent::set($def, $config);
        if ($status) $this->definitions[$this->generateKey($config)] = $def;
        return $status;
    }


    public function replace($def, $config) {
        $status = parent::replace($def, $config);
        if ($status) $this->definitions[$this->generateKey($config)] = $def;
        return $status;
    }


    public function generateFilePath($config) {
        $key = $this->generateKey($config);
        return $this->generateDirectoryPath($config) . '/' . $key . '.ser';
    }


    private function _prepareDir($config) {
        $directory = $this->generateDirectoryPath($config);
        $chmod = $config->get('Cache.SerializerPermissions');
        if (!$chmod) {
            $chmod = 0755; // invalid config or simpletest
        }
        if (!is_dir($directory)) {
            $base = $this->generateBaseDirectoryPath($config);
            if (!is_dir($base)) {
                trigger_error('Base directory '.$base.' does not exist,
                    please create or change using %Cache.SerializerPath',
                    E_USER_WARNING);
                return false;
            } elseif (!$this->_testPermissions($base, $chmod)) {
                return false;
            }
            $old = umask(0000);
            mkdir($directory, $chmod);
            umask($old);
        } elseif (!$this->_testPermissions($directory, $chmod)) {
            return false;
        }
        return true;
    }


        foreach ($doctype->aliases as $alias) {
            if (isset($this->doctypes[$alias])) continue;
            $this->aliases[$alias] = $name;
        }


    public static function create($content_model, $content_model_type, $attr) {
        $def = new HTMLPurifier_ElementDef();
        $def->content_model = $content_model;
        $def->content_model_type = $content_model_type;
        $def->attr = $attr;
        return $def;
    }


    public function substituteNonSpecialEntities($string) {
        // it will try to detect missing semicolons, but don't rely on it
        return preg_replace_callback(
            $this->_substituteEntitiesRegex,
            array($this, 'nonSpecialEntityCallback'),
            $string
            );
    }


    public function substituteSpecialEntities($string) {
        return preg_replace_callback(
            $this->_substituteEntitiesRegex,
            array($this, 'specialEntityCallback'),
            $string);
    }


    public function __construct($context) {
        $this->locale    =& $context->get('Locale');
        $this->context   = $context;
        $this->_current  =& $this->_stacks[0];
        $this->errors    =& $this->_stacks[0];
    }


    protected function postFilterCallback($matches) {
        $url = $this->armorUrl($matches[1]);
        return '<object width="425" height="350" type="application/x-shockwave-flash" '.
            'data="http://www.youtube.com/'.$url.'">'.
            '<param name="movie" value="http://www.youtube.com/'.$url.'"></param>'.
            '<!--[if IE]>'.
            '<embed src="http://www.youtube.com/'.$url.'"'.
            'type="application/x-shockwave-flash"'.
            'wmode="transparent" width="425" height="350" />'.
            '<![endif]-->'.
            '</object>';

    }


public function preFilter($html, $config, $context) {
        $pre_regex = '#<object[^>]+>.+?'.
            'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s';
        $pre_replace = '\1';
        return preg_replace($pre_regex, $pre_replace, $html);
    }


            $attr = $this->generateAttributes($token->attr, $token->name);
            if ($this->_flashCompat) {
                if ($token->name == "object") {
                    $flash = new stdclass();
                    $flash->attr = $token->attr;
                    $flash->param = array();
                    $this->_flashStack[] = $flash;
                }
            }
            return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';

        } elseif ($token instanceof HTMLPurifier_Token_End) {


    public function generateScriptFromToken($token) {
        if (!$token instanceof HTMLPurifier_Token_Text) return $this->generateFromToken($token);
        // Thanks <http://lachy.id.au/log/2005/05/script-comments>
        $data = preg_replace('#//\s*$#', '', $token->data);
        return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
    }


    protected function processModules($config) {

        if ($this->_anonModule) {
            // for user specific changes
            // this is late-loaded so we don't have to deal with PHP4
            // reference wonky-ness
            $this->manager->addModule($this->_anonModule);
            unset($this->_anonModule);
        }

        $this->manager->setup($config);
        $this->doctype = $this->manager->doctype;

        foreach ($this->manager->modules as $module) {
            foreach($module->info_tag_transform as $k => $v) {
                if ($v === false) unset($this->info_tag_transform[$k]);
                else $this->info_tag_transform[$k] = $v;
            }
            foreach($module->info_attr_transform_pre as $k => $v) {
                if ($v === false) unset($this->info_attr_transform_pre[$k]);
                else $this->info_attr_transform_pre[$k] = $v;
            }
            foreach($module->info_attr_transform_post as $k => $v) {
                if ($v === false) unset($this->info_attr_transform_post[$k]);
                else $this->info_attr_transform_post[$k] = $v;
            }
            foreach ($module->info_injector as $k => $v) {
                if ($v === false) unset($this->info_injector[$k]);
                else $this->info_injector[$k] = $v;
            }
        }

        $this->info = $this->manager->getElements();
        $this->info_content_sets = $this->manager->contentSets->lookup;

    }


    public function setup($config) {

        $this->addElement('marquee', 'Inline', 'Flow', 'Common',
            array(
                'direction' => 'Enum#left,right,up,down',
                'behavior' => 'Enum#alternate',
                'width' => 'Length',
                'height' => 'Length',
                'scrolldelay' => 'Number',
                'scrollamount' => 'Number',
                'loop' => 'Number',
                'bgcolor' => 'Color',
                'hspace' => 'Pixels',
                'vspace' => 'Pixels',
            )
        );

    }


    public function setup($config) {
        $this->addElement('ruby', 'Inline',
            'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',
            'Common');
        $this->addElement('rbc', false, 'Required: rb', 'Common');
        $this->addElement('rtc', false, 'Required: rt', 'Common');
        $rb = $this->addElement('rb', false, 'Inline', 'Common');
        $rb->excludes = array('ruby' => true);
        $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));
        $rt->excludes = array('ruby' => true);
        $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');
    }


    public function setup($config) {

        // create fixes, initialize fixesForLevel
        $fixes = $this->makeFixes();
        $this->makeFixesForLevel($fixes);

        // figure out which fixes to use
        $level = $config->get('HTML.TidyLevel');
        $fixes_lookup = $this->getFixesForLevel($level);

        // get custom fix declarations: these need namespace processing
        $add_fixes    = $config->get('HTML.TidyAdd');
        $remove_fixes = $config->get('HTML.TidyRemove');

        foreach ($fixes as $name => $fix) {
            // needs to be refactored a little to implement globbing
            if (
                isset($remove_fixes[$name]) ||
                (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))
            ) {
                unset($fixes[$name]);
            }
        }

        // populate this module with necessary fixes
        $this->populate($fixes);

    }


    public function makeFixes() {
        $r = array();
        $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();
        return $r;
    }


            foreach ($module->info as $name => $def) {
                if (!isset($this->elementLookup[$name])) {
                    $this->elementLookup[$name] = array();
                }
                $this->elementLookup[$name][] = $module->name;
            }


    public function handleText(&$token) {
        if (!$this->allowsElement('a')) return;
        if (strpos($token->data, '%') === false) return;

        $bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
        $token = array();

        // $i = index
        // $c = count
        // $l = is link
        for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
            if (!$l) {
                if ($bits[$i] === '') continue;
                $token[] = new HTMLPurifier_Token_Text($bits[$i]);
            } else {
                $token[] = new HTMLPurifier_Token_Start('a',
                    array('href' => str_replace('%s', $bits[$i], $this->docURL)));
                $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);
                $token[] = new HTMLPurifier_Token_End('a');
            }
        }

    }


    public function prepare($config, $context) {
        $this->attrValidator = new HTMLPurifier_AttrValidator();
        $this->config = $config;
        $this->context = $context;
        return parent::prepare($config, $context);
    }


    public function handleEnd(&$token) {
        if ($token->markForDeletion) {
            $token = false;
        }
    }


    public function tokenizeHTML($string, $config, $context) {
        trigger_error('Call to abstract class', E_USER_ERROR);
    }


    protected static function CDATACallback($matches) {
        // not exactly sure why the character set is needed, but whatever
        return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
    }


    public function callbackArmorCommentEntities($matches) {
        return '<!--' . str_replace('&', '&', $matches[1]) . $matches[2];
    }


            foreach($token['attr'] as $attr) {
                if(!$this->stack[0]->hasAttribute($attr['name'])) {
                    $this->stack[0]->setAttribute($attr['name'], $attr['value']);
                }
            }


            $this->token = array(
                'name' => strtoupper($char),
                'type' => self::DOCTYPE,
                'error' => true
            );

            $this->state = 'doctypeName';

        } elseif($char === '>') {


    private function emitToken($token) {
        $emit = $this->tree->emitToken($token);

        if(is_int($emit)) {
            $this->content_model = $emit;

        } elseif($token['type'] === self::ENDTAG) {
            $this->content_model = self::PCDATA;
        }
    }


    private function clearTheActiveFormattingElementsUpToTheLastMarker() {
        /* When the steps below require the UA to clear the list of active
        formatting elements up to the last marker, the UA must perform the
        following steps: */

        while(true) {
            /* 1. Let entry be the last (most recently added) entry in the list
            of active formatting elements. */
            $entry = end($this->a_formatting);

            /* 2. Remove entry from the list of active formatting elements. */
            array_pop($this->a_formatting);

            /* 3. If entry was a marker, then stop the algorithm at this point.
            The list has been cleared up to the last marker. */
            if($entry === self::MARKER) {
                break;
            }
        }
    }


            $ret .= $this->end('textarea');
        } else {
            $attr['value'] = $value;
            $attr['type'] = 'text';
            $ret .= $this->elementEmpty('input', $attr);
        }
        return $ret;
    }


    protected function renderDoctype() {
        $doctype = $this->def->doctype;
        $ret = '';
        $ret .= $this->start('table');
        $ret .= $this->element('caption', 'Doctype');
        $ret .= $this->row('Name', $doctype->name);
        $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No');
        $ret .= $this->row('Default Modules', implode($doctype->modules, ', '));
        $ret .= $this->row('Default Tidy Modules', implode($doctype->tidyModules, ', '));
        $ret .= $this->end('table');
        return $ret;
    }


    public function parseMultiFile($file) {
        if (!file_exists($file)) return false;
        $ret = array();
        $fh = fopen($file, 'r');
        if (!$fh) return false;
        while (!feof($fh)) {
            $ret[] = $this->parseHandle($fh);
        }
        fclose($fh);
        return $ret;
    }


    public function __get($n) {
      if ($n === 'type') {
        trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);
        switch (get_class($this)) {
          case 'HTMLPurifier_Token_Start':      return 'start';
          case 'HTMLPurifier_Token_Empty':      return 'empty';
          case 'HTMLPurifier_Token_End':        return 'end';
          case 'HTMLPurifier_Token_Text':       return 'text';
          case 'HTMLPurifier_Token_Comment':    return 'comment';
          default: return null;
        }
      }
    }


    public function __construct($data, $line = null, $col = null) {
        $this->data = $data;
        $this->is_whitespace = ctype_space($data);
        $this->line = $line;
        $this->col  = $col;
    }


    public function filter(&$uri, $config, $context) {
        return !$context->get('EmbeddedURI', true);
    }


    public function parse($uri) {

        $uri = $this->percentEncoder->normalize($uri);

        // Regexp is as per Appendix B.
        // Note that ["<>] are an addition to the RFC's recommended
        // characters, because they represent external delimeters.
        $r_URI = '!'.
            '(([^:/?#"<>]+):)?'. // 2. Scheme
            '(//([^/?#"<>]*))?'. // 4. Authority
            '([^?#"<>]*)'.       // 5. Path
            '(\?([^#"<>]*))?'.   // 7. Query
            '(#([^"<>]*))?'.     // 8. Fragment
            '!';

        $matches = array();
        $result = preg_match($r_URI, $uri, $matches);

        if (!$result) return false; // *really* invalid URI

        // seperate out parts
        $scheme     = !empty($matches[1]) ? $matches[2] : null;
        $authority  = !empty($matches[3]) ? $matches[4] : null;
        $path       = $matches[5]; // always present, can be empty
        $query      = !empty($matches[6]) ? $matches[7] : null;
        $fragment   = !empty($matches[8]) ? $matches[9] : null;

        // further parse authority
        if ($authority !== null) {
            $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";
            $matches = array();
            preg_match($r_authority, $authority, $matches);
            $userinfo   = !empty($matches[1]) ? $matches[2] : null;
            $host       = !empty($matches[3]) ? $matches[3] : '';
            $port       = !empty($matches[4]) ? (int) $matches[5] : null;
        } else {
            $port = $host = $userinfo = null;
        }

        return new HTMLPurifier_URI(
            $scheme, $userinfo, $host, $port, $path, $query, $fragment);
    }


    public function validate(&$uri, $config, $context) {
        if ($this->default_port == $uri->port) $uri->port = null;
        // kludge: browsers do funny things when the scheme but not the
        // authority is set
        if (!$this->may_omit_host &&
            // if the scheme is present, a missing host is always in error
            (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) ||
            // if the scheme is not present, a *blank* host is in error,
            // since this translates into '///path' which most browsers
            // interpret as being 'http://path'.
             (is_null($uri->scheme) && $uri->host === '')
        ) {
            do {
                if (is_null($uri->scheme)) {
                    if (substr($uri->path, 0, 2) != '//') {
                        $uri->host = null;
                        break;
                    }
                    // URI is '////path', so we cannot nullify the
                    // host to preserve semantics.  Try expanding the
                    // hostname instead (fall through)
                }
                // first see if we can manually insert a hostname
                $host = $config->get('URI.Host');
                if (!is_null($host)) {
                    $uri->host = $host;
                } else {
                    // we can't do anything sensible, reject the URL.
                    return false;
                }
            } while (false);
        }
        return $this->doValidate($uri, $config, $context);
    }


    public function doValidate(&$uri, $config, $context) {
        $uri->userinfo = null;
        $uri->host     = null;
        $uri->port     = null;
        $uri->query    = null;
        // typecode check needed on path
        return true;
    }


    public function getScheme($scheme, $config, $context) {
        if (!$config) $config = HTMLPurifier_Config::createDefault();

        // important, otherwise attacker could include arbitrary file
        $allowed_schemes = $config->get('URI.AllowedSchemes');
        if (!$config->get('URI.OverrideAllowedSchemes') &&
            !isset($allowed_schemes[$scheme])
        ) {
            return;
        }

        if (isset($this->schemes[$scheme])) return $this->schemes[$scheme];
        if (!isset($allowed_schemes[$scheme])) return;

        $class = 'HTMLPurifier_URIScheme_' . $scheme;
        if (!class_exists($class)) return;
        $this->schemes[$scheme] = new $class();
        return $this->schemes[$scheme];
    }


    protected function error($msg) {
        throw new HTMLPurifier_VarParserException($msg);
    }


    public function popupnewsitem($id) {

                if(!is_numeric($id)){header('Location: '.url('/'));}

                $result = PopUpNewsData::popupnewsitem($id);
                Template::Set('item', $result);
                Template::Show('popupnews/popupnews_item.tpl');
        }

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')

The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.


		function verifyCSRFToken() {
			$clean_referer = str_replace(array("http://","https://"),"//",$_SERVER["HTTP_REFERER"]);
			$clean_domain = str_replace(array("http://","https://"),"//",DOMAIN);
			$token = isset($_POST[$this->CSRFTokenField]) ? $_POST[$this->CSRFTokenField] : $_GET[$this->CSRFTokenField];

			if (strpos($clean_referer, $clean_domain) !== 0 || $token != $this->CSRFToken) {
				$this->stop("Cross site request forgery detected.");
			}
		}


    private function mailPassthru($to, $subject, $body, $header, $params)
    {
        //Check overloading of mail function to avoid double-encoding
        if (ini_get('mbstring.func_overload') & 1) {
            $subject = $this->secureHeader($subject);
        } else {
            $subject = $this->encodeHeader($this->secureHeader($subject));
        }

        //Can't use additional_parameters in safe_mode, calling mail() with null params breaks
        //@link http://php.net/manual/en/function.mail.php
        if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
            $result = @mail($to, $subject, $body, $header);
        } else {
            $result = @mail($to, $subject, $body, $header, $params);
        }
        return $result;
    }


    public function couponCodeGetDataFromSession()
    {
        $coupon_code = $this->app->user_manager->session_get('coupon_code');
        if ($coupon_code and !$this->couponCodeCheckIfValid($coupon_code)) {
            //check if coupon is valid
            if (function_exists('coupons_delete_session')) {
                coupons_delete_session();
            }

            $this->coupon_data = false;
        } else {
            if (function_exists('coupon_get_by_code')) {
                $this->coupon_data = coupon_get_by_code($coupon_code);
            } else {
                $this->coupon_data = false;
            }
        }
        return $this->coupon_data;
    }

NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.


    public function couponCodeCheckIfValid($coupon_code)
    {
        if (function_exists('coupon_apply')) {
            //check if coupon is valid
            $coupon_valid = coupon_apply([
                'coupon_code' => $coupon_code,
                'coupon_check_if_valid' => true
            ]);
            if (!$coupon_valid) {
                return false;
            }
            return true;
        }
        return false;

    }


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

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


	public function testZipReader() {

        ImportLogger::clearLog();
        $zip = new ZipReader(__DIR__ . DS. 'strange-file.zip');
        $zip->readData();
        $zip->clearCache();
        $log = ImportLogger::getLog();

        $this->assertTrue((strpos($log, 'The zip file has no files.')!==false));

        ImportLogger::clearLog();
        Config::set('microweber.allow_php_files_upload', true);

        $zip = new ZipReader(__DIR__ . DS. 'strange-file.zip');
        $zip->readData();
        $zip->clearCache();

        $log = ImportLogger::getLog();

        $this->assertTrue((strpos($log, 'queue strange-file.php')!==false));
        $this->assertTrue((strpos($log, 'no files to import')!==false));

    }

Unrestricted Upload of File with Dangerous Type

The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.


    function get_allowed_files_extensions_for_upload($fileTypes = 'images')
    {

        $are_allowed = '';
        switch ($fileTypes) {

            case 'img':
            case 'image':
            case 'images':
                $are_allowed .= ',png,gif,jpg,jpeg,tiff,bmp,svg,webp,ico';
                break;
            case 'audio':
            case 'audios':
                $are_allowed .= ',mp3,mp4,ogg,wav,flac';
                break;
            case 'video':
            case 'videos':
                $are_allowed .= ',avi,asf,mpg,mpeg,mp4,flv,mkv,webm,ogg,ogv,3gp,3g2,wma,mov,wmv';
                break;
            case 'file':
            case 'files':
                $are_allowed .= ',doc,docx,pdf,html,js,css,htm,rtf,txt,zip,gzip,rar,cad,xml,psd,xlsx,csv,7z';
                break;
            case 'documents':
            case 'doc':
                $are_allowed .= ',doc,docx,pdf,log,msg,odt,pages,rtf,tex,txt,wpd,wps,pps,ppt,pptx,xml,htm,html,xlr,xls,xlsx';
                break;
            case 'archives':
            case 'arc':
            case 'arch':
                $are_allowed .= ',zip,zipx,gzip,rar,gz,7z,cbr,tar.gz';
                break;
            case 'all':
                $are_allowed .= ',*';
                break;
            case '*':
                $are_allowed .= ',*';
                break;
            default:
                $are_allowed .= ',' . $fileTypes;
        }

        if($are_allowed){
            $are_allowed = explode(',',$are_allowed);
            array_unique($are_allowed);
            $are_allowed = array_filter($are_allowed);
            $are_allowed = implode(',', $are_allowed);
        }

        return $are_allowed;
    }


private function _extract_file($compressed_file_name, $target_file_name = false, $underscore_case = false)
    {
        if (strpos($target_file_name,'..') !== false) {
            return false;
        }

        if (strpos($compressed_file_name,'..') !== false) {
            return false;
        }

        if (!sizeof($this->compressed_list)) {
            $this->set_debug('Trying to unzip before loading file list... Loading it!');
            $this->_list_files(false, $compressed_file_name);
        }

        $fdetails = &$this->compressed_list[$compressed_file_name];

        if (!isset($this->compressed_list[$compressed_file_name])) {
            $this->set_error('File "$compressed_file_name" is not compressed in the zip.');

            return false;
        }

        if (substr($compressed_file_name, -1) == '/') {
            $this->set_error('Trying to unzip a folder name "$compressed_file_name".');

            return false;
        }

        if (!$fdetails['uncompressed_size']) {
            $this->set_debug('File "$compressed_file_name" is empty.');

            return $target_file_name ? file_put_contents($target_file_name, '') : '';
        }

        if ($underscore_case) {
            $pathinfo = pathinfo($target_file_name);
            //  $pathinfo['filename_new'] = preg_replace('/([^.a-z0-9]+)/i', '_', strtolower($pathinfo['filename']));
            $pathinfo['filename_new'] = ($pathinfo['filename']);
            $target_file_name = $pathinfo['dirname'] . '/' . $pathinfo['filename_new'] . '.' . ($pathinfo['extension']);
        }

Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.


		function new_user() {
			global $db;
			$insert = $db->sql_query("INSERT INTO `mod_useronline` (`timestamp`, `ip`) VALUES ('$this->timestamp', '$this->ip')");
			if (!$insert) {
				$this->error[$this->i] = "Unable to record new visitor\r\n";
				$this->i ++;
			}
		}


function main_exifreaddata() {
  $jpeg = "\xff\xd8\xc9\x00\x03\x04\x03\xf8";
  $data_stream = "data://text/plain;base64," . base64_encode($jpeg);
  var_dump(exif_read_data($data_stream));
}

The software reads data past the end, or before the beginning, of the intended buffer.


function main_exifreaddata() {
  $jpeg = "\xff\xd8\xec\x00\x05\x58\x00\x17";
  $data_stream = "data://text/plain;base64," . base64_encode($jpeg);
  var_dump(exif_read_data($data_stream));
}


function make_fb_cs_list_map($size) {
  return str_repeat("\xfa\xfd", $size) . str_repeat("\xfc", $size);
}

The product does not properly control the amount of recursion which takes place,  consuming excessive resources, such as allocated memory or the program stack.


    public function getReplacementText()
    {
        return $this->replacementText;
    }


    public function __construct()
    {
        /* WARNING: This function is deprecated and will be made protected in a future
         * version of jBBCode. */
        $this->parseContent = true;
        $this->useOption = false;
        $this->nestLimit = -1;
        $this->elCounter = 0;
        $this->optionValidator = null;
        $this->bodyValidator = null;
    }


    public function setNestLimit($limit)
    {
        if(!is_int($limit) || ($limit <= 0 && -1 != $limit)) {
            throw new InvalidArgumentException("A nest limit must be a positive integer " .
                                               "or -1.");
        }
        $this->nestLimit = $limit;
        return $this;
    }


    public function __construct($tagName, $replacementText)
    {
        $this->tagName = $tagName;
        $this->replacementText = $replacementText;
    }


    public function setAttribute($attribute)
    {
        $this->attribute = $attribute;
    }


    public function getAttribute()
    {
        return $this->attribute;
    }


    public function getAsHTML()
    {
        return $this->treeRoot->getAsHTML();
    }


    public function getAsText()
    {
        return $this->treeRoot->getAsText();
    }


    protected function parseTagOpen(ElementNode $parent, Tokenizer $tokenizer)
    {

        if (!$tokenizer->hasNext()) {
            /* The [ that sent us to this state was just a trailing [, not the
             * opening for a new tag. Treat it as such. */
            $this->createTextNode($parent, '[');
            return $parent;
        }

        $next = $tokenizer->next();

        /* This while loop could be replaced by a recursive call to this same method,
         * which would likely be a lot clearer but I decided to use a while loop to
         * prevent stack overflow with a string like [[[[[[[[[...[[[.
         */
        while ('[' == $next) {
            /* The previous [ was just a random bracket that should be treated as text.
             * Continue until we get a non open bracket. */
            $this->createTextNode($parent, '[');
            if (!$tokenizer->hasNext()) {
                $this->createTextNode($parent, '[');
                return $parent;
            }
            $next = $tokenizer->next();
        }

        /* At this point $next is either ']' or plain text. */
        if (']' == $next) {
            $this->createTextNode($parent, '[');
            $this->createTextNode($parent, ']');
            return $parent;
        } else {
            /* $next is plain text... likely a tag name. */
            return $this->parseTag($parent, $tokenizer, $next);
        }
    }


    public function getAsHTML()
    {
        return $this->getValue();
    }


    public function getAsText()
    {
        return $this->getValue();
    }


    public function testOneTagWithSurroundingText()
    {
        $this->assertBBCodeOutput('buffer text [b]this is bold[/b] buffer text',
                                  'buffer text [b]this is bold[/b] buffer text');
    }


    public function testUnclosedTag()
    {

        $parser = new JBBCode\Parser();
        $parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
        $parser->addBBCode('verbatim', '{param}', false, false);

        $parser->parse('[verbatim]i wonder [b]what will happen[/verbatim]');
        $this->assertEquals('i wonder [b]what will happen', $parser->getAsHtml());
        $this->assertEquals('[verbatim]i wonder [b]what will happen[/verbatim]', $parser->getAsBBCode());
    }


    public function testSimpleNoParsing()
    {

        $parser = new JBBCode\Parser();
        $parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
        $parser->addBBCode('verbatim', '{param}', false, false);

        $parser->parse('[verbatim]plain text[/verbatim]');
        $this->assertEquals('plain text', $parser->getAsHtml());

        $parser->parse('[verbatim][b]bold[/b][/verbatim]');
        $this->assertEquals('[b]bold[/b]', $parser->getAsHtml());

    }


    public function testOneTag()
    {
        $tokenizer = new JBBCode\Tokenizer('[b]');
        $this->assertEquals('[', $tokenizer->next());
        $this->assertEquals('b', $tokenizer->next());
        $this->assertEquals(']', $tokenizer->next());
        $this->assertFalse($tokenizer->hasNext());
    }


    public function testInvalidCssColor()
    {
        $colorValidator = new JBBCode\validators\CssColorValidator();
        $this->assertFalse($colorValidator->validate('" onclick="javascript: alert(\"gotcha!\");'));
        $this->assertFalse($colorValidator->validate('"><marquee scrollamount="100'));
    }


            } elseif (strtolower($val)=='now()') {
                $w .= "`$key` = NOW(), ";
            } else {
                if (strpos($key,'.') === false) {
                    $w .= "`$key` = '".$this->escape($val)."' AND ";
                } else {
                    $w .= "$key = '".$this->escape($val)."' AND ";
                }
            }
        }


function curPage()
{
    parse_str(substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], "?")+1), $result);
    return $result['page'];
}


" . $frm->checkbox("ban_types[{$i}]", $i) . $frm->label($ipAdministrator->getBanTypeString($i, false), "ban_types[{$i}]", $i) . "
									(" . $ipAdministrator->getBanTypeString($i, true) . ")

				";
			}


function phpAds_SessionRegenerateId()
{
    global $session;

    $dal = new MAX_Dal_Admin_Session();

    if (!empty($_COOKIE['sessionID'])) {
        $dal->deleteSession($_COOKIE['sessionID']);
    }

    if (!empty($session['__authentic__'])) {
        $sessionId = phpAds_SessionGenerateId();
        $dal->storeSerializedSession(serialize($session), $sessionId);

        return $sessionId;
    }

    unset($_COOKIE['sessionID']);

    return phpAds_SessionStart();
}

Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.


function phpAds_SessionGenerateId()
{
    $_COOKIE['sessionID'] = md5(uniqid('phpads', 1));

    phpAds_SessionSetAdminCookie('sessionID', $_COOKIE['sessionID']);

    return $_COOKIE['sessionID'];
}


    function logon($username, $password, &$sessionId)
    {
        global $_POST, $_COOKIE;
        global $strUsernameOrPasswordWrong;

        /**
         * @todo Please check if the following statement is in correct place because
         * it seems illogical that user can get session ID from internal login with
         * a bad username or password.
         */

        if (!$this->_verifyUsernameAndPasswordLength($username, $password)) {
            return false;
        }

        $_POST['username'] = $username;
        $_POST['password'] = $password;

        $_POST['login'] = 'Login';

        unset($_COOKIE['sessionID']);
        phpAds_SessionStart();
        $_POST['phpAds_cookiecheck'] = $_COOKIE['sessionID'];

        $this->preInitSession();
        if ($this->_internalLogin($username, $password)) {
            // Check if the user has administrator access to Openads.
            if (OA_Permission::isUserLinkedToAdmin()) {

                $this->postInitSession();

                $sessionId = $_COOKIE['sessionID'];
                return true;
            } else {

                $this->raiseError('User must be OA installation admin');
                return false;
            }
        } else {

            $this->raiseError($strUsernameOrPasswordWrong);
            return false;
        }
    }


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


    function __construct()
    {
        $this->_useDefaultDal();

        $this->csrf_token    = phpAds_SessionGetToken();
        $this->advertiser_id = MAX_getValue('clientid', 0);
        $this->tracker_id    = MAX_getValue('trackerid', 0);
        $this->assetPath 	 = OX::assetPath();
        $this->showReminder  = false;
    }


    function _log($local_path, $remote_path, $error) {
        $data = sprintf("[%s] [%s => %s] %s\n", date('r'), $local_path, $remote_path, $error);
        $data = strtr($data, '<>', '..');

        $filename = w3_debug_log('cdn');

        return @file_put_contents($filename, $data, FILE_APPEND);
    }


    public function run()
    {
        if ($this->user->isCurrentUser() || \Yii::$app->user->isGuest) {
            return;
        }

        // Add class for javascript handling
        $this->followOptions['class'] .= ' followButton';
        $this->unfollowOptions['class'] .= ' unfollowButton';

        // Hide inactive button
        if ($this->user->isFollowedByUser()) {
            $this->followOptions['style'] .= ' display:none;';
        } else {
            $this->unfollowOptions['style'] .= ' display:none;';
        }

        // Add UserId Buttons
        $this->followOptions['data-content-container-id'] = $this->user->id;
        $this->unfollowOptions['data-content-container-id'] = $this->user->id;

        // Add JS Action
        $this->followOptions['data-action-click'] = 'content.container.follow';
        $this->unfollowOptions['data-action-click'] = 'content.container.unfollow';

        // Add Action Url
        $this->followOptions['data-action-url'] = $this->user->createUrl('/user/profile/follow');
        $this->unfollowOptions['data-action-url'] = $this->user->createUrl('/user/profile/unfollow');

        // Add Action Url
        $this->followOptions['data-ui-loader'] = '';
        $this->unfollowOptions['data-ui-loader'] = '';

        // Confirm action "Unfollow"
        $this->unfollowOptions['data-action-confirm'] = Yii::t('SpaceModule.base', 'Would you like to unfollow {userName}?', [
            '{userName}' => '<strong>' . Html::encode($this->user->getDisplayName()) . '</strong>'
        ]);

        $module = Yii::$app->getModule('user');

        // still enable unfollow if following was disabled afterwards.
        if ($module->disableFollow) {
            return Html::a($this->unfollowLabel, '#', $this->unfollowOptions);
        }

        return Html::a($this->unfollowLabel, '#', $this->unfollowOptions) .
                Html::a($this->followLabel, '#', $this->followOptions);
    }


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

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

        return $drop;
    }


    public function __construct () {
        global $vars;
        if(DB_DRIVER == 'mysql') {
            mysql_connect(DB_HOST, DB_USER, DB_PASS);
            mysql_select_db(DB_NAME);
        }elseif(DB_DRIVER == 'mysqli') {
            try {
                self::$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
                if (self::$mysqli->connect_error) {
                    Control::error('db', self::$mysqli->connect_error);
                    exit;
                }else{
                    return true;
                }
            } catch (exception $e) {
                Control::error('db', $e->getMessage() );
            }

            //return self::$mysqli;
        }
    }


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

        return $desc;
    }


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

    }


    public function __construct () {

    }


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

        $newtoken = json_encode($newtoken);
        return $newtoken;
    }


    public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){
        $filename = Typo::cleanX($_FILES[$input]['name']);
        $filename = str_replace(' ', '_', $filename);
        if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){
            if($uniq == true){
                $uniqfile = sha1(microtime().$filename);
            }else{
                $uniqfile = '';
            }

            $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);
            $filetmp = $_FILES[$input]['tmp_name'];
            $filepath = GX_PATH.$path.$uniqfile.$filename;

            if(!in_array(strtolower($extension), $allowed)){
                $result['error'] = 'File not allowed';
            }else{
                if(move_uploaded_file(
                    $filetmp,
                    $filepath)
                ){
                    $result['filesize'] = filesize($filepath);
                    $result['filename'] = $uniqfile.$filename;
                    $result['path'] = $path.$uniqfile.$filename;
                    $result['filepath'] = $filepath;
                    $result['fileurl'] = Site::$url.$path.$uniqfile.$filename;

                }else{
                    $result['error'] = 'Cannot upload to directory, please check
                    if directory is exist or You had permission to write it.';
                }
            }

        }else{
            //$result['error'] = $_FILES[$input]['error'];
             $result['error'] = '';
        }

        return $result;

    }


    public static function post($vars) {
        switch (SMART_URL) {
            case true:
                # code...
                $url = Site::$url."/".self::slug($vars)."/{$vars}";
                break;

            default:
                # code...
                $url = Site::$url."/index.php?post={$vars}";
                break;

        }

        return $url;
    }


    public static function rss() {
        switch (SMART_URL) {
            case true:
                # code...
                $url = Site::$url."/rss".GX_URL_PREFIX;
                break;

            default:
                # code...
                $url = Site::$url."/index.php?rss";
                break;

        }

        return $url;
    }


    public static function id($name)
    {
        $name = sprintf('%s', $name);
        if (isset($name)) {
            $cat = Db::result("SELECT `id` FROM `cat`
                                WHERE `name` = '{$name}' LIMIT 1");
            // print_r($cat);
            if (isset($cat['error'])) {
                return '';
            } else {
                return $cat[0]->id;
            }
        } else {
            echo 'No ID Selected';
        }

        //print_r($cat);
    }


    public static function ajax($vars = '', $val = '')
    {
        if (isset($vars) && $vars != '') {
            $file = GX_PATH.'/inc/lib/Control/Ajax/'.$vars.'-ajax.control.php';
            if (file_exists($file)) {
                include $file;
            } else {
                self::error('404');
            }
        }
    }


                } elseif ($k == 'lang') {
                    self::incFront('default');
                } elseif ($k == 'error') {


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

        return $vars;
    }


    public static function connect(
        $dbhost = DB_HOST,
        $dbuser = DB_USER,
        $dbpass = DB_PASS,
        $dbname = DB_NAME
    ) {
        self::$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

        if (self::$mysqli->connect_error) {
            return false;
        } else {
            return true;
        }
    }


            $file = explode('.', $lang);
            if ($var == $file[0]) {
                $sel = 'SELECTED';
            } else {
                $sel = '';
            }
            $opt .= "<option {$sel}>{$file[0]}</option>";
        }

        return $opt;
    }


    public static function getParent($id)
    {
        $q = self::getId($id);

        return $q[0]->parent;
    }


    public static function activate($mod)
    {
        $json = Options::v('modules');
        $mods = json_decode($json, true);
        //print_r($mods);
        if (!is_array($mods) || $mods == '') {
            $mods = array();
        }
        if (!in_array($mod, $mods)) {
            # code...
            $mods = array_merge($mods, array($mod));
        }

        $mods = json_encode($mods);

        $mods = Options::update('modules', $mods);
        if ($mods) {
            new Options();

            return true;
        } else {
            return false;
        }
    }


    public static function is_on()
    {
        $on = Options::v('pinger_enable');
        if ($on == 'on') {
            return true;
        } else {
            return false;
        }
    }


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

            if (Pinger::is_on()) {
                $pinger = Options::v('pinger');
                Pinger::run($pinger);
            }
        }

        return $post;
    }


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

        return $drop;
    }


    public static function getFolder()
    {
        $uri = explode('/', Site::$url);

        if (count($uri) > 3) {
            unset($uri[0]);
            unset($uri[1]);
            unset($uri[2]);

            $uri = array_values($uri);

            $uris = '';
            for ($i = 0; $i < count($uri); ++$i) {
                $uris .= '/'.$uri[$i];
            }

            return $uris;
        } else {
            return '/';
        }
    }


    private static function sesKey()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $browser = $_SERVER['HTTP_USER_AGENT'];
        $dt = date('Y-m-d H');

        $key = md5($ip.$browser.$dt);

        return $key;
    }


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

        return $desc;
    }


    public static function versionCheck()
    {
        $v = trim(self::latestVersion());

        // print_r($v);
        $v = str_replace('.', '', $v);
        $selfv = str_replace('.', '', self::$version);
        if ($v > $selfv) {
            Hooks::attach('admin_page_notif_action', array('System', 'versionReport'));
        }
    }


    public static function getLatestVersion($now)
    {
        $v = file_get_contents('https://raw.githubusercontent.com/semplon/GeniXCMS/master/VERSION');

        $arr = array(
                'version' => trim($v),
                'last_check' => $now,
            );
        $arr = json_encode($arr);

        Options::update('system_check', $arr);

        return $v;
    }


    public static function add($tags)
    {
        $tag = explode(',', $tags);

        for ($i = 0; $i < count($tag); ++$i) {
            // echo($i);
            $tag_i = Typo::cleanX($tag[$i]);
            // echo $tag[$i];
            $exist = self::exist($tag_i);
            if (!$exist) {
                if ($tag_i != '') {
                    $slug = Typo::slugify($tag_i);
                    $cat = $tag_i;
                    Db::insert(
                        sprintf(
                            "INSERT INTO `cat` VALUES (null, '%s', '%s', '%d', '', 'tag' )",
                            $cat,
                            $slug,
                            0
                        )
                    );
                }
            }
        }
    }


    public static function getParent($id = '')
    {
        return Categories::getParent($id);
    }


    public static function inc($var, $data = '')
    {
        self::theme($var, $data);
    }


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


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


    public static function ajax($vars)
    {
        switch (SMART_URL) {
            case true:
                # code...
                $inFold = (Options::v('permalink_use_index_php') == 'on') ? '/index.php' : '';
                $url = Site::$url.$inFold.'/ajax/'.$vars.'?token='.TOKEN;
                break;

            default:
                # code...
                $url = Site::$url."/?ajax={$vars}&token=".TOKEN;
                break;
        }

        return $url;
    }


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

        return $pass;
    }


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

        return $v;
    }


    public static function access($grp = '4')
    {
        if (isset($_SESSION['gxsess']['val']['group'])) {
            if ($_SESSION['gxsess']['val']['group'] <= $grp) {
                return true;
            } else {
                return false;
            }
        }
    }


    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 is_email($vars)
    {
        if (isset($_GET['act']) && $_GET['act'] == 'edit') {
            $id = Typo::int($_GET['id']);
            $where = "AND `id` != '{$id}' ";
        } else {
            $where = '';
        }
        $vars = sprintf('%s', Typo::cleanX($vars));
        $sql = sprintf("SELECT * FROM `user` WHERE `email` = '%s' %s", $vars, $where);
        $e = Db::result($sql);
        if (Db::$num_rows > 0) {
            return false;
        } else {
            return true;
        }
    }


    public static function deactivate($id)
    {
        $act = Db::query(
            sprintf(
                "UPDATE `user` SET `status` = '0' WHERE `id` = '%d'",
                Typo::int($id)
            )
        );
        if ($act) {
            return true;
        } else {
            return false;
        }
    }


    private function createSink(StreamInterface $stream, array $options)
    {
        if (!empty($options['stream'])) {
            return $stream;
        }

        $sink = isset($options['sink'])
            ? $options['sink']
            : fopen('php://temp', 'r+');

        return is_string($sink)
            ? new Psr7\LazyOpenStream($sink, 'w+')
            : Psr7\stream_for($sink);
    }


    private function createResponse(
        RequestInterface $request,
        array $options,
        $stream,
        $startTime
    ) {
        $hdrs = $this->lastHeaders;
        $this->lastHeaders = [];
        $parts = explode(' ', array_shift($hdrs), 3);
        $ver = explode('/', $parts[0])[1];
        $status = $parts[1];
        $reason = isset($parts[2]) ? $parts[2] : null;
        $headers = \GuzzleHttp\headers_from_lines($hdrs);
        list ($stream, $headers) = $this->checkDecode($options, $headers, $stream);
        $stream = Psr7\stream_for($stream);
        $sink = $stream;

        if (strcasecmp('HEAD', $request->getMethod())) {
            $sink = $this->createSink($stream, $options);
        }

        $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);

        if (isset($options['on_headers'])) {
            try {
                $options['on_headers']($response);
            } catch (\Exception $e) {
                $msg = 'An error was encountered during the on_headers event';
                $ex = new RequestException($msg, $request, $response, $e);
                return new RejectedPromise($ex);
            }
        }

        // Do not drain when the request is a HEAD request because they have
        // no body.
        if ($sink !== $stream) {
            $this->drain(
                $stream,
                $sink,
                $response->getHeaderLine('Content-Length')
            );
        }

        $this->invokeStats($options, $request, $startTime, $response, null);

        return new FulfilledPromise($response);
    }


function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
    $data = \json_decode($json, $assoc, $depth, $options);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_decode error: ' . json_last_error_msg());
    }

    return $data;
}


    public function withCookieParams(array $cookies)
    {
        $new = clone $this;
        $new->cookieParams = $cookies;

        return $new;
    }


    public function getQueryParams()
    {
        return $this->queryParams;
    }


    private function isStringOrNull($param)
    {
        return in_array(gettype($param), ['string', 'NULL']);
    }


    private function filterPort($port)
    {
        if ($port === null) {
            return null;
        }

        $port = (int) $port;
        if (1 > $port || 0xffff < $port) {
            throw new \InvalidArgumentException(
                sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
            );
        }

        return self::isNonStandardPort($this->scheme, $port) ? $port : null;
    }


    private function applyParts(array $parts)
    {
        $this->scheme = isset($parts['scheme'])
            ? $this->filterScheme($parts['scheme'])
            : '';
        $this->userInfo = isset($parts['user']) ? $parts['user'] : '';
        $this->host = isset($parts['host'])
            ? $this->filterHost($parts['host'])
            : '';
        $this->port = isset($parts['port'])
            ? $this->filterPort($parts['port'])
            : null;
        $this->path = isset($parts['path'])
            ? $this->filterPath($parts['path'])
            : '';
        $this->query = isset($parts['query'])
            ? $this->filterQueryAndFragment($parts['query'])
            : '';
        $this->fragment = isset($parts['fragment'])
            ? $this->filterQueryAndFragment($parts['fragment'])
            : '';
        if (isset($parts['pass'])) {
            $this->userInfo .= ':' . $parts['pass'];
        }
    }


    public function withHost($host)
    {
        $host = $this->filterHost($host);

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

        $new = clone $this;
        $new->host = $host;
        return $new;
    }


    public function testParsesRequestMessagesWithCustomMethod()
    {
        $req = "GET_DATA / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
        $request = Psr7\parse_request($req);
        $this->assertEquals('GET_DATA', $request->getMethod());
    }


    public function testValidateRequestUri()
    {
        new Request('GET', '///');
    }


    public function testWithStatusCodeAndReason()
    {
        $r = (new Response())->withStatus(201, 'Foo');
        $this->assertSame(201, $r->getStatusCode());
        $this->assertSame('Foo', $r->getReasonPhrase());

        $r = (new Response())->withStatus(201, '0');
        $this->assertSame(201, $r->getStatusCode());
        $this->assertSame('0', $r->getReasonPhrase(), 'Falsey reason works');
    }


    public function testWithAddedHeader()
    {
        $r = new Response(200, ['Foo' => 'Bar']);
        $r2 = $r->withAddedHeader('foO', 'Baz');
        $this->assertSame(['Foo' => ['Bar']], $r->getHeaders());
        $this->assertSame(['Foo' => ['Bar', 'Baz']], $r2->getHeaders());
        $this->assertSame('Bar, Baz', $r2->getHeaderLine('foo'));
        $this->assertSame(['Bar', 'Baz'], $r2->getHeader('foo'));
    }


    public function testUploadedFiles()
    {
        $request1 = new ServerRequest('GET', '/');

        $files = [
            'file' => new UploadedFile('test', 123, UPLOAD_ERR_OK)
        ];

        $request2 = $request1->withUploadedFiles($files);

        $this->assertNotSame($request2, $request1);
        $this->assertSame([], $request1->getUploadedFiles());
        $this->assertSame($files, $request2->getUploadedFiles());
    }


    public function testAddAndRemoveQueryValues()
    {
        $uri = new Uri();
        $uri = Uri::withQueryValue($uri, 'a', 'b');
        $uri = Uri::withQueryValue($uri, 'c', 'd');
        $uri = Uri::withQueryValue($uri, 'e', null);
        $this->assertSame('a=b&c=d&e', $uri->getQuery());

        $uri = Uri::withoutQueryValue($uri, 'c');
        $this->assertSame('a=b&e', $uri->getQuery());
        $uri = Uri::withoutQueryValue($uri, 'e');
        $this->assertSame('a=b', $uri->getQuery());
        $uri = Uri::withoutQueryValue($uri, 'a');
        $this->assertSame('', $uri->getQuery());
    }


    public function testImmutability()
    {
        $uri = new Uri();

        $this->assertNotSame($uri, $uri->withScheme('https'));
        $this->assertNotSame($uri, $uri->withUserInfo('user', 'pass'));
        $this->assertNotSame($uri, $uri->withHost('example.com'));
        $this->assertNotSame($uri, $uri->withPort(8080));
        $this->assertNotSame($uri, $uri->withPath('/path/123'));
        $this->assertNotSame($uri, $uri->withQuery('q=abc'));
        $this->assertNotSame($uri, $uri->withFragment('test'));
    }


    public function testWithQueryEncodesProperly()
    {
        $uri = (new Uri())->withQuery('?=#&€=/&b%61r');
        // A query starting with a "?" is valid and must not be magically removed. Otherwise it would be impossible to
        // construct such an URI. Also the "?" and "/" does not need to be encoded in the query.
        $this->assertSame('?=%23&%E2%82%AC=/&b%61r', $uri->getQuery());
        $this->assertSame('??=%23&%E2%82%AC=/&b%61r', (string) $uri);
    }


    public function testPathMustHaveCorrectType()
    {
        (new Uri())->withPath([]);
    }


    public function testUriComponentsGetEncodedProperly($input, $path, $query, $fragment, $output)
    {
        $uri = new Uri($input);
        $this->assertSame($path, $uri->getPath());
        $this->assertSame($query, $uri->getQuery());
        $this->assertSame($fragment, $uri->getFragment());
        $this->assertSame($output, (string) $uri);
    }


    public function testRemoveExtraSlashesWihoutHost()
    {
        // If the path is starting with more than one "/" and no authority is
        // present, the starting slashes MUST be reduced to one.
        $uri = (new Uri)->withPath('//foo');
        $this->assertSame('//foo', $uri->getPath());
        // URI "//foo" would be interpreted as network reference and thus change the original path to the host
        $this->assertSame('/foo', (string) $uri);
    }


    public function testCanConstructFalseyUriParts()
    {
        $uri = (new Uri())
            ->withScheme('0')
            ->withUserInfo('0', '0')
            ->withHost('0')
            ->withPath('/0')
            ->withQuery('0')
            ->withFragment('0');

        $this->assertSame('0', $uri->getScheme());
        $this->assertSame('0:0@0', $uri->getAuthority());
        $this->assertSame('0:0', $uri->getUserInfo());
        $this->assertSame('0', $uri->getHost());
        $this->assertSame('/0', $uri->getPath());
        $this->assertSame('0', $uri->getQuery());
        $this->assertSame('0', $uri->getFragment());
        $this->assertSame('0://0:0@0/0?0#0', (string) $uri);
    }


    function handleError($errorCode, $errorMessage)
    {
        $this->error = new Error($errorCode, $errorMessage);

        return false;
    }


    function query()
    {
        // Prepare multicall, then call the parent::query() method
        return parent::query('system.multicall', $this->calls);
    }


    function __construct($server, $path = false, $port = 80)
    {
        parent::__construct($server, $path, $port);
        $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
    }


    function __construct($server, $path = false, $port = 443, $timeout = false, $timeout_io = null)
    {
        parent::__construct($server, $path, $port, $timeout, $timeout_io);
        $this->useragent = 'The Incutio XML-RPC PHP Library for SSL';

        // Set class fields
        $this->_certFile = false;
        $this->_caFile = false;
        $this->_keyFile = false;
        $this->_passphrase = '';
    }


    function __construct($code, $message)
    {
        $this->code = $code;
        $this->message = htmlspecialchars($message);
    }


    function serve($data = false)
    {
        if (!$data) {
            if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
                header('Content-Type: text/plain'); // merged from WP #9093
                throw new ServerException('XML-RPC server accepts POST requests only.');
            }

            $data = file_get_contents('php://input');
        }
        $this->message = new Message($data);
        if (!$this->message->parse()) {
            $this->error(-32700, 'parse error. not well formed');
        }
        if ($this->message->messageType != 'methodCall') {
            $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
        }
        $result = $this->call($this->message->methodName, $this->message->params);

        // Is the result an error?
        if ($result instanceof Error) {
            $this->error($result);
        }

        // Encode the result
        $r = new Value($result);
        $resultxml = $r->getXml();

        // Create the XML
        $xml = <<<EOD
<methodResponse>
  <params>
    <param>
      <value>
      $resultxml
      </value>
    </param>
  </params>
</methodResponse>

EOD;
        // Send it
        $this->output($xml);
    }


    function __construct($callbacks = false, $data = false, $wait = false)
    {
        $this->setCapabilities();
        if ($callbacks) {
            $this->callbacks = $callbacks;
        }
        $this->setCallbacks();
        if (!$wait) {
            $this->serve($data);
        }
    }


    public function getSupportedBrands()
    {
        return $this->supported_cards;
    }


	private function getTempDir($volumeTempPath = null) {
		$testDirs = array();
		if ($this->uploadTempPath) {
			$testDirs[] = rtrim(realpath($this->uploadTempPath), DIRECTORY_SEPARATOR);
		}
		if ($volumeTempPath) {
			$testDirs[] = rtrim(realpath($volumeTempPath), DIRECTORY_SEPARATOR);
		}
		if (function_exists('sys_get_temp_dir')) {
			$testDirs[] = sys_get_temp_dir();
		}
		$tempDir = '';
		foreach($testDirs as $testDir) {
			if (!$testDir || !is_dir($testDir)) continue;
			if (is_writable($testDir)) {
				$tempDir = $testDir;
				$gc = time() - 3600;
				foreach(glob($tempDir . DIRECTORY_SEPARATOR .'ELF*') as $cf) {
					if (filemtime($cf) < $gc) {
						unlink($cf);
					}
				}
				break;
			}
		}
		return $tempDir;
	}


    protected function init()
    {
        if (empty($this->options['icon'])) {
            $this->options['icon'] = true;
        }
        if ($res = parent::init()) {
            if ($this->options['icon'] === true) {
                unset($this->options['icon']);
            }
        }
        return $res;
    }


	public function rename($hash, $name) {
		if ($this->commandDisabled('rename')) {
			return $this->setError(elFinder::ERROR_PERM_DENIED);
		}

		if (!$this->nameAccepted($name)) {
			return $this->setError(elFinder::ERROR_INVALID_NAME, $name);
		}

		$mimeByName = elFinderVolumeDriver::mimetypeInternalDetect($name);
		if ($mimeByName && $mimeByName !== 'unknown' && !$this->allowPutMime($mimeByName)) {
			return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME, $name);
		}

		if (!($file = $this->file($hash))) {
			return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
		}

		if ($name == $file['name']) {
			return $file;
		}

		if (!empty($file['locked'])) {
			return $this->setError(elFinder::ERROR_LOCKED, $file['name']);
		}

		$path = $this->decode($hash);
		$dir  = $this->dirnameCE($path);
		$stat = $this->stat($this->joinPathCE($dir, $name));
		if ($stat) {
			return $this->setError(elFinder::ERROR_EXISTS, $name);
		}

		if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
			return $this->setError(elFinder::ERROR_PERM_DENIED);
		}

		$this->rmTmb($file); // remove old name tmbs, we cannot do this after dir move

		if ($path = $this->convEncOut($this->_move($this->convEncIn($path), $this->convEncIn($dir), $this->convEncIn($name)))) {
			$this->clearcache();
			return $this->stat($path);
		}
		return false;
	}


	protected function gdImageCreate($path,$mime) {
		switch($mime) {
			case 'image/jpeg':
			return imagecreatefromjpeg($path);

			case 'image/png':
			return imagecreatefrompng($path);

			case 'image/gif':
			return imagecreatefromgif ($path);

			case 'image/x-ms-bmp':
			if (!function_exists('imagecreatefrombmp')) {
				include_once dirname(__FILE__).'/libs/GdBmp.php';
			}
			return imagecreatefrombmp($path);

			case 'image/xbm':
			return imagecreatefromxbm($path);

			case 'image/xpm':
			return imagecreatefromxpm($path);
		}
		return false;
	}


	protected function canCreateTmb($path, $stat, $checkTmbPath = true) {
		if ((! $checkTmbPath || $this->tmbPathWritable)
			&& (! $this->tmbPath || strpos($path, $this->tmbPath) === false) // do not create thumnbnail for thumnbnail
		) {
			$mime = strtolower($stat['mime']);
			list($type) = explode('/', $mime);
			if (! empty($this->imgConverter)) {
				if (isset($this->imgConverter[$mime])) {
					return true;
				}
				if (isset($this->imgConverter[$type])) {
					return true;
				}
			}
			return $this->imgLib
				&& ($type === 'image')
				&& ($this->imgLib == 'gd' ? in_array($stat['mime'], array('image/jpeg', 'image/png', 'image/gif', 'image/x-ms-bmp')) : true);
		}
		return false;
	}


	public function duplicate($hash, $suffix='copy') {
		if ($this->commandDisabled('duplicate')) {
			return $this->setError(elFinder::ERROR_COPY, '#'.$hash, elFinder::ERROR_PERM_DENIED);
		}

		if (($file = $this->file($hash)) == false) {
			return $this->setError(elFinder::ERROR_COPY, elFinder::ERROR_FILE_NOT_FOUND);
		}

		$path = $this->decode($hash);
		$dir  = $this->dirnameCE($path);
		$name = $this->uniqueName($dir, $file['name'], sprintf($this->options['duplicateSuffix'], $suffix));

		if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
			return $this->setError(elFinder::ERROR_PERM_DENIED);
		}

		return ($path = $this->copy($path, $dir, $name)) == false
			? false
			: $this->stat($path);
	}