            foreach ($usr as $u) {
                # code...
                $msgs = str_replace('{{userid}}', $u->userid, $msg);
                $vars = array(
                            'to' => $u->email,
                            'to_name' => $u->userid,
                            'message' => $msgs,
                            'subject' => $subject,
                            'msgtype' => $_POST['type']
                        );
                $mailsend = Mail::send($vars);
                if ($mailsend !== null) {
                    $alermailsend[] = $mailsend;
                }
                sleep(3);
            }


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

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

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

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

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.


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

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 static function loader(){
        $theme = Options::v('themes');
        define('THEME', $theme);
        self::incFunc($theme);
    }


    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 function testClearTags () {
        $contact = $this->contacts ('testAnyone');
        Yii::app()->db->createCommand ("
            delete from x2_tags where type='Contacts' and itemId=:id
        ")->execute (array (':id' => $contact->id));
        $tags = array ('test', 'test2', 'test3');
        $contact->addTags ($tags);
        $contact->clearTags ();
        $this->assertEquals (array (), $contact->getTags (true));
    }

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.


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


$f = function (\Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber $v) { return $v; }; return $f(${($_ = isset($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber']) ? $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] : ($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber())) && false ?: '_'});


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


		public function merge($branch, $options = NULL)
		{
			$this->run('merge', $options, $branch);
			return $this;
		}

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

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


    protected function forceChangePassword()
    {
        if (!Yii::$app->user->isMustChangePasswordUrl()) {
            Yii::$app->getResponse()->redirect([Yii::$app->user->mustChangePasswordRoute]);
        }
    }

The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.


	public static function dplParserFunction( &$parser ) {
		self::setLikeIntersection( false );

		$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );

		// callback for the parser function {{#dpl:	  or   {{DynamicPageList::
		$input = "";

		$numargs = func_num_args();
		if ( $numargs < 2 ) {
			$input = "#dpl: no arguments specified";
			return str_replace( '§', '<', '§pre>§nowiki>' . $input . '§/nowiki>§/pre>' );
		}

		// fetch all user-provided arguments (skipping $parser)
		$arg_list = func_get_args();
		for ( $i = 1; $i < $numargs; $i++ ) {
			$p1 = $arg_list[$i];
			$input .= str_replace( "\n", "", $p1 ) . "\n";
		}

		$parse = new \DPL\Parse();
		$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );
		return [ // parser needs to be coaxed to do further recursive processing
			$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),
			'isLocalObj' => true,
			'title' => $parser->getTitle()
		];
	}

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.


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

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

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

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.


				array_push($privileges, $p);
		}
	}

	return array('status' => 'success',
	              'privileges' => array_unique($privileges));
}

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 read($sessionId)
    {
        $dbData = $this->getCollection()->findOne(array(
            $this->options['id_field'] => $sessionId,
            $this->options['expiry_field'] => array('$gte' => new \MongoDate()),
        ));

        return null === $dbData ? '' : $dbData[$this->options['data_field']]->bin;
    }


    public function testBodyConsistent()
    {
        $r = new Response(200, [], '0');
        $this->assertEquals('0', (string)$r->getBody());
    }


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


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

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


function XMLRPCremoveNode($nodeID) {
	require_once(".ht-inc/privileges.php");
	global $user;
	if(! is_numeric($nodeID)) {
		return array('status' => 'error',
		             'errorcode' => 78,
		             'errormsg' => 'Invalid nodeid specified');
	}
	if(! in_array("nodeAdmin", $user['privileges'])) {
		return array('status' => 'error',
		             'errorcode' => 70,
		             'errormsg' => 'User cannot administer nodes');
	}
	if(! checkUserHasPriv("nodeAdmin", $user['id'], $nodeID)) {
		return array('status' => 'error',
		             'errorcode' => 57,
		             'errormsg' => 'User cannot edit this node');
	}
	$nodes = recurseGetChildren($nodeID);
	array_push($nodes, $nodeID);
	$deleteNodes = implode(',', $nodes);
	$query = "DELETE FROM privnode "
	       . "WHERE id IN ($deleteNodes)";
	doQuery($query, 345);
	return array('status' => 'success');
}


    public function getFilePath($fileName = null)
    {
        if ($fileName === null) {
            $fileName = $this->fileName;
        }

        return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;
    }

Inclusion of Functionality from Untrusted Control Sphere

The software imports, requires, or includes executable functionality (such as a library) from a source that is outside of the intended control sphere.


    private static function sign($input, $key, $algo)
    {
        switch ($algo) {

            case 'HS256':
                return hash_hmac('sha256', $input, $key, true);

            case 'HS384':
                return hash_hmac('sha384', $input, $key, true);

            case 'HS512':
                return hash_hmac('sha512', $input, $key, true);

            case 'RS256':
                return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA256);

            case 'RS384':
                return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA384);

            case 'RS512':
                return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA512);

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


    public function sendData($data)
    {
        $httpRequest = $this->httpClient->post($this->getEndpoint(), null, http_build_query($data));
        $httpRequest->getCurlOptions()->set(CURLOPT_SSLVERSION, 6); // CURL_SSLVERSION_TLSv1_2 for libcurl < 7.35
        $httpResponse = $httpRequest->send();

        return $this->createResponse($httpResponse->getBody());
    }


function get_filedisplay_views() {
    expTemplate::get_filedisplay_views();

    $paths = array(
        BASE.'framework/modules/common/views/file/',
        BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',
    );

    $views = array();
    foreach ($paths as $path) {
        if (is_readable($path)) {
            $dh = opendir($path);
            while (($file = readdir($dh)) !== false) {
                if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {
                    $filename = substr($file, 0, -4);
                    $views[$filename] = gt($filename);
                }
            }
        }
    }

    return $views;
}


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

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

        }

        return $url;
    }


	public function Archive()
	{

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

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

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.


		form_end_row();
		$i++;
	}

	html_end_box(false);

/*
	print "<pre>";
	if (isset($check) && is_array($check)) {
		print_r($check);
	}
	print "</pre>";
*/

}


            $q = self::query($sql);
        }

        return true;
    }


    public function testRedirectLinkGeneration () {
        Yii::app()->controller = new MarketingController (
            'campaign', new MarketingModule ('campaign', null));
        $_SERVER['SERVER_NAME'] = 'localhost';
        $cmb = $this->instantiate();
        $contact = $this->contacts('testUser_unsent');
        $campaign = $this->campaign('redirectLinkGeneration');
        $url = preg_replace ('/^[^"]*"([^"]*)".*$/', '$1', $campaign->content);
        list($subject,$message,$uniqueId) = $cmb->prepareEmail(
            $this->campaign('redirectLinkGeneration'),
            $contact);
        $this->assertRegExp ('/'.preg_quote (urlencode ($url)).'/', $message);

    }


    public function __construct(Database $database, $cookiePrefix = '')
    {
        parent::__construct($database, TBL_SESSIONS, 'ses');

        // determine session id
        if (array_key_exists(COOKIE_PREFIX . '_SESSION_ID', $_COOKIE)) {
            $sessionId = $_COOKIE[COOKIE_PREFIX . '_SESSION_ID'];
        } else {
            $sessionId = session_id();
        }

        $this->cookieAutoLoginId = $cookiePrefix . '_AUTO_LOGIN_ID';

        if (is_int($sessionId)) {
            $this->readDataById($sessionId);
        } else {
            $this->readDataByColumns(array('ses_session_id' => $sessionId));

            if ($this->newRecord) {
                // if PHP session id was commited then store them in that field
                $this->setValue('ses_session_id', $sessionId);
                $this->setValue('ses_timestamp', DATETIME_NOW);
            }
        }

        // check for a valid auto login
        $this->refreshAutoLogin();
    }

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 update()
    {
        try {
            $_recipients = array();
            if ($this->recipients != null) {
                foreach ($this->recipients as $_r) {
                    $_recipients[$_r->id] = $_r->sname . ' <' . $_r->email . '>';
                }
            }

            $sender = ($this->sender === 0) ?
                new Expression('NULL') : $this->sender;
            $sender_name = ($this->sender_name === null) ?
                new Expression('NULL') : $this->sender_name;
            $sender_address = ($this->sender_address === null) ?
                new Expression('NULL') : $this->sender_address;

            $values = array(
                'mailing_sender'            => $sender,
                'mailing_sender_name'       => $sender_name,
                'mailing_sender_address'    => $sender_address,
                'mailing_subject'           => $this->subject,
                'mailing_body'              => $this->message,
                'mailing_date'              => $this->date,
                'mailing_recipients'        => serialize($_recipients),
                'mailing_sent'              => ($this->sent) ?
                    true :
                    ($this->zdb->isPostgres() ? 'false' : 0)
            );

            $update = $this->zdb->update(self::TABLE);
            $update->set($values);
            $update->where(self::PK . ' = ' . $this->mailing->history_id);
            $this->zdb->execute($update);
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurend updating Mailing | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public function execute(&$params){
        $model = new Actions;
        $model->type = 'note';
        $model->complete = 'Yes';
        $model->associationId = $params['model']->id;
        $model->associationType = $params['model']->module;
        $model->actionDescription = $this->parseOption('comment', $params);
        $model->assignedTo = $this->parseOption('assignedTo', $params);
        $model->completedBy = $this->parseOption('assignedTo', $params);

        if(empty($model->assignedTo) && $params['model']->hasAttribute('assignedTo')){
            $model->assignedTo = $params['model']->assignedTo;
            $model->completedBy = $params['model']->assignedTo;
        }

        if($params['model']->hasAttribute('visibility'))
            $model->visibility = $params['model']->visibility;
        $model->createDate = time();
        $model->completeDate = time();

        if($model->save()){
            return array(
                true,
                Yii::t('studio', 'View created action: ').$model->getLink());
        }else{
            return array(false, array_shift($model->getErrors()));
        }
    }


    function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {

        if ($is_revisioned) {
            $object->revision_id++;
            //if ($table=="text") eDebug($object);
            $res = $this->insertObject($object, $table);
            //if ($table=="text") eDebug($object,true);
            $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);
            return $res;
        }
        $sql = "UPDATE " . $this->prefix . "$table SET ";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            //if($is_revisioned && $var=='revision_id') $val++;
            if ($var{0} != '_') {
                if (is_array($val) || is_object($val)) {
                    $val = serialize($val);
                    $sql .= "`$var`='".$val."',";
                } else {
                    $sql .= "`$var`='".mysqli_real_escape_string($this->connection,$val)."',";
                }
            }
        }
        $sql = substr($sql, 0, -1) . " WHERE ";
        if ($where != null)
            $sql .= $where;
        else
            $sql .= "`" . $identifier . "`=" . $object->$identifier;
        //if ($table == 'text') eDebug($sql,true);
        $res = (@mysqli_query($this->connection, $sql) != false);
        return $res;
    }


    public function testDisplayBlocksAcceptTemplateOnlyAsBlocks()
    {
        $template = $this->getMockForAbstractClass('Twig_Template', array(), '', false);
        $template->displayBlock('foo', array(), array('foo' => array(new stdClass(), 'foo')));
    }

Permissions, Privileges, and Access Controls

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


    private function _getMetaTags()
    {
        $retval  = '<meta charset="utf-8" />';
        $retval .= '<meta name="robots" content="noindex,nofollow" />';
        $retval .= '<meta http-equiv="X-UA-Compatible" content="IE=Edge">';
        $retval .= '<style>html{display: none;}</style>';
        return $retval;
    }


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

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

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

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

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

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


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


    function autoLogin()
    {
        $oPlugin = OA_Auth::staticGetAuthPlugin();

        phpAds_SessionStart();

        // No auto-login if auth is external
        if (empty($oPlugin) || (get_class($oPlugin) != 'Plugins_Authentication')) {
            phpAds_SessionDataDestroy();
            return;
        }

        $adminAccountId = OA_Dal_ApplicationVariables::get('admin_account_id');
        if (isset($adminAccountId)) {
            // Fetch the user linked to the admin account
            $doUser = OA_Dal::factoryDO('users');
            $doAUA = OA_Dal::factoryDO('account_user_assoc');
            $doAUA->account_id = $adminAccountId;
            $doUser->joinAdd($doAUA);
            $doUser->find();
            if ($doUser->fetch()) {
                phpAds_SessionRegenerateId();
                phpAds_SessionDataRegister(OA_Auth::getSessionData($doUser));
                phpAds_SessionDataStore();
            }
        }
    }

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


  public function __construct() {
    $this->pop_conn  = 0;
    $this->connected = false;
    $this->error     = null;
  }


    public function setObjectSrc(Response $response)
    {
        if (config('app.allow_content_scripts')) {
            return;
        }

        $response->headers->set('Content-Security-Policy', 'object-src \'self\'', false);
    }


function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params);
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);
            expHistory::back();
        }
    }


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    	return $text;
    }


                $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);
                if (!empty($newret)) $ret .= $newret . '<br>';
                if ($iLoc->mod == 'container') {
                    $ret .= scan_container($container->internal, $page_id);
                }
            }
            return $ret;
        }


				unset($map[$n], $n, $d);
			}
			unset($map);
			if(!self::$client) {
				self::$client = false;
			}
		}
	}

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


    public function testForWritableDir($value)
    {
        if (substr($value, 0, 7) === "phar://") {
            return 'Phar protocol not allowed.';
        }
        if (!is_dir($value)) {
            return 'Not a valid directory.';
        }
        if (!is_writeable($value)) {
            return 'Not a writable directory.';
        }
        return true;
    }


    public function getFilePath($fileName = null)
    {
        if ($fileName === null) {
            $fileName = $this->fileName;
        }

        // Limit paths to those under the assets directory
        $directory = $this->theme->getPath() . '/' . $this->dirName . '/';
        $path = realpath($directory . $fileName);
        if (!starts_with($path, $directory)) {
            return false;
        }

        return $path;
    }

The software allows user input to control or influence paths or file names that are used in filesystem operations.


function phpAds_SessionDataFetch()
{
    global $session;

    // Guard clause: Can't fetch a session without an ID
    if (empty($_COOKIE['sessionID']) || !preg_match('#^[0-9a-f]{32}$#D', $_COOKIE['sessionID'])) {
        return;
    }

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

    // Return if the session was not found (expired or forged)
    if (!$serialized_session) {
        return;
    }

    $loaded_session = unserialize($serialized_session);

    // Or if it can't be unserialized and/or is not a session we started
    if (empty($loaded_session['__authentic__'])) {
        return;
    }

    $session = $loaded_session;

    $dal->refreshSession($_COOKIE['sessionID']);
}


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

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


function render_menu_tabs()
    {
        $current_tab = $this->get_current_tab();

        echo '
';
        foreach ( $this->menu_tabs as $tab_key => $tab_caption )
        {
            $active = $current_tab == $tab_key ? 'nav-tab-active' : '';
            echo 'menu_page_slug . '&tab=' . $tab_key . '">' . $tab_caption . '';
        }
        echo '
';
    }


    public function testFromParts($input)
    {
        $uri = Uri::fromParts(parse_url($input));

        $this->assertSame($input, (string) $uri);
    }


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


	protected function _basename($path) {
		$parts = explode($this->separator, trim($path, $this->separator));
		return array_pop($parts);
	}


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

        $sql = "select DISTINCT(p.id) as id, p.title, model from " . $db->prefix . "product as p WHERE ";
        if (!($user->isAdmin())) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';

        //if first character of search is a -, then we do a wild card, else from beginning
        $this->params['query'] = expString::escape($this->params['query']);
        if ($this->params['query'][0] == '-') {
            $sql .= " p.model LIKE '%" . $this->params['query'];
        } else {
            $sql .= " p.model LIKE '" . $this->params['query'];
        }

        $sql .= "%' AND p.parent_id=0 GROUP BY p.id ";
        $sql .= "order by p.model ASC LIMIT 30";
        $res = $db->selectObjectsBySql($sql);
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    public function testPhpSession53()
    {
        if (PHP_VERSION_ID >= 50400) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $storage = $this->getStorage();

        $this->assertFalse(isset($_SESSION));
        $this->assertFalse($storage->getSaveHandler()->isActive());

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

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


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


    public function activate_discount(){
        if (isset($this->params['id'])) {
            $discount = new discounts($this->params['id']);
            $discount->update($this->params);
            //if ($discount->discountulator->hasConfig() && empty($discount->config)) {
                //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');
                //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));
            //}
        }

        expHistory::back();
    }


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

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

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


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

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


            $masteroption->delete();
        }

        // delete the mastergroup
        $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);
        $mastergroup->delete();

        expHistory::back();
    }


	function output( $p_format = 'dot', $p_headers = false ) {
		# Check if it is a recognized format.
		if( !isset( $this->formats[$p_format] ) ) {
			trigger_error( ERROR_GENERIC, ERROR );
		}

		$t_binary = $this->formats[$p_format]['binary'];
		$t_type = $this->formats[$p_format]['type'];
		$t_mime = $this->formats[$p_format]['mime'];

		# Send Content-Type header, if requested.
		if( $p_headers ) {
			header( 'Content-Type: ' . $t_mime );
		}
		# Retrieve the source dot document into a buffer
		ob_start();
		$this->generate();
		$t_dot_source = ob_get_contents();
		ob_end_clean();

		# Start dot process

		$t_command = $this->graphviz_tool . ' -T' . $p_format;
		$t_descriptors = array(
			0 => array( 'pipe', 'r', ),
			1 => array( 'pipe', 'w', ),
			2 => array( 'file', 'php://stderr', 'w', ),
			);

		$t_pipes = array();
		$t_process = proc_open( $t_command, $t_descriptors, $t_pipes );

		if( is_resource( $t_process ) ) {
			# Filter generated output through dot
			fwrite( $t_pipes[0], $t_dot_source );
			fclose( $t_pipes[0] );

			if( $p_headers ) {
				# Headers were requested, use another output buffer to
				# retrieve the size for Content-Length.
				ob_start();
				while( !feof( $t_pipes[1] ) ) {
					echo fgets( $t_pipes[1], 1024 );
				}
				header( 'Content-Length: ' . ob_get_length() );
				ob_end_flush();
			} else {
				# No need for headers, send output directly.
				while( !feof( $t_pipes[1] ) ) {
					print( fgets( $t_pipes[1], 1024 ) );
				}
			}

			fclose( $t_pipes[1] );
			proc_close( $t_process );
		}
	}

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.


            $q->close();
        }

        self::$num_rows = $n;

        return $r;
    }


    public function uploadAvatar(Request $request)
    {
        $user = auth()->user();

        if ($user && $request->hasFile('admin_avatar')) {
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromRequest('admin_avatar')
                ->toMediaCollection('admin_avatar');
        }

        if ($user && $request->has('avatar')) {
            $data = json_decode($request->avatar);
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromBase64($data->data)
                ->usingFileName($data->name)
                ->toMediaCollection('admin_avatar');
        }

        return new UserResource($user);
    }


    public function asText(ElementNode $el)
    {
        if (!$this->hasValidInputs($el)) {
            return $el->getAsBBCode();
        }

        $s = "";
        foreach ($el->getChildren() as $child)
            $s .= $child->getAsText();
        return $s;
    }


	private function _qualitypages( $option ) {
		if ( function_exists( 'efLoadFlaggedRevs' ) ) {
			//Do not add this again if 'stablepages' has already added it.
			if ( !$this->parametersProcessed['stablepages'] ) {
				$this->addJoin(
					'flaggedpages',
					[
						"LEFT JOIN",
						"page_id = fp_page_id"
					]
				);
			}
			switch ( $option ) {
				case 'only':
					$this->addWhere( 'fp_quality >= 1' );
					break;
				case 'exclude':
					$this->addWhere( 'fp_quality = 0' );
					break;
			}
		}
	}


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


    public function getQuerySelect()
    {
        return "a.per_tracker_artifact_id AS `" . $this->name . "`";
    }


	public function get($extramediatypes = false) {
		try {
			return $this->getConfig($extramediatypes);
		} catch (\Exception $exception) {
			return $this->jsonError($exception);
		}
	}


    public function renew2FaSecretAction(Request $request)
    {
        $this->checkCsrfToken($request);

        $user = $this->getAdminUser();
        $proxyUser = $this->getAdminUser(true);

        $twoFactorService = $this->get('scheb_two_factor.security.google_authenticator');
        $newSecret = $twoFactorService->generateSecret();
        $user->setTwoFactorAuthentication('enabled', true);
        $user->setTwoFactorAuthentication('type', 'google');
        $user->setTwoFactorAuthentication('secret', $newSecret);
        $user->save();

        Tool\Session::useSession(function (AttributeBagInterface $adminSession) {
            Tool\Session::regenerateId();
            $adminSession->set('2fa_required', true);
        });

        $twoFactorService = $this->get('scheb_two_factor.security.google_authenticator');
        $url = $twoFactorService->getQRContent($proxyUser);

        $code = new \Endroid\QrCode\QrCode;
        $code->setWriterByName('png');
        $code->setText($url);
        $code->setSize(200);

        $qrCodeFile = PIMCORE_PRIVATE_VAR . '/qr-code-' . uniqid() . '.png';
        $code->writeFile($qrCodeFile);

        $response = new BinaryFileResponse($qrCodeFile);

        return $response;
    }

Improper Restriction of Excessive Authentication Attempts

The software does not implement sufficient measures to prevent multiple failed authentication attempts within in a short time frame, making it more susceptible to brute force attacks.


    public function testNewInstanceWhenAddingHeaderThatWasNotThereBefore()
    {
        $r = new Response(200, ['Foo' => 'Bar']);
        $r2 = $r->withAddedHeader('Baz', 'Bam');
        $this->assertNotSame($r, $r2);
        $this->assertEquals('Bam', $r2->getHeaderLine('Baz'));
        $this->assertEquals('Bar', $r2->getHeaderLine('Foo'));
    }


    private static function restoreIniSettings () {
        foreach (self::$_savedIniSettings as $setting => $val) {
            if ($val !== null) {
                ini_set ($setting, $val);
            }
        }
    }


    private function doCreation(array $project, array $values)
    {
        $values['project_id'] = $project['id'];
        list($valid, ) = $this->actionValidator->validateCreation($values);

        if ($valid) {
            if ($this->actionModel->create($values) !== false) {
                $this->flash->success(t('Your automatic action have been created successfully.'));
            } else {
                $this->flash->failure(t('Unable to create your automatic action.'));
            }
        }

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

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.


	private function _maxrevisions( $option ) {
		$this->addWhere( "((SELECT count(rev_aux3.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux3 WHERE rev_aux3.revactor_page = {$this->tableNames['page']}.page_id) <= {$option})" );
	}


    public function show() {
        global $user;

        $id = !empty($this->params['id']) ? $this->params['id'] : null;

        // check to see if we should be editing.  You either need to be an admin, or viewing own account.
        if ($user->isAdmin() || ($user->id == $id)) {
            $u = new user($id);
            if ($u->isSuperAdmin() && $user->isActingAdmin()) {
                flash('error', gt('You do not have the proper permissions to view this record'));
                expHistory::back();
            }
            parent::show();
        } else {
            flash('error', gt('You do not have the proper permissions to view this record'));
            expHistory::back();
        }
    }

Exposure of Sensitive Information to an Unauthorized Actor

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


    public static function isHadSub($parent, $menuid =''){
        $sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
    }

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.


    protected function expandCSSEscape($string) {
        // flexibly parse it
        $ret = '';
        for ($i = 0, $c = strlen($string); $i < $c; $i++) {
            if ($string[$i] === '\\') {
                $i++;
                if ($i >= $c) {
                    $ret .= '\\';
                    break;
                }
                if (ctype_xdigit($string[$i])) {
                    $code = $string[$i];
                    for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
                        if (!ctype_xdigit($string[$i])) break;
                        $code .= $string[$i];
                    }
                    // We have to be extremely careful when adding
                    // new characters, to make sure we're not breaking
                    // the encoding.
                    $char = HTMLPurifier_Encoder::unichr(hexdec($code));
                    if (HTMLPurifier_Encoder::cleanUTF8($char) === '') continue;
                    $ret .= $char;
                    if ($i < $c && trim($string[$i]) !== '') $i--;
                    continue;
                }
                if ($string[$i] === "\n") continue;
            }
            $ret .= $string[$i];
        }
        return $ret;
    }

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.


    protected function itemLock($hashes, $autoUnlock = true)
    {
        if (!elFinder::$commonTempPath) {
            return;
        }
        if (!is_array($hashes)) {
            $hashes = array($hashes);
        }
        foreach ($hashes as $hash) {
            $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
            if ($this->itemLocked($hash)) {
                $cnt = file_get_contents($lock) + 1;
            } else {
                $cnt = 1;
            }
            if (file_put_contents($lock, $cnt, LOCK_EX)) {
                if ($autoUnlock) {
                    $this->autoUnlocks[] = $hash;
                }
            }
        }
    }

The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.


    public function hasParameter($name)
    {
        $name = (string) $name;
        $name = $this->normalizeParameterName($name);

        return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters);
    }

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 get_view_config() {
        global $template;

        // set paths we will search in for the view
        $paths = array(
            BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',
            BASE.'framework/modules/common/views/file/configure',
        );

        foreach ($paths as $path) {
            $view = $path.'/'.$this->params['view'].'.tpl';
            if (is_readable($view)) {
                if (bs(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                if (bs3(true)) {
                    $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';
                    if (file_exists($bstrapview)) {
                        $view = $bstrapview;
                    }
                }
                $template = new controllertemplate($this, $view);
                $ar = new expAjaxReply(200, 'ok');
		        $ar->send();
            }
        }
    }


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

	    $hv = new help_version();
	    $current_version = $hv->find('first', 'is_current=1');

	    $sql  = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';
	    $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';

	    $page = new expPaginator(array(
            'sql'=>$sql,
            'limit'=>30,
            'order'      => (isset($this->params['order']) ? $this->params['order'] : 'version'),
            'dir'        => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Version')=>'version',
                gt('Title')=>'title',
                gt('Current')=>'is_current',
                gt('# of Docs')=>'num_docs'
            ),
        ));

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

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.


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


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


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

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


function PMA_secureSession()
{
    // prevent session fixation and XSS
    // (better to use session_status() if available)
    if ((PMA_PHP_INT_VERSION >= 50400 && session_status() === PHP_SESSION_ACTIVE)
        || (PMA_PHP_INT_VERSION < 50400 && session_id() !== '')
    ) {
        session_regenerate_id(true);
    }
    $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));
}


    function setTimeoutIo($timeout_io)
    {
        $this->timeout_io = $timeout_io;
    }


	public function formatTemplateArg( $arg, $s, $argNr, $firstCall, $maxLength, Article $article ) {
		$tableFormat = $this->getParameters()->getParameter( 'tablerow' );
		// we could try to format fields differently within the first call of a template
		// currently we do not make such a difference

		// if the result starts with a '-' we add a leading space; thus we avoid a misinterpretation of |- as
		// a start of a new row (wiki table syntax)
		if ( array_key_exists( "$s.$argNr", $tableFormat ) ) {
			$n = -1;
			if ( $s >= 1 && $argNr == 0 && !$firstCall ) {
				$n = strpos( $tableFormat["$s.$argNr"], '|' );
				if ( $n === false || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '{' ) === false ) || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '[' ) === false ) ) {
					$n = -1;
				}
			}
			$result = str_replace( '%%', $arg, substr( $tableFormat["$s.$argNr"], $n + 1 ) );
			$result = str_replace( '%PAGE%', $article->mTitle->getPrefixedText(), $result );
			$result = str_replace( '%IMAGE%', $this->parseImageUrlWithPath( $arg ), $result ); //@TODO: This just blindly passes the argument through hoping it is an image.  --Alexia
			$result = $this->cutAt( $maxLength, $result );
			if ( strlen( $result ) > 0 && $result[0] == '-' ) {
				return ' ' . $result;
			} else {
				return $result;
			}
		}
		$result = $this->cutAt( $maxLength, $arg );
		if ( strlen( $result ) > 0 && $result[0] == '-' ) {
			return ' ' . $result;
		} else {
			return $result;
		}
	}

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 handleEnd(&$token) {
        // This is the WRONG way of handling the object and param stacks;
        // we should be inserting them directly on the relevant object tokens
        // so that the global stack handling handles it.
        if ($token->name == 'object') {
            array_pop($this->objectStack);
            array_pop($this->paramStack);
        }
    }


    public function squash($force = false) {
        if ($this->cache !== null && !$force) return $this->cache;
        if ($this->parent) {
            return $this->cache = array_merge($this->parent->squash($force), $this->data);
        } else {
            return $this->cache = $this->data;
        }
    }


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

		// Load profiler
		if (Kohana::config('config.enable_profiler'))
		{
			$this->profiler = new Profiler;
		}

		$this->auth = Auth::instance();

		$this->db = Database::instance();

		// Are we logged in? if not, do we have an auto-login cookie?
		if (! $this->auth->logged_in()) {
			// Try to login with 'remember me' token
			if (! $this->auth->auto_login())
			{
				// Login user in via HTTP AUTH
				$this->auth->http_auth_login();
			}
		}

		// Get session information
		$this->user = Auth::instance()->get_user();

		// Check private deployment access
		$controller_whitelist = array(
			'login',
			'riverid',
			'api'
		);

		if (Kohana::config('settings.private_deployment'))
		{
			if (!$this->auth->logged_in('login') AND ! in_array(Router::$controller, $controller_whitelist))
			{
				// Redirect to login form
				url::redirect('login');
			}
		}

		// Set default content-type header
		header('Content-type: text/html; charset=UTF-8');
	}


    public static function validateSignature(array $data, XMLSecurityKey $key)
    {
        assert('array_key_exists("Query", $data)');
        assert('array_key_exists("SigAlg", $data)');
        assert('array_key_exists("Signature", $data)');

        $query = $data['Query'];
        $sigAlg = $data['SigAlg'];
        $signature = $data['Signature'];

        $signature = base64_decode($signature);

        if ($key->type !== XMLSecurityKey::RSA_SHA1) {
            throw new \Exception('Invalid key type for validating signature on query string.');
        }
        if ($key->type !== $sigAlg) {
            $key = Utils::castKey($key, $sigAlg);
        }

        if (!$key->verifySignature($query, $signature)) {
            throw new \Exception('Unable to validate signature on query string.');
        }
    }

Improper Verification of Cryptographic Signature

The software does not verify, or incorrectly verifies, the cryptographic signature for data.


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


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

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


function wp_validate_redirect($location, $default = '') {
	$location = trim( $location );
	// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
	if ( substr($location, 0, 2) == '//' )
		$location = 'http:' . $location;

	// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
	$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;

	// @-operator is used to prevent possible warnings in PHP < 5.3.3.
	$lp = @parse_url($test);

	// Give up if malformed URL
	if ( false === $lp )
		return $default;

	// Allow only http and https schemes. No data:, etc.
	if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
		return $default;

	// Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
	if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
		return $default;
	}

	// Reject malformed components parse_url() can return on odd inputs.
	foreach ( array( 'user', 'pass', 'host' ) as $component ) {
		if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
			return $default;
		}
	}

	$wpp = parse_url(home_url());

	/**
	 * Filters the whitelist of hosts to redirect to.
	 *
	 * @since 2.3.0
	 *
	 * @param array       $hosts An array of allowed hosts.
	 * @param bool|string $host  The parsed host; empty if not isset.
	 */
	$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );

	if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
		$location = $default;

	return $location;
}

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 showByModel() {
        global $order, $template, $db;

        expHistory::set('viewable', $this->params);
        $product = new product();
        $model = $product->find("first", 'model="' . $this->params['model'] . '"');
        //eDebug($model);
        $product_type = new $model->product_type($model->id);
        //eDebug($product_type);
        $tpl = $product_type->getForm('show');
        if (!empty($tpl)) $template = new controllertemplate($this, $tpl);
        //eDebug($template);
        $this->grabConfig(); // grab the global config
        assign_to_template(array(
            'config'        => $this->config,
            'product'       => $product_type,
            'last_category' => $order->lastcat
        ));
    }


public static function insert ($vars) {
        if(is_array($vars)){
            $set = "";
            $k = "";
            foreach ($vars['key'] as $key => $val) {
                $set .= "'$val',";
                $k .= "`$key`,";
            }

            $set = substr($set, 0,-1);
            $k = substr($k, 0,-1);

            $sql = sprintf("INSERT INTO `%s` (%s) VALUES (%s) ", $vars['table'], $k, $set) ;
        }else{
            $sql = $vars;
        }
        if(DB_DRIVER == 'mysql') {
            mysql_query('SET CHARACTER SET utf8');
            $q = mysql_query($sql) or die(mysql_error());
            self::$last_id = mysql_insert_id();
        }elseif(DB_DRIVER == 'mysqli'){
            try {
                if(!self::query($sql)){
                    printf("
Errormessage: %s
\n", self::$mysqli->error);
                }else{
                    self::$last_id = self::$mysqli->insert_id;
                }

            } catch (exception $e) {
                echo $e->getMessage();
            }

        }

        return true;
    }


    public function __construct()
    {
        self::setActive();
    }


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

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

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


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


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

        $details = Shopware()->Modules()->Marketing()->sMailCampaignsGetDetail((int) $id);

        foreach ($details['containers'] as $key => $container) {
            if ($container['type'] === 'ctVoucher') {
                if (!empty($container['value'])) {
                    $details['voucher'] = $container['value'];
                }
                $details['containers'][$key]['type'] = 'ctText';
            }
            if ($container['type'] === 'ctSuggest') {
                $details['suggest'] = true;
            }
        }

        return $details;
    }


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

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

    if($typeid = getResourceTypeID($type)){
        if(!checkForGroupName($name, 'resource', '', $typeid)){
            return array('status' => 'error',
                         'errorcode' => 28,
                         'errormsg' => 'resource group does not exist');
        }
        $perms = explode(':', $permissions);
        updateResourcePrivs("$type/$name", $nodeid, $perms, array());
        return array('status' => 'success');
    } else {
        return array('status' => 'error',
                     'errorcode' => 56,
                     'errormsg' => 'Invalid resource type');
    }
}


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

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


	protected function Start()
	{
		$sCurrentStepClass = $this->sInitialStepClass;
		$oStep = new $sCurrentStepClass($this, $this->sInitialState);
		$this->DisplayStep($oStep);
	}


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

        //print_r($cat);
    }


		public function renameRemote($oldName, $newName)
		{
			$this->run('remote', 'rename', $oldName, $newName);
			return $this;
		}

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


    public function resetAccessed() {
        $this->accessed = array();
    }


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

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


    public function disconnect()
    {
        $this->sendString('QUIT');
        //The QUIT command may cause the daemon to exit, which will kill our connection
        //So ignore errors here
        try {
            @fclose($this->pop_conn);
        } catch (Exception $e) {
            //Do nothing
        };
    }


    public function handle($request, Closure $next)
    {
        view()->share('cspNonce', $this->cspService->getNonce());
        if ($this->cspService->allowedIFrameHostsConfigured()) {
            config()->set('session.same_site', 'none');
        }

        $response = $next($request);

        $this->cspService->setFrameAncestors($response);
        $this->cspService->setScriptSrc($response);
        $this->cspService->setObjectSrc($response);
        $this->cspService->setBaseUri($response);

        return $response;
    }


    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 static function desc($vars){
        if(!empty($vars)){
            $desc = substr(strip_tags(htmlspecialchars_decode($vars).". ".self::$desc),0,150);
        }else{
            $desc = substr(self::$desc,0,150);
        }

        return $desc;
    }


    public static function DragnDropReRank2() {
        global $router, $db;

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

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

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

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


    private function _collapseStack($stack) {
        $result = array();
        $is_folder = false;
        for ($i = 0; isset($stack[$i]); $i++) {
            $is_folder = false;
            // absorb an internally duplicated slash
            if ($stack[$i] == '' && $i && isset($stack[$i+1])) continue;
            if ($stack[$i] == '..') {
                if (!empty($result)) {
                    $segment = array_pop($result);
                    if ($segment === '' && empty($result)) {
                        // error case: attempted to back out too far:
                        // restore the leading slash
                        $result[] = '';
                    } elseif ($segment === '..') {
                        $result[] = '..'; // cannot remove .. with ..
                    }
                } else {
                    // relative path, preserve the double-dots
                    $result[] = '..';
                }
                $is_folder = true;
                continue;
            }
            if ($stack[$i] == '.') {
                // silently absorb
                $is_folder = true;
                continue;
            }
            $result[] = $stack[$i];
        }
        if ($is_folder) $result[] = '';
        return $result;
    }


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

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

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

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

        $this->validatePathLength();
    }


    public function tearDown () {
        // try to replace mocks with original components in case mocks were set during test case
        TestingAuxLib::restoreX2WebUser ();
        TestingAuxLib::restoreX2AuthManager ();
        return parent::tearDown ();
    }


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


    private function doCreation(array $project, array $values)
    {
        $values['project_id'] = $project['id'];
        list($valid, ) = $this->actionValidator->validateCreation($values);

        if ($valid) {
            if ($this->actionModel->create($values) !== false) {
                $this->flash->success(t('Your automatic action have been created successfully.'));
            } else {
                $this->flash->failure(t('Unable to create your automatic action.'));
            }
        }

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


            } elseif ($key === 'allowedProtocols') {
                $this->setAllowedProtocols($value);
            } elseif ($key === 'logOutputFile' || $key === 'log_output_file') {


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

		$result = false;

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

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

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

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

				break;

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

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

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

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

				return $result ? $path : false;

				break;
		}

		return false;
	}


            foreach ($this->fixesForLevel[$level] as $fix) {
                $ret[$fix] = true;
            }


    public function start()
    {
        if ($this->started) {
            return true;
        }

        $this->loadSession();
        if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
            // This condition matches only PHP 5.3 + internal save handlers
            $this->saveHandler->setActive(true);
        }

        return true;
    }


                    elseif ($permission == $rolePermission && $rolePermissions[$permission] == 1) {
                        $matched = true;
                        break;
                    }


function csv_escape_string( $p_string ) {
	# Prevent CSV injection by escaping text that could be interpreted as a formula
	if( $p_string && strpos( '=-+@', $p_string[0] ) !== false ) {
		# Prefixing with a tab rather than single quote, as Excel does not show
		# the tab visually in the cell.
		$p_string = "\t" . $p_string;
	}

	$t_escaped = str_split( '"' . csv_get_separator() . csv_get_newline() );
	$t_must_escape = false;
	while( ( $t_char = current( $t_escaped ) ) !== false && !$t_must_escape ) {
		$t_must_escape = strpos( $p_string, $t_char ) !== false;
		next( $t_escaped );
	}
	if( $t_must_escape ) {
		$p_string = '"' . str_replace( '"', '""', $p_string ) . '"';
	}

	return $p_string;
}

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.


    protected function generateCookieHash($class, $username, $expires, $password)
    {
        return hash_hmac('sha256', $class.self::COOKIE_DELIMITER.$username.self::COOKIE_DELIMITER.$expires.self::COOKIE_DELIMITER.$password, $this->getSecret());
    }

When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.


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

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

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

            $replacements[] = $expanded;
        }

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

        return $ret;
    }


	public function tmb($hash) {
		$path = $this->decode($hash);
		$stat = $this->stat($path);

		if (isset($stat['tmb'])) {
			return $stat['tmb'] == "1" ? $this->createTmb($path, $stat) : $stat['tmb'];
		}
		return false;
	}


function execute_backup($command) {
	$backup_options = get_option('dbmanager_options');
	check_backup_files();

	if( realpath( $backup_options['path'] ) === false ) {
		return sprintf( __( '%s is not a valid backup path', 'wp-dbmanager' ), stripslashes( $backup_options['path'] ) );
	} else if( dbmanager_is_valid_path( $backup_options['mysqldumppath'] ) === 0 ) {
		return sprintf( __( '%s is not a valid mysqldump path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqldumppath'] ) );
	} else if( dbmanager_is_valid_path( $backup_options['mysqlpath'] ) === 0 ) {
		return sprintf( __( '%s is not a valid mysql path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqlpath'] ) );
	}

	if(substr(PHP_OS, 0, 3) == 'WIN') {
		$writable_dir = $backup_options['path'];
		$tmpnam = $writable_dir.'/wp-dbmanager.bat';
		$fp = fopen($tmpnam, 'w');
		fwrite($fp, $command);
		fclose($fp);
		system($tmpnam.' > NUL', $error);
		unlink($tmpnam);
	} else {
		passthru($command, $error);
	}
	return $error;
}

Weaknesses in this category are related to the management of credentials.


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

        $out = array();

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

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

        return $out;
    }


function is_proper_view_name( $string )
{
  if(preg_match("/[^a-zA-z0-9_\-\ ]/", $string)){
    return false;
  } else {
    return true;
  }
}


	public function delete() {
	    global $user;

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


	function execute( $par ) {
		$this->setHeaders();
		$this->outputHeader();

		$pager = new GlobalNewFilesPager();

		$this->getOutput()->addParserOutputContent( $pager->getFullOutput() );
	}


                    $forwardedValues[$k] = substr_replace($v, '0.0.0.0', 0, strrpos($v, ':'));
                }
            }
        }


    private function defaultParse($bbcode)
    {
        $parser = new JBBCode\Parser();
        $parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
        $parser->parse($bbcode);
        return $parser->getAsHtml();
    }


$f = function (\Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition $v) { return $v; }; return $f(${($_ = isset($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber']) ? $this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] : ($this->services['Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber())) && false ?: '_'});


    private function _testPermissions($dir, $chmod) {
        // early abort, if it is writable, everything is hunky-dory
        if (is_writable($dir)) return true;
        if (!is_dir($dir)) {
            // generally, you'll want to handle this beforehand
            // so a more specific error message can be given
            trigger_error('Directory '.$dir.' does not exist',
                E_USER_WARNING);
            return false;
        }
        if (function_exists('posix_getuid')) {
            // POSIX system, we can give more specific advice
            if (fileowner($dir) === posix_getuid()) {
                // we can chmod it ourselves
                $chmod = $chmod | 0700;
                if (chmod($dir, $chmod)) return true;
            } elseif (filegroup($dir) === posix_getgid()) {
                $chmod = $chmod | 0070;
            } else {
                // PHP's probably running as nobody, so we'll
                // need to give global permissions
                $chmod = $chmod | 0777;
            }
            trigger_error('Directory '.$dir.' not writable, '.
                'please chmod to ' . decoct($chmod),
                E_USER_WARNING);
        } else {
            // generic error message
            trigger_error('Directory '.$dir.' not writable, '.
                'please alter file permissions',
                E_USER_WARNING);
        }
        return false;
    }


                $length = strlen($part);
                if ($part[$length - 1] === '%') {
                    // handle percents
                    if (!$type) {
                        $type = 'percentage';
                    } elseif ($type !== 'percentage') {
                        return false;
                    }
                    $num = (float) substr($part, 0, $length - 1);
                    if ($num < 0) $num = 0;
                    if ($num > 100) $num = 100;
                    $new_parts[] = "$num%";
                } else {
                    // handle integers
                    if (!$type) {
                        $type = 'integer';
                    } elseif ($type !== 'integer') {
                        return false;
                    }
                    $num = (int) $part;
                    if ($num < 0) $num = 0;
                    if ($num > 255) $num = 255;
                    $new_parts[] = (string) $num;
                }
            }
            $new_triad = implode(',', $new_parts);
            $color = "rgb($new_triad)";
        } else {
            // hexadecimal handling
            if ($color[0] === '#') {
                $hex = substr($color, 1);
            } else {
                $hex = $color;
                $color = '#' . $color;
            }
            $length = strlen($hex);
            if ($length !== 3 && $length !== 6) return false;
            if (!ctype_xdigit($hex)) return false;
        }

        return $color;

    }


    public function testUserCredentials($email, $password, $server, $port, $security) {
        require_once(
            realpath(Yii::app()->basePath.'/components/phpMailer/PHPMailerAutoload.php'));
        $phpMail = new PHPMailer(true);

        $phpMail->isSMTP();
        $phpMail->SMTPAuth = true;
        $phpMail->Username = $email;
        $phpMail->Password = $password;
        $phpMail->Host = $server;
        $phpMail->Port = $port;
        $phpMail->SMTPSecure = $security;

        try {
            $validCredentials = $phpMail->SmtpConnect();
        } catch(phpmailerException $error) {
            $validCredentials = false;
        }
        return $validCredentials;
    }


	protected function imageMagickConvertPrepare($path, $destformat, $jpgQuality, $imageSize = null) {
		if (is_null($imageSize)) {
			$imageSize = getimagesize($path);
		}
		if (!$imageSize) {
			return array();
		}
		$srcType = $this->getExtentionByMime($imageSize['mime'], ':');
		$ani = false;
		$cmd = 'identify ' . escapeshellarg($srcType . $path);
		if ($this->procExec($cmd, $o) === 0) {
			$ani = preg_split('/(?:\r\n|\n|\r)/', trim($o));
			if (count($ani) < 2) {
				$ani = false;
			}
		}
		$coalesce = $index = '';
		$deconstruct = ' +repage';
		if ($ani) {
			if (is_null($destformat)) {
				$coalesce = ' -coalesce -repage 0x0';
				$deconstruct = ' +repage -deconstruct -layers optimize';
			} else {
				$index = '[0]';
				if ($srcType === 'ico:') {
					foreach($ani as $_i => $_info) {
						if (preg_match('/ (\d+)x(\d+) /', $_info, $m)) {
							if ($m[1] == $imageSize[0] && $m[2] == $imageSize[1]) {
								$index = '[' . $_i . ']';
								break;
							}
						}
					}
				}
			}
		}
		if ($imageSize[2] === IMAGETYPE_JPEG || $imageSize[2] === IMAGETYPE_JPEG2000) {
			$jpgQuality = ' -quality ' . $jpgQuality;
		} else {
			$jpgQuality = '';
		}
		$quotedPath = escapeshellarg($srcType . $path . $index);
		$quotedDstPath = escapeshellarg(($destformat? ($destformat . ':') : $srcType) . $path);
		return compact('ani', 'index', 'coalesce', 'deconstruct', 'jpgQuality', 'quotedPath', 'quotedDstPath');
	}


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

        $this->response->html($this->template->render('subtask_restriction/show', array(
            'status_list' => array(
                SubtaskModel::STATUS_TODO => t('Todo'),
                SubtaskModel::STATUS_DONE => t('Done'),
            ),
            'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    public function getQuerySelect()
    {
        return '';
    }


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

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


    public function getError()
    {
        return $this->error;
    }


    public static function gZip()
    {

        #ob_start(ob_gzhandler);
        // ob_start('Site::minifyHTML');
        ob_start();
        ob_implicit_flush(0);
    }


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

                break;

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

        }

        return $url;
    }


	public function update() {
        global $user;

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


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

        $this->params['author'] = expString::escape($this->params['author']);
        $user = user::getUserByName($this->params['author']);
		$page = new expPaginator(array(
            'model'=>$this->basemodel_name,
            'where'=>($this->aggregateWhereClause()?$this->aggregateWhereClause()." AND ":"")."poster=".$user->id,
            'limit'=>isset($this->config['limit']) ? $this->config['limit'] : 10,
            'order'=>'publish',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title'
            ),
        ));

		assign_to_template(array(
            'page'=>$page,
            'moduletitle'=>gt('Blogs by author').' "'.$this->params['author'].'"'
        ));
	}


                    $db->updateObject($value, 'section');
                }
                $db->updateObject($moveSec, 'section');
                //handle re-ranking of previous parent
                $oldSiblings = $db->selectObjects("section", "parent=" . $oldParent . " AND rank>" . $oldRank . " ORDER BY rank");
                $rerank      = 1;
                foreach ($oldSiblings as $value) {
                    if ($value->id != $moveSec->id) {
                        $value->rank = $rerank;
                        $db->updateObject($value, 'section');
                        $rerank++;
                    }
                }
                if ($oldParent != $moveSec->parent) {
                    //we need to re-rank the children of the parent that the moving section has just left
                    $childOfLastMove = $db->selectObjects("section", "parent=" . $oldParent . " ORDER BY rank");
                    for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {
                        $childOfLastMove[$i]->rank = $i;
                        $db->updateObject($childOfLastMove[$i], 'section');
                    }
                }
            }
        }
        self::checkForSectionalAdmins($move);
        expSession::clearAllUsersSessionCache('navigation');
    }


    private function __search_query($cmd)
    {
        $cmd .= $this->__url . " -s '" . $this->__setup['dataset'] . "'";
        return $this->__simple_query($cmd);
    }


    public function replace($def, $config) {
        $status = parent::replace($def, $config);
        if (!$status) parent::cleanup($config);
        return $status;
    }


			addUserGroupMember($esc_user, $rc['id']);
		else
			$fails[] = $_user;
	}
	if(count($fails)) {
		$cnt = 'some';
		$code = 34;
		if(count($fails) == count($users)) {
			$cnt = 'all submitted';
			$code = 35;
		}
		return array('status' => 'warning',
		             'failedusers' => $fails,
		             'warningcode' => $code,
		             'warningmsg' => "failed to add $cnt users to user group");
	}
	return array('status' => 'success');
}

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


    public function testVersion()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
        $this->assertAccessIsGranted($client, '/api/version');
        $result = json_decode($client->getResponse()->getContent(), true);

        $this->assertIsArray($result);

        $this->assertArrayHasKey('version', $result);
        $this->assertArrayHasKey('versionId', $result);
        $this->assertArrayHasKey('candidate', $result);
        $this->assertArrayHasKey('semver', $result);
        $this->assertArrayHasKey('name', $result);
        $this->assertArrayHasKey('copyright', $result);

        $this->assertSame(Constants::VERSION, $result['version']);
        $this->assertSame(Constants::VERSION_ID, $result['versionId']);
        $this->assertEquals(Constants::STATUS, $result['candidate']);
        $this->assertEquals(Constants::VERSION . '-' . Constants::STATUS, $result['semver']);
        $this->assertEquals(Constants::NAME, $result['name']);
        $this->assertEquals(
            'Kimai - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.',
            $result['copyright']
        );
    }


    public static function getDueDate(Db $zdb, $member_id)
    {
        if (!$member_id) {
            return '';
        }
        try {
            $select = $zdb->select(self::TABLE, 'c');
            $select->columns(
                array(
                    'max_date' => new Expression('MAX(date_fin_cotis)')
                )
            )->join(
                array('ct' => PREFIX_DB . ContributionsTypes::TABLE),
                'c.' . ContributionsTypes::PK . '=ct.' . ContributionsTypes::PK,
                array()
            )->where(
                Adherent::PK . ' = ' . $member_id
            )->where(
                array('cotis_extension' => new Expression('true'))
            );

            $results = $zdb->execute($select);
            $result = $results->current();
            $due_date = $result->max_date;

            //avoid bad dates in postgres and bad mysql return from zenddb
            if ($due_date == '0001-01-01 BC' || $due_date == '1901-01-01') {
                $due_date = '';
            }
            return $due_date;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred trying to retrieve member\'s due date',
                Analog::ERROR
            );
            throw $e;
        }
    }


private function SendHello($hello, $host) {
    fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);

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

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

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

    $this->helo_rply = $rply;

    return true;
  }


    public function cleanup($config) {
        return false;
    }


	public function Delete() {

		// Delete "main" ticket
		$del_stmt = Database::prepare('
			DELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'
		);
		Database::pexecute($del_stmt, array('tid' => $this->tid));

		// Delete "answers" to ticket"
		$del_stmt = Database::prepare('
			DELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `answerto` = :tid'
		);
		Database::pexecute($del_stmt, array('tid' => $this->tid));
		return true;
	}

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


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


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


    public function isValid() {
        if ($this->isValid === null) $this->isValid = $this->validate();
        return $this->isValid;
    }


    function reset_stats() {
//        global $db;

        // reset the counters
//        $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');
        banner::resetImpressions();
//        $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');
        banner::resetClicks();

        // let the user know we did stuff.
        flash('message', gt("Banner statistics reset."));
        expHistory::back();
    }


    public function withParsedBody($data)
    {
        $new = clone $this;
        $new->parsedBody = $data;

        return $new;
    }