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

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


    private function dumpParameter($name)
    {
        if ($this->container->isCompiled() && $this->container->hasParameter($name)) {
            $value = $this->container->getParameter($name);
            $dumpedValue = $this->dumpValue($value, false);

            if (!$value || !\is_array($value)) {
                return $dumpedValue;
            }

            if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
                return sprintf("\$this->parameters['%s']", $name);
            }
        }

        return sprintf("\$this->getParameter('%s')", $name);
    }

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.


    public function withQuery($query)
    {
        if (!is_string($query) && !method_exists($query, '__toString')) {
            throw new \InvalidArgumentException(
                'Query string must be a string'
            );
        }

        $query = (string) $query;
        if (substr($query, 0, 1) === '?') {
            $query = substr($query, 1);
        }

        $query = $this->filterQueryAndFragment($query);

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

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


	public function test_create_nonce_url() {
        $url = yourls_nonce_url( rand_str(), rand_str(), rand_str(), rand_str() );
        $this->assertTrue( is_string($url) );
        // $this->assertIsString($url);
    }

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 ac_sigleme($str, $name, $id) {
        global $cms_db, $sess;

        $sess->gc( true );
	    if( $id >= 1 && $this->session_enabled ) {
            $this->db->query(sprintf("delete from %s where name = '%s' and sid != '%s' and user_id = '%s'",
                $cms_db[sessions],
                addslashes($name),
                $str,
                $id));
        }
    }


	static public function editCategory($_category = null, $_id = 0, $_order = 1)
	{
		if ($_category != null && $_category != '' && $_id != 0) {
			if ($_order < 1) {
				$_order = 1;
			}

			$upd_stmt = Database::prepare("
				UPDATE `" . TABLE_PANEL_TICKET_CATS . "` SET
					`name` = :name,
					`logicalorder` = :lo
                  WHERE `id` = :id
			");
			Database::pexecute($upd_stmt, array(
				'name' => $_category,
				'lo' => $_order,
				'id' => $_id
			));
			return true;
		}
		return false;
	}

Incorrect Permission Assignment for Critical Resource

The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.


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

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

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 passwordvisit_input_password(&$template)
{
    global $zbp;
    if (isset($_POST['password']) && $_POST['password'] != '') {
        $article = $template->GetTags('article');
        if ($article->Metas->passwordvisit_password != '') {
            if (GetVars('password', 'POST') == $article->Metas->passwordvisit_password) {
                return;
            } else {
                echo '<script type="text/javascript">alert("密码错误，请重新输入！");window.location="' . $article->Url . '";</script>';
                die();
            }
        } else {
            if (GetVars('password', 'POST') == $zbp->Config('passwordvisit')->default_password) {
                return;
            } else {
                echo '<script type="text/javascript">alert("密码错误，请重新输入！");window.location="' . $article->Url . '";</script>';
                die();
            }
        }
    } else {
        $article = $template->GetTags('article');
        if ($zbp->Config('passwordvisit')->all_encrypt || $article->Metas->passwordvisit_enable_encrypt) {
            $article->Content = $zbp->Config('passwordvisit')->default_text . '<form id="form1" name="form1" method="post"><input name="password" type="password" width="100px" /><input name="submit" type="submit" value="查看"/></form>';
            $template->SetTags('article', $article);
        }
    }
}

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.


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

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

		assign_to_template(array(
            'purchase_orders'=>$purchase_orders,
            'vendors' => $vendors,
            'vendor_id' => @$this->params['vendor']
        ));
	}


	function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}

		return $records;
	}


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

//        eDebug($files,true);
    }


	public static function extendTimeLimit($time = null) {
		static $defLimit = null;
		if (is_null($defLimit)) {
			$defLimit = ini_get('max_execution_time');
		}
		if ($defLimit != 0) {
			$time = is_null($time)? $defLimit : max($defLimit, $time);
			set_time_limit($time);
		}
	}


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

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

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

Authorization Bypass Through User-Controlled Key

The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.


    public function testSerializeCleanupSocket()
    {
        $this->socket->expects($this->at(0))->method('connect')->will($this->returnValue(true));
        $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
        $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n");
        $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 OK\r\n"));

        $smtpTransport = new SmtpTestTransport();
        $smtpTransport->setSocket($this->socket);
        $smtpTransport->connect();

        $result = unserialize(serialize($smtpTransport));
        $this->assertAttributeEquals(null, '_socket', $result);
        $this->assertFalse($result->connected());
    }

The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.


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

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


function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
{
	// List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
	// Char '>' '<' '|' '$' and ';' are special chars for shells.
	// Char '/' and '\' are file delimiters.
	$filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
	return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
}

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.


	public function delete_version() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // get the version
	    $version = new help_version($this->params['id']);
	    if (empty($version->id)) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // if we have errors than lets get outta here!
	    if (!expQueue::isQueueEmpty('error')) expHistory::back();

	    // delete the version
	    $version->delete();

	    expSession::un_set('help-version');

	    flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));
	    expHistory::back();
	}


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

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

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

        return $comment;
    }

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.


    function fopen($filename, $mode)
    {
        if (\yiiunit\framework\base\SecurityTest::$fopen !== null) {
            return \yiiunit\framework\base\SecurityTest::$fopen;
        }

        return \fopen($filename, $mode);
    }

The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.


            return $this->mainPhase($token);
        }
    }

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.


                    $sort    = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';
                    $array[] = $this->parseKey($key, true) . $sort;
                }
            }


	protected function LoadSize($blob)
	{
		if (!$blob)
			return;

		$args = array();
		$args[] = '-s';
		$args[] = escapeshellarg($blob->GetHash());

		return $this->exe->Execute($blob->GetProject()->GetPath(), GIT_CAT_FILE, $args);
	}

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

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


    function ac_checkme($id, $name) {
        global $cms_db;

        $ret = true;
        $cquery = sprintf("select count(*) from %s where sid='%s' and name='%s'",
            $cms_db['sessions'],
            addslashes($id),
            addslashes($name));
        $squery = sprintf("select sid from %s where sid  = '%s' and name = '%s'",
            $cms_db['sessions'],
            addslashes($id),
            addslashes($name));
        $this->db->query($squery);
        if ( $this->db->affected_rows() == 0
            && $this->db->query($cquery)
	        && $this->db->next_record() && $this->db->f(0) == 0 ) {
            // nothing found here
            $ret = false;
        }
        return $ret;
    }


    public function __toString()
    {
        return self::createUriString(
            $this->scheme,
            $this->getAuthority(),
            $this->path,
            $this->query,
            $this->fragment
        );
    }


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

Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')

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


    public function uriComponentsEncodingProvider()
    {
        $unreserved = 'a-zA-Z0-9.-_~!$&\'()*+,;=:@';

        return [
            // Percent encode spaces
            ['/pa th?q=va lue#frag ment', '/pa%20th', 'q=va%20lue', 'frag%20ment', '/pa%20th?q=va%20lue#frag%20ment'],
            // Percent encode multibyte
            ['/€?€#€', '/%E2%82%AC', '%E2%82%AC', '%E2%82%AC', '/%E2%82%AC?%E2%82%AC#%E2%82%AC'],
            // Don't encode something that's already encoded
            ['/pa%20th?q=va%20lue#frag%20ment', '/pa%20th', 'q=va%20lue', 'frag%20ment', '/pa%20th?q=va%20lue#frag%20ment'],
            // Percent encode invalid percent encodings
            ['/pa%2-th?q=va%2-lue#frag%2-ment', '/pa%252-th', 'q=va%252-lue', 'frag%252-ment', '/pa%252-th?q=va%252-lue#frag%252-ment'],
            // Don't encode path segments
            ['/pa/th//two?q=va/lue#frag/ment', '/pa/th//two', 'q=va/lue', 'frag/ment', '/pa/th//two?q=va/lue#frag/ment'],
            // Don't encode unreserved chars or sub-delimiters
            ["/$unreserved?$unreserved#$unreserved", "/$unreserved", $unreserved, $unreserved, "/$unreserved?$unreserved#$unreserved"],
            // Encoded unreserved chars are not decoded
            ['/p%61th?q=v%61lue#fr%61gment', '/p%61th', 'q=v%61lue', 'fr%61gment', '/p%61th?q=v%61lue#fr%61gment'],
        ];
    }


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


    public function testForBinExec($value)
    {
        if (substr($value, 0, 7) === "phar://") {
            return 'Phar protocol not allowed.';
        }
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        if ($value === '') {
            return true;
        }
        if (is_executable($value)) {
            if (finfo_file($finfo, $value) == "application/x-executable" || finfo_file($finfo, $value) == "application/x-sharedlib") {
                finfo_close($finfo);
                return true;
            } else {
                return 'Binary file not executable. It is of type: ' . finfo_file($finfo, $value);
            }
        } else {
            return false;
        }
    }


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


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


    public function addAllowedValues($key, $allowed) {
        $this->info[$key]->allowed = $allowed;
    }


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


    public static function load($mod)
    {
        $file = GX_MOD.'/'.$mod.'/index.php';
        if (file_exists($file)) {
            include $file;
        }
    }


    public static function getTemplateHierarchyFlat($parent, $depth = 1) {
        global $db;

        $arr  = array();
        $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');
//		$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));
        for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {
            $page        = $kids[$i];
            $page->depth = $depth;
            $page->first = ($i == 0 ? 1 : 0);
            $page->last  = ($i == count($kids) - 1 ? 1 : 0);
            $arr[]       = $page;
            $arr         = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));
        }
        return $arr;
    }


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

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

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


    function download($disposition=false, $expires=false) {
        $disposition = $disposition ?: 'inline';
        $bk = $this->open();
        if ($bk->sendRedirectUrl($disposition))
            return;
        $ttl = ($expires) ? $expires - Misc::gmtime() : false;
        $this->makeCacheable($ttl);
        $type = $this->getType() ?: 'application/octet-stream';
        Http::download($this->getName(), $type, null, 'inline');
        header('Content-Length: '.$this->getSize());
        $this->sendData(false);
        exit();
    }

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


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

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

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


    public function get_discount_value()
    {
        if (empty($this->coupon_data)) {
            return false;
        }

        $apply_code = false;
        if ($this->sum() >= $this->coupon_data['total_amount']) {
            $apply_code = true;
        }

        if ($apply_code) {
            return floatval($this->coupon_data['discount_value']);
        }

        return false;
    }


    public function validate($string, $config, $context) {

        static $allowed_values = array(
            'line-through' => true,
            'overline' => true,
            'underline' => true,
        );

        $string = strtolower($this->parseCDATA($string));

        if ($string === 'none') return $string;

        $parts = explode(' ', $string);
        $final = '';
        foreach ($parts as $part) {
            if (isset($allowed_values[$part])) {
                $final .= $part . ' ';
            }
        }
        $final = rtrim($final);
        if ($final === '') return false;
        return $final;

    }


    public function testPages()
    {
        \MicroweberPackages\Multilanguage\MultilanguageHelpers::setMultilanguageEnabled(false);

        $this->browse(function (Browser $browser) {

            $browser->within(new AdminLogin(), function ($browser) {
                $browser->fillForm();
            });

            $routeCollection = Route::getRoutes();
            foreach ($routeCollection as $value) {
                if ($value->getActionMethod() == 'GET') {
                    continue;
                }
                if (strpos($value->uri(), 'admin') !== false) {
                    $browser->visit($value->uri());

                    $browser->within(new ChekForJavascriptErrors(), function ($browser) {
                        $browser->validate();
                    });

                 //   $browser->pause(2000);
                }
            }

        });

    }

URL Redirection to Untrusted Site ('Open Redirect')

A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.


   function prepareInputForUpdate($input) {

      if (isset($input["rootdn_passwd"])) {
         if (empty($input["rootdn_passwd"])) {
            unset($input["rootdn_passwd"]);
         } else {
            $input["rootdn_passwd"] = Toolbox::encrypt(stripslashes($input["rootdn_passwd"]),
                                                       GLPIKEY);
         }
      }

      if (isset($input["_blank_passwd"]) && $input["_blank_passwd"]) {
         $input['rootdn_passwd'] = '';
      }

      // Set attributes in lower case
      if (count($input)) {
         foreach ($input as $key => $val) {
            if (preg_match('/_field$/', $key)) {
               $input[$key] = Toolbox::strtolower($val);
            }
         }
      }

      //do not permit to override sync_field
      if ($this->isSyncFieldEnabled()
         && isset($input['sync_field'])
         && $this->isSyncFieldUsed()
      ) {
         if ($input['sync_field'] == $this->fields['sync_field']) {
            unset($input['sync_field']);
         } else {
            Session::addMessageAfterRedirect(
               __('Synchronization field cannot be changed once in use.'),
               false,
               ERROR
            );
            return false;
         };
      }
      return $input;
   }

The software contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.


                }elseif(!in_array($k, $arr) && $k != 'paging'){
                    //self::error('404');
                }else{

                    self::incFront('default');

                }

            }

        }else{


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

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


    public function testDefaultConstructor()
    {
        $r = new Response();
        $this->assertSame(200, $r->getStatusCode());
        $this->assertSame('1.1', $r->getProtocolVersion());
        $this->assertSame('OK', $r->getReasonPhrase());
        $this->assertSame([], $r->getHeaders());
        $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
        $this->assertSame('', (string) $r->getBody());
    }


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


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

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

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


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

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


    public function testCanConstructWithStatusCode()
    {
        $r = new Response(404);
        $this->assertSame(404, $r->getStatusCode());
        $this->assertSame('Not Found', $r->getReasonPhrase());
    }


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


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

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


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

		return $this;
	}


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


        function scan_page($parent_id) {
            global $db;

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


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

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

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

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

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

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


    public static function navtojson() {
        return json_encode(self::navhierarchy());
    }


    public static function _date2timestamp( $datetime, $wtz=null ) {
      if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
      if( !isset( $datetime['min'] ))  $datetime['min']  = 0;
      if( !isset( $datetime['sec'] ))  $datetime['sec']  = 0;
      if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty(  $datetime['tz'] )))
        return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      $output = $offset = 0;
      if( empty( $wtz )) {
        if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
          $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
          $wtz    = 'UTC';
        }
        else
          $wtz    = $datetime['tz'];
      }
      if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
        $wtz      = 'UTC';
      try {
        $strdate  = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
        $d        = new DateTime( $strdate, new DateTimeZone( $wtz ));
        if( 0    != $offset )  // adjust for offset
          $d->modify( $offset.' seconds' );
        $output   = $d->format( 'U' );
        unset( $d );
      }
      catch( Exception $e ) {
        $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      }
      return $output;
    }


            foreach ($val as $k => $v) {
                unset($process[$key][$k]);
                $stripTags = \in_array($k, $stripTagsWhiteList) ? false : $stripTagsConf;
                $allowedHtmlTags = \array_key_exists($k, $allowanceList) ? $allowanceList[$k][self::ALLOWED_HTML_TAGS_KEY] : [];
                $allowedAttributes = \array_key_exists($k, $allowanceList) ? $allowanceList[$k][self::ALLOWED_ATTRIBUTES_KEY] : [];

                if (\is_string($k)) {
                    $filteredKey = self::filterValue($k, $regex, $stripTags, $allowedHtmlTags, $allowedAttributes);
                } else {
                    $filteredKey = $k;
                }

                if ($filteredKey === '' || $filteredKey === null) {
                    continue;
                }

                if (\is_array($v)) {
                    $process[$key][$filteredKey] = self::filterArrayValue($v, $regex, $stripTags, $allowedHtmlTags, $allowedAttributes);
                    continue;
                }

                if (\is_string($v)) {
                    $process[$key][$filteredKey] = self::filterValue($v, $regex, $stripTags, $allowedHtmlTags, $allowedAttributes);
                    continue;
                }

                $process[$key][$filteredKey] = $v;
            }


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

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

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

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


    function restart($sMessage = '')
    {
        $_COOKIE['sessionID'] = phpAds_SessionRegenerateId();
        OA_Auth::displayLogin($sMessage, $_COOKIE['sessionID']);
    }

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.


    public static function Xclean($vars)
    {
        $var = htmlspecialchars_decode($vars, ENT_QUOTES | ENT_HTML5);
        // $var = html_entity_decode($vars);
        return $var;
    }

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.


    public function __construct() {
        $this->parser = new HTMLPurifier_URIParser();
    }


    private function getSwimlane()
    {
        $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));

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

        return $swimlane;
    }


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

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


$logo = "";
        }else{
            $logo = "";
        }
        return $logo;
    }

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.


    public static function getHelpVersion($version_id) {
        global $db;

        return $db->selectValue('help_version', 'version', 'id="'.intval($version_id).'"');
    }


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

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


            $count += $db->dropTable($basename);
        }

        flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
        expHistory::back();
    }


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


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


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


    public function setTagName($tagName)
    {
        $this->tagName = strtolower($tagName);
    }


    public function shippingMethodSave(Request $request) {

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

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

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

The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.


    public function breadcrumb() {
        global $sectionObj;

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


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


    public function showall() {
        global $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }


	public static function onLoadExtensionSchemaUpdates( DatabaseUpdater $updater ) {
		$config = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'globalnewfiles' );

		if ( $config->get( 'CreateWikiDatabase' ) === $config->get( 'DBname' ) ) {
			$updater->addExtensionTable(
				'gnf_files',
				__DIR__ . '/../sql/gnf_files.sql'
			);

			$updater->modifyExtensionField(
				'gnf_files',
				'files_timestamp',
				__DIR__ . '/../sql/patches/patch-gnf_files-binary.sql'
			);

			$updater->modifyTable(
 				'gnf_files',
  				__DIR__ . '/../sql/patches/patch-gnf_files-add-indexes.sql',
				true
 			);
		}

		return true;
	}

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.


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

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

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


      public function edit_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);

        //grab all user groups
        $group = new group();

        //create two 'default' groups:
        $groups = array(
                -1 => 'ALL LOGGED IN USERS',
                -2 => 'ALL NON-LOGGED IN USERS'
                );
        //loop our groups and append them to the array
       // foreach ($group->find() as $g){
       //this is a workaround for older code. Use the previous line if possible:
       $allGroups = group::getAllGroups();
       if (count($allGroups))
       {
           foreach ($allGroups as $g)
           {
                $groups[$g->id] = $g->name;
           };
       }
       //find our selected groups for this discount already
       // eDebug($discount);
       $selected_groups = array();
       if (!empty($discount->group_ids))
       {
            $selected_groups = expUnserialize($discount->group_ids);
       }

       if ($discount->minimum_order_amount == "") $discount->minimum_order_amount = 0;
       if ($discount->discount_amount == "") $discount->discount_amount = 0;
       if ($discount->discount_percent == "") $discount->discount_percent = 0;

        // get the shipping options and their methods
        $shipping_services = array();
        $shipping_methods = array();
//        $shipping = new shipping();
        foreach (shipping::listAvailableCalculators() as $calcid=>$name) {
            if (class_exists($name)) {
                $calc = new $name($calcid);
                $shipping_services[$calcid] = $calc->title;
                $shipping_methods[$calcid] = $calc->availableMethods();
            }
        }

       assign_to_template(array(
           'discount'=>$discount,
           'groups'=>$groups,
           'selected_groups'=>$selected_groups,
           'shipping_services'=>$shipping_services,
           'shipping_methods'=>$shipping_methods
       ));
    }


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


  public function __construct() {
    $this->smtp_conn = 0;
    $this->error = null;
    $this->helo_rply = null;

    $this->do_debug = 0;
  }


    public static function run()
    {
        $m = self::match();
        // print_r($m);
        if (is_array($m)) {
            # code...

            $val = self::extract($m[0], $m[1]);
            // print_r($val);
            if (isset($val) && $val != null) {
                return $val;
            } else {
                $val['error'] = '';

                return $val;
            }
        } else {
            $val['error'] = '';

            return $val;
        }
    }


    public function search($q, $page='') {
        $q = str_replace(' ', '+', trim($q));
        if (isset($page) && $page !='') {
            $page = "&page=".$page;
        } else {
            $page = "";
        }
        $url = "http://api.themoviedb.org/3/search/movie?query=".$q."&api_key=".$this->apikey.$page;
        $search = $this->curl($url);
        //echo $search;
        return $search;
    }


    public function iisRequestUriProvider()
    {
        return array(
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(),
                '/foo/bar',
            ),
            array(
                array(
                    'X_REWRITE_URL' => '/foo/bar',
                ),
                array(),
                '/foo/bar',
            ),
            array(
                array(),
                array(
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar',
                ),
                '/foo/bar',
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'HTTP_X_ORIGINAL_URL' => '/foo/bar',
                ),
                '/foo/bar',
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar',
                ),
                '/foo/bar',
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'HTTP_X_ORIGINAL_URL' => '/foo/bar',
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar',
                ),
                '/foo/bar',
            ),
            array(
                array(),
                array(
                    'ORIG_PATH_INFO' => '/foo/bar',
                ),
                '/foo/bar',
            ),
            array(
                array(),
                array(
                    'ORIG_PATH_INFO' => '/foo/bar',
                    'QUERY_STRING' => 'foo=bar',
                ),
                '/foo/bar?foo=bar',
            ),
        );
    }


	function edit() {
	    if (empty($this->params['content_id'])) {
	        flash('message',gt('An error occurred: No content id set.'));
            expHistory::back();
	    }
        /* The global constants can be overridden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $comment = new expComment($id);
        //FIXME here is where we might sanitize the comment before displaying/editing it
		assign_to_template(array(
		    'content_id'=>$this->params['content_id'],
            'content_type'=>$this->params['content_type'],
		    'comment'=>$comment
		));
	}


    function manage() {
        global $db, $router, $user;

        expHistory::set('manageable', $router->params);
        assign_to_template(array(
            'canManageStandalones' => self::canManageStandalones(),
            'sasections'           => $db->selectObjects('section', 'parent=-1'),
            'user'                 => $user,
//            'canManagePagesets'    => $user->isAdmin(),
//            'templates'            => $db->selectObjects('section_template', 'parent=0'),
        ));
    }


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

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

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


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

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

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


    public function testNullAttribute()
    {
        $request = (new ServerRequest('GET', '/'))->withAttribute('name', null);

        $this->assertSame(['name' => null], $request->getAttributes());
        $this->assertNull($request->getAttribute('name', 'different-default'));

        $requestWithoutAttribute = $request->withoutAttribute('name');

        $this->assertSame([], $requestWithoutAttribute->getAttributes());
        $this->assertSame('different-default', $requestWithoutAttribute->getAttribute('name', 'different-default'));
    }


    private function doTestEncodeFormulas(bool $legacy = false)
    {
        if ($legacy) {
            $this->encoder = new CsvEncoder(',', '"', '\\', '.', true);
        } else {
            $this->encoder = new CsvEncoder([CsvEncoder::ESCAPE_FORMULAS_KEY => true]);
        }

        $this->assertSame(<<<'CSV'
0
"	=2+3"

CSV
            , $this->encoder->encode(['=2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	-2+3"

CSV
            , $this->encoder->encode(['-2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	+2+3"

CSV
            , $this->encoder->encode(['+2+3'], 'csv'));

        $this->assertSame(<<<'CSV'
0
"	@MyDataColumn"

CSV
            , $this->encoder->encode(['@MyDataColumn'], 'csv'));
    }

Improper Neutralization of Formula Elements in a CSV File

The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.


   	function show() {
//        assign_to_template(array('record'=>$record,'tag'=>$tag));  //FIXME $record & $tag are undefined
    }


public function testXssExternalLinkImg()
    {
        $antiXss = new \MicroweberPackages\Helper\HTMLClean();

        $string = '';
        $content = $antiXss->clean($string);
        $this->assertEquals('', $content);

        $string = '';
        $content = $antiXss->clean($string);
        $this->assertEquals('', $content);

    }


    private function filterQueryAndFragment($str)
    {
        if (!is_string($str)) {
            throw new \InvalidArgumentException('Query and fragment must be a string');
        }

        return preg_replace_callback(
            '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
            [$this, 'rawurlencodeMatchZero'],
            $str
        );
    }


	public function getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}


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

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

		assign_to_template(array(
            'purchase_orders'=>$purchase_orders,
            'vendors' => $vendors,
            'vendor_id' => @$this->params['vendor']
        ));
	}


    function getResponse()
    {
        // methodResponses can only have one param - return that
        return $this->message->params[0];
    }


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

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

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

The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.


        function scan_page($parent_id) {
            global $db;

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


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


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


    public function showall() {
        global $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }


    protected function getCustomDefinitionService()
    {
        return $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition();
    }


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

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.


            $result = $this->defs[$i]->validate($string, $config, $context);
            if ($result !== false) return $result;
        }
        return false;
    }


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


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

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

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


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


   function __construct(bool $connect = false) {
      global $CFG_GLPI;

      $options = [
         'base_uri'        => GLPI_MARKETPLACE_PLUGINS_API_URI,
         'connect_timeout' => self::TIMEOUT,
      ];

      // add proxy string if configured in glpi
      if (!empty($CFG_GLPI["proxy_name"])) {
         $proxy_creds      = !empty($CFG_GLPI["proxy_user"])
            ? $CFG_GLPI["proxy_user"].":".Toolbox::decrypt($CFG_GLPI["proxy_passwd"], GLPIKEY)."@"
            : "";
         $proxy_string     = "http://{$proxy_creds}".$CFG_GLPI['proxy_name'].":".$CFG_GLPI['proxy_port'];
         $options['proxy'] = $proxy_string;
      }

      // init guzzle client with base options
      $this->httpClient = new Guzzle_Client($options);
   }

Use of a Broken or Risky Cryptographic Algorithm

The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.


    function categoryBreadcrumb() {
//        global $db, $router;

        //eDebug($this->category);

        /*if(isset($router->params['action']))
        {
            $ancestors = $this->category->pathToNode();
        }else if(isset($router->params['section']))
        {
            $current = $db->selectObject('section',' id= '.$router->params['section']);
            $ancestors[] = $current;
            if( $current->parent != -1 || $current->parent != 0 )
            {
                while ($db->selectObject('section',' id= '.$router->params['section']);)
                    if ($section->id == $id) {
                        $current = $section;
                        break;
                    }
                }
            }
            eDebug($sections);
            $ancestors = $this->category->pathToNode();
        }*/

        $ancestors = $this->category->pathToNode();
        // eDebug($ancestors);
        assign_to_template(array(
            'ancestors' => $ancestors
        ));
    }


    public function isAuthorizedBackendUserSession()
    {
        if (!$this->hasSessionCookie()) {
            return false;
        }
        $this->initializeSession();
        if (empty($_SESSION['authorized']) || empty($_SESSION['isBackendSession'])) {
            return false;
        }
        return !$this->isExpired();
    }

According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."


public function set_controller($controller, $action)
	{
		include CLASS_DIR . 'module.php';

		$module = new Module($controller);

		define ('MODULE_NAME', $module->get_name());

		$class_file = APP_DIR . 'controller/' . MODULE_NAME . '.php';
		$class_name = ucfirst(MODULE_NAME) . '_Controller';
		$class_method = ucfirst($action) . '_Action';

		// tworzy obiekt kontrolera:

		if (file_exists($class_file))
		{
			include $class_file;

			if (class_exists($class_name))
			{
				$this->controller_object = new $class_name($this);

				$this->set_acl($this);
			}
			else
			{
				die ('Class:
'.$class_name.'
 not found.');
			}
		}
		else
		{
			die ('File:
'.$class_file.'
 not found.');
		}

		// tworzy obiekt modelu:

		$this->set_model_object(MODULE_NAME);

		// tworzy obiekt widoku:

		$this->set_view_object(MODULE_NAME);

		// wywołuje akcję (metodę) kontrolera:

		if (method_exists($class_name, $class_method))
		{
			$this->controller_object->{$class_method}();
		}
		else
		{
			die ('Method:
'.$class_method.'
 in class:
'.$class_name.'
 not found.');
		}
	}


    public function execute(&$params){
        $options = &$this->config['options'];
        $notif = new Notification;
        $notif->user = $this->parseOption('user', $params);
        $notif->createdBy = 'API';
        $notif->createDate = time();
        // file_put_contents('triggerLog.txt',"\n".$notif->user,FILE_APPEND);
        // if($this->parseOption('type',$params) == 'auto') {
        // if(!isset($params['model']))
        // return false;
        // $notif->modelType = get_class($params['model']);
        // $notif->modelId = $params['model']->id;
        // $notif->type = $this->getNotifType();
        // } else {
        $notif->type = 'custom';
        $notif->text = $this->parseOption('text', $params);
        // }

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

    }


    public static function group($id)
    {
        $usr = Db::result(
            sprintf(
                "SELECT * FROM `user` WHERE `id` = '%d' OR `userid` = '%s' LIMIT 1",
                Typo::int($id),
                Typo::cleanX($id)
            )
        );

        return $usr[0]->group;
    }


	public function delete_item_permissions_check( $request ) {

		$id = (int) $request['id'];

		if ( ! current_user_can( 'delete_user', $id ) ) {
			return new WP_Error( 'rest_user_cannot_delete', __( 'Sorry, you are not allowed to delete this user.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		return true;
	}


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


    public function setItems($items)
    {
        if ($items && !$items instanceof ItemBag) {
            $items = new PayPalItemBag($items);
        }

        return $this->setParameter('items', $items);
    }


	public function update($key, $qty) {
		if ((int)$qty && ((int)$qty > 0) && isset($this->session->data['cart'][$key])) {
			$this->session->data['cart'][$key] = (int)$qty;
		} else {
			$this->remove($key);
		}

		$this->data = array();
	}

Improper Restriction of XML External Entity Reference

The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.


    protected function beginExport($includeHidden = false) {
        if ($includeHidden) {
            $this->click ("css=#includeHidden");
        }
        $this->click ("css=#export-button");
        $this->waitForTextPresent ("data successfully exported.");
        $this->assertAlert ("Export Complete!");
    }

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 db_start()
{
	global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;

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

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


    public static function url($mod) {
        $url = Site::$url."/inc/mod/".$mod;
        return $url;
    }


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


    public static function add($var) {

        $route = self::$_route;

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

        return self::$_route;

    }


                        foreach ($days as $value) {
                            $regitem[] = $value;
                        }


    public function setParseContent($parseContent)
    {
        $this->parseContent = $parseContent;
        return $this;
    }


function path_f ($path)
{
    global $home_dir;
    $abs_dir = $home_dir;
    switch ($path)
    {
        case '.':
        case '': return realpath($abs_dir);
    }

    return realpath(realpath($home_dir) . "/$path");
}


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

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


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

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

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

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


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

        $paths = func_get_args();

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

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

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

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

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


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

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


    public static function Zipped () {

        global $HTTP_ACCEPT_ENCODING;

        if( headers_sent() ){

            $encoding = false;

        }elseif( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ){

            $encoding = 'x-gzip';

        }elseif( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){

            $encoding = 'gzip';

        }else{

            $encoding = false;

        }

        if( $encoding ){

            $contents = ob_get_contents();
            ob_end_clean();
            header('Content-Encoding: '.$encoding);
            print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
            $size = strlen($contents);
            $contents = gzcompress($contents, 9);
            $contents = substr($contents, 0, $size);
            print($contents);
            exit();

        }else{

            ob_end_flush();
            exit();

        }
    }


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


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

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

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


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


$ids = array_map (function ($event) { return $event->id; }, $events);


    public function testFormsCsrfIsEnabledByDefault()
    {
        if (class_exists(FullStack::class)) {
            $this->markTestSkipped('testing with the FullStack prevents verifying default values');
        }
        $container = $this->createContainerFromFile('form_default_csrf');

        $this->assertTrue($container->hasDefinition('security.csrf.token_manager'));
        $this->assertTrue($container->hasParameter('form.type_extension.csrf.enabled'));
        $this->assertTrue($container->getParameter('form.type_extension.csrf.enabled'));
    }


    public static function fixName($name) {
        $name = preg_replace('/[^A-Za-z0-9\.]/','_',$name);
        if ($name[0] == '.')
            $name[0] = '_';
        return $name;
//        return preg_replace('/[^A-Za-z0-9\.]/', '-', $name);
    }


	public function addSelect( $fields ) {
		if ( !is_array( $fields ) ) {
			throw new \MWException( __METHOD__ . ': A non-array was passed.' );
		}
		foreach ( $fields as $alias => $field ) {
			if ( !is_numeric( $alias ) && array_key_exists( $alias, $this->select ) && $this->select[$alias] != $field ) {
				//In case of a code bug that is overwriting an existing field alias throw an exception.
				throw new \MWException( __METHOD__ . ": Attempted to overwrite existing field alias `{$this->select[$alias]}` AS `{$alias}` with `{$field}` AS `{$alias}`." );
			}
			//String alias and does not exist already.
			if ( !is_numeric( $alias ) && !array_key_exists( $alias, $this->select ) ) {
				$this->select[$alias] = $field;
			}

			//Speed up by not using in_array() or array_key_exists().  Toss the field names into their own array as keys => true to exploit a speedy look up with isset().
			if ( is_numeric( $alias ) && !isset( $this->selectedFields[$field] ) ) {
				$this->select[] = $field;
				$this->selectedFields[$field] = true;
			}
		}
		return true;
	}

The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.


	public function __construct()
	{
		parent::__construct();
		$this->exposeMethod('getOwners');
		$this->exposeMethod('getReference');
		$this->exposeMethod('getUserRole');
		$this->exposeMethod('verifyPhoneNumber');
		$this->exposeMethod('findAddress');
		$this->exposeMethod('verifyIsHolidayDate');
		$this->exposeMethod('changeFavoriteOwner');
	}


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

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

                break;
        }

        return $url;
    }


    protected function driverRead(CacheItemInterface $item)
    {
        $this->driverConnect();
        // return null if no caching
        // return value if in caching
        $keyword = self::PREFIX . $item->getKey();
        $x = isset($_COOKIE[ $keyword ]) ? $this->decode(json_decode($_COOKIE[ $keyword ], true)) : false;

        if ($x == false) {
            return null;
        } else {
            if (!is_scalar($this->driverUnwrapData($x)) && !is_null($this->driverUnwrapData($x))) {
                throw new phpFastCacheDriverException('Hacking attempt: The decoding returned a non-scalar value, Cookie driver does not allow this.');
            }

            return $x;
        }
    }

The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.


public function getHTMLFormatted($config, $errors = null) {
        $ret = array();

        $this->generator = new HTMLPurifier_Generator($config, $this->context);
        if ($errors === null) $errors = $this->errors;

        // 'At line' message needs to be removed

        // generation code for new structure goes here. It needs to be recursive.
        foreach ($this->lines as $line => $col_array) {
            if ($line == -1) continue;
            foreach ($col_array as $col => $struct) {
                $this->_renderStruct($ret, $struct, $line, $col);
            }
        }
        if (isset($this->lines[-1])) {
            $this->_renderStruct($ret, $this->lines[-1]);
        }

        if (empty($errors)) {
            return '
' . $this->locale->getMessage('ErrorCollector: No errors') . '
';
        } else {
            return '

' . implode('

', $ret) . '

';
        }

    }


    protected function getFoo2Service()
    {
        return $this->services['Foo\\Foo'] = new \Foo\Foo();
    }


    public static function make($id) {
        return new HTMLPurifier_ConfigSchema_Interchange_Id($id);
    }


    public function __construct()
    {
        global $GLOBALS;
    }


. htmlspecialchars($table['table']) . '`';
                    $html .= '
';
                }
            }
        } else {
            $html .= '
'
                  . ($this->_tableType == 'recent'
                    ?__('There are no recent tables.')
                    :__('There are no favorite tables.'))
                  . '
';
        }


    public function upload() {

        // upload the file, but don't save the record yet...
        if ($this->params['resize'] != 'false') {
            $maxwidth = $this->params['max_width'];
        } else {
            $maxwidth = null;
        }
        $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);
        // since most likely this function will only get hit via flash in YUI Uploader
        // and since Flash can't pass cookies, we lose the knowledge of our $user
        // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,
        // and then assign $user->id to $file->poster so we have an audit trail for the upload

        if (is_object($file)) {
            $resized = !empty($file->resized) ? true : false;
            $user = new user($this->params['usrid']);
            $file->poster = $user->id;
            $file->posted = $file->last_accessed = time();
            $file->save();
            if (!empty($this->params['cat'])) {
                $expcat = new expCat($this->params['cat']);
                $params['expCat'][0] = $expcat->id;
                $file->update($params);
            }

            // a echo so YUI Uploader is notified of the function's completion
            if ($resized) {
                echo gt('File resized and then saved');
            } else {
                echo gt('File saved');
            }
        } else {
            echo gt('File was NOT uploaded!');
//            flash('error',gt('File was not uploaded!'));
        }
    }


	protected function _setContent($path, $fp) {
		elFinder::rewind($fp);
		$fstat = fstat($fp);
		$size = $fstat['size'];

	}


    public function prepare($config, $context) {
        parent::prepare($config, $context);
        $this->config = $config;
        $this->context = $context;
        $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');
        $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');
        $this->attrValidator = new HTMLPurifier_AttrValidator();
    }


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


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


            list($type, $params) = $this->getFixType($name);
            switch ($type) {
                case 'attr_transform_pre':
                case 'attr_transform_post':
                    $attr = $params['attr'];
                    if (isset($params['element'])) {
                        $element = $params['element'];
                        if (empty($this->info[$element])) {
                            $e = $this->addBlankElement($element);
                        } else {
                            $e = $this->info[$element];
                        }
                    } else {
                        $type = "info_$type";
                        $e = $this;
                    }
                    // PHP does some weird parsing when I do
                    // $e->$type[$attr], so I have to assign a ref.
                    $f =& $e->$type;
                    $f[$attr] = $fix;
                    break;
                case 'tag_transform':
                    $this->info_tag_transform[$params['element']] = $fix;
                    break;
                case 'child':
                case 'content_model_type':
                    $element = $params['element'];
                    if (empty($this->info[$element])) {
                        $e = $this->addBlankElement($element);
                    } else {
                        $e = $this->info[$element];
                    }
                    $e->$type = $fix;
                    break;
                default:
                    trigger_error("Fix type $type not supported", E_USER_ERROR);
                    break;
            }
        }
    }


    public function write($template = '')
    {
        if (!empty($this->script_files)) {
            $this->set_env('request_token', $this->app->get_request_token());
        }

        $commands = $this->get_js_commands($framed);

        // if all js commands go to parent window we can ignore all
        // script files and skip rcube_webmail initialization (#1489792)
        if ($framed) {
            $this->scripts      = array();
            $this->script_files = array();
            $this->header       = '';
            $this->footer       = '';
        }

        // write all javascript commands
        $this->add_script($commands, 'head_top');

        // allow (legal) iframe content to be loaded
        $iframe = $this->framed || $this->env['framed'];
        if (!headers_sent() && $iframe && $this->app->config->get('x_frame_options', 'sameorigin') === 'deny') {
            header('X-Frame-Options: sameorigin', true);
        }

        // call super method
        $this->_write($template, $this->config->get('skin_path'));
    }


    public static function getHelpVersionId($version) {
        global $db;

        return $db->selectValue('help_version', 'id', 'version="'.$version.'"');
    }


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

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


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

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


    public function accept(NodeVisitor $visitor)
    {
        $visitor->visitTextNode($this);
    }


    function update_optiongroup_master() {
        global $db;

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

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

        expHistory::back();
    }


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


    public function generateFromTokens($tokens) {
        if (!$tokens) return '';

        // Basic algorithm
        $html = '';
        for ($i = 0, $size = count($tokens); $i < $size; $i++) {
            if ($this->_scriptFix && $tokens[$i]->name === 'script'
                && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
                // script special case
                // the contents of the script block must be ONE token
                // for this to work.
                $html .= $this->generateFromToken($tokens[$i++]);
                $html .= $this->generateScriptFromToken($tokens[$i++]);
            }
            $html .= $this->generateFromToken($tokens[$i]);
        }

        // Tidy cleanup
        if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
            $tidy = new Tidy;
            $tidy->parseString($html, array(
               'indent'=> true,
               'output-xhtml' => $this->_xhtml,
               'show-body-only' => true,
               'indent-spaces' => 2,
               'wrap' => 68,
            ), 'utf8');
            $tidy->cleanRepair();
            $html = (string) $tidy; // explicit cast necessary
        }

        // Normalize newlines to system defined value
        if ($this->config->get('Core.NormalizeNewlines')) {
            $nl = $this->config->get('Output.Newline');
            if ($nl === null) $nl = PHP_EOL;
            if ($nl !== "\n") $html = str_replace("\n", $nl, $html);
        }
        return $html;
    }


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


    public function getViewFileParams () {
        if (!isset ($this->_viewFileParams)) {
            $this->_viewFileParams = array_merge (
                parent::getViewFileParams (),
                array (
                    'chartType' => $this->chartType,
			        'chartSettingsDataProvider' => self::getChartSettingsProvider (
                        $this->chartType),
                    'eventTypes' =>
                        array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,
                    'socialSubtypes' => json_decode (
			            Dropdowns::model()->findByPk(113)->options,true),
                    'visibilityFilters' => array (
                        '1'=>'Public',
                        '0'=>'Private',
                    ),
                    'suppressChartSettings' => false,
                    'chartType' => 'usersChart',
                    'widgetUID' => $this->widgetUID,
                    'metricTypes' => User::getUserOptions (),
                )
            );
        }
        return $this->_viewFileParams;
    }


    public function assertIsBool() {
        if (!is_bool($this->contents)) $this->error('must be a boolean');
        return $this;
    }


	public function findAddress(App\Request $request)
	{
		$instance = \App\Map\Address::getInstance($request->getByType('type'));
		$response = new Vtiger_Response();
		if ($instance) {
			$response->setResult($instance->find($request->getByType('value', 'Text')));
		}
		$response->emit();
	}

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


	function manage() {
	    global $db;

	    expHistory::set('manageable', $this->params);
//	    $classes = array();
        $dir = BASE."framework/modules/ecommerce/billingcalculators";
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
                    include_once("$dir/$file");
                    $classname = substr($file, 0, -4);
                    $id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
                    if (empty($id)) {
//                        $calobj = null;
                        $calcobj = new $classname();
                        if ($calcobj->isSelectable() == true) {
                            $obj = new billingcalculator(array(
                                'title'=>$calcobj->name(),
//                                'user_title'=>$calcobj->title,
                                'body'=>$calcobj->description(),
                                'calculator_name'=>$classname,
                                'enabled'=>false));
                            $obj->save();
                        }
                    }
                }
            }
        }

        $bcalc = new billingcalculator();
        $calculators = $bcalc->find('all');
        assign_to_template(array(
            'calculators'=>$calculators
        ));
	}


foreach ($elem[2] as $field) {
            echo '

                           '.$field[1].' :
                        ';
            if ($field[3] === "masked") {
                echo '

<input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'_'.$elem[0].'" class="fields" />';
            } else {
                echo '

<input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'_'.$elem[0].'" class="fields" />';
            }
            echo '

';
        }

The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.


    public function breadcrumb() {
        global $sectionObj;

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


public function getN() {return $this->n;}


	function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}

		return $records;
	}


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

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			assign_to_template(array(
                'vendor'=>$vendor
            ));
		}
	}


    public function set_coupon_data($data)
    {
        $this->coupon_data = $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 static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
        //echo "1
"; eDebug($str);

        $str = str_replace("�", "’", $str);
        $str = str_replace("�", "‘", $str);
        $str = str_replace("�", "®", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "—", $str);
        $str = str_replace("�", "”", $str);
        $str = str_replace("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\t", " ", $str);
        $str = str_replace(",", "\,", $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);

        if (!$isHTML) {
            $str = str_replace('\"', """, $str);
            $str = str_replace('"', """, $str);
        } else {
            $str = str_replace('"', '""', $str);
        }

        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
        $str = trim(str_replace("�", "™", $str));
        //echo "2
"; eDebug($str,die);
        return $str;
    }

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.


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