mcanoglu/cwe-class-group huggingface dataset:
public function loginForm( WebRequest $request ) { // Step 13
		$out = $this->getOutput();
		$username = $request->getVal('username');
		$codes = SOA2Login::codes( $username );
		$out->addHTML(Html::openElement('form', [ 'method' => 'POST' ]));
		$out->addHTML(Html::hidden('username', $username));
		$out->addHTML(Html::hidden('token', $codes['csrf'])); // Step 14
		$profile = Html::element(
			'a',
			[
				'href' => sprintf(SOA2_PROFILE_URL, urlencode($username)),
				'target' => '_new'
			],
			wfMessage('soa2-your-profile')->plain()
		);
		// Step 16
		$out->addHTML(Html::rawElement(
			'p', [],
			wfMessage('soa2-vercode-explanation')->rawParams($profile)->parse()
		));
		$out->addHTML(Html::rawElement('p', [], Html::element(
			'code', [], $codes['code']
		)));
		$out->addHTML(Html::rawElement('p', [], Html::submitButton(
			wfMessage('soa2-login')->plain(), []
		)));
		$out->addHTML(Html::closeElement('form'));
	}

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

// Vulnerability class: CWE-200
public function update_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);
        // find required shipping method if needed
        if ($this->params['required_shipping_calculator_id'] > 0) {
            $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];
        } else {
            $this->params['required_shipping_calculator_id'] = 0;
        }
        
        $discount->update($this->params);
        expHistory::back();
    }

// Vulnerability class: CWE-74
public function chmod() {
        if (!AuthUser::hasPermission('file_manager_chmod')) {
            Flash::set('error', __('You do not have sufficient permissions to change the permissions on a file or directory.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

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

        if (file_exists($file)) {
            if (@!chmod($file, octdec($data['mode'])))
                Flash::set('error', __('Permission denied!'));
        }
        else {
            Flash::set('error', __('File or directory not found!'));
        }

        $path = substr($data['name'], 0, strrpos($data['name'], '/'));
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }

// Vulnerability class: CWE-20
public function testGetDropdownValue($params, $expected, $session_params = []) {
      $this->login();

      $bkp_params = [];
      //set session params if any
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($_SESSION[$param])) {
               $bkp_params[$param] = $_SESSION[$param];
            }
            $_SESSION[$param] = $value;
         }
      }

      $params['_idor_token'] = \Session::getNewIDORToken($params['itemtype'] ?? '');

      $result = \Dropdown::getDropdownValue($params, false);

      //reset session params before executing test
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($bkp_params[$param])) {
               $_SESSION[$param] = $bkp_params[$param];
            } else {
               unset($_SESSION[$param]);
            }
         }
      }

      $this->array($result)->isIdenticalTo($expected);
   }

// Vulnerability class: CWE-862
foreach($paths as $path)
			{
				// Convert wild-cards to RegEx
				$path = str_replace(array(':any', '*'), '.*', str_replace(':num', '[0-9]+', $path));

				// Does the RegEx match?
				if (!empty($_SERVER['HTTP_HOST']) AND preg_match('#^'.$path.'$#', $_SERVER['HTTP_HOST']))
				{
					define('ENVIRONMENT', $env);
					break 2;
				}
			}

// Vulnerability class: CWE-74
private function _allrevisionsbefore( $option ) {
		$this->addTable( 'revision_actor_temp', 'rev' );
		$this->addSelect(
			[
				'rev.revactor_rev',
				'rev.revactor_timestamp'
			]
		);
		$this->addOrderBy( 'rev.revactor_rev' );
		$this->setOrderDir( 'DESC' );
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )
			]
		);
	}

// Vulnerability class: CWE-400
$eml->prepareBody();
		}

        list ($success, $message) = $this->checkDoNotEmailFields ($eml);
        if (!$success) {
            return array ($success, $message);
        }

		$result = $eml->send($historyFlag);
		if (isset($result['code']) && $result['code'] == 200) {
            if (YII_UNIT_TESTING) {
                return array(true, $eml->message);
            } else {
                return array(true, "");
            }
        } else {
            return array (false, Yii::t('app', "Email could not be sent"));
        }
	}

// Vulnerability class: CWE-20
public function search(){
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $username = Yii::app()->user->name;
        $criteria->addCondition("uploadedBy='$username' OR private=0 OR private=null");
        $criteria->addCondition("associationType != 'theme'");
        return $this->searchBase($criteria);
    }

// Vulnerability class: CWE-20
function XMLRPCremoveResourceGroupPriv($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 remove group privileges on 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, array(), $perms);
        return array('status' => 'success');
    } else {
        return array('status' => 'error',
                     'errorcode' => 56,
                     'errormsg' => 'Invalid resource type');
    }
}

// Vulnerability class: CWE-20
foreach ($nodes as $node) {
            if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
                if ($node->active == 1) {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
                } else {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
                }
                $ar[$node->id] = $text;
                foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
                    $ar[$id] = $text;
                }
            }
        }

// Vulnerability class: CWE-74
public function execute(&$params){
        $action = new Actions;
        $action->associationType = lcfirst(get_class($params['model']));
        $action->associationId = $params['model']->id;
        $action->subject = $this->parseOption('subject', $params);
        $action->actionDescription = $this->parseOption('description', $params);
        if($params['model']->hasAttribute('assignedTo'))
            $action->assignedTo = $params['model']->assignedTo;
        if($params['model']->hasAttribute('priority'))
            $action->priority = $params['model']->priority;
        if($params['model']->hasAttribute('visibility'))
            $action->visibility = $params['model']->visibility;

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

    }

// Vulnerability class: CWE-20
public function renameTag($oldName, $newName)
		{
			// http://stackoverflow.com/a/1873932
			// create new as alias to old (`git tag NEW OLD`)
			$this->run('tag', $newName, $oldName);
			// delete old (`git tag -d OLD`)
			$this->removeTag($oldName);
			return $this;
		}

// Vulnerability class: CWE-77
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();
    }

// Vulnerability class: CWE-74
static function getRSSFeed($url, $cache_duration = DAY_TIMESTAMP) {
      global $CFG_GLPI;

      $feed = new SimplePie();
      $feed->set_cache_location(GLPI_RSS_DIR);
      $feed->set_cache_duration($cache_duration);

      // proxy support
      if (!empty($CFG_GLPI["proxy_name"])) {
         $prx_opt = [];
         $prx_opt[CURLOPT_PROXY]     = $CFG_GLPI["proxy_name"];
         $prx_opt[CURLOPT_PROXYPORT] = $CFG_GLPI["proxy_port"];
         if (!empty($CFG_GLPI["proxy_user"])) {
            $prx_opt[CURLOPT_HTTPAUTH]     = CURLAUTH_ANYSAFE;
            $prx_opt[CURLOPT_PROXYUSERPWD] = $CFG_GLPI["proxy_user"].":".
                                             Toolbox::decrypt($CFG_GLPI["proxy_passwd"],
                                                              GLPIKEY);
         }
         $feed->set_curl_options($prx_opt);
      }

      $feed->enable_cache(true);
      $feed->set_feed_url($url);
      $feed->force_feed(true);
      // Initialize the whole SimplePie object.  Read the feed, process it, parse it, cache it, and
      // all that other good stuff.  The feed's information will not be available to SimplePie before
      // this is called.
      $feed->init();

      // We'll make sure that the right content type and character encoding gets set automatically.
      // This function will grab the proper character encoding, as well as set the content type to text/html.
      $feed->handle_content_type();
      if ($feed->error()) {
         return false;
      }
      return $feed;
   }

// Vulnerability class: CWE-327
static function authenticate() {
        if (isset($_REQUEST['backend_login'])) {
            $user = DB_DataObject::factory('users');
            $user->active = true;
            $user->name = $_REQUEST['username'];
            $user->find(true);

            // Don't look whether that user exists, so we give less timing information
            // Instead, rely only on having a matching password
            $proffered_password = $_REQUEST['password'];
            if (in_array(
                $user->password,
                self::password_hashes($proffered_password, $user->password_salt)
            )) {
                // Regenerate the session ID, unless it's an IE we're talking to which would use the old session ID to load the frame contents
                // Remove this guard once we no longer use frames
                if(!preg_match('/(?i)msie /', $_SERVER['HTTP_USER_AGENT'])) {
                    session_regenerate_id();
                }
                $user->login();
                
                return $user;
            } else {
                Log::warn("Failed login for user name '".$_REQUEST['username']."' from " . $_SERVER['REMOTE_ADDR'].' user-agent '.$_SERVER['HTTP_USER_AGENT']);
                return -1;
            }
        }
        return false;
    }

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

        if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);
        // eDebug($sql, true);
        
        // count the unapproved comments
        if ($require_approval == 1 && $user->isAdmin()) {
            $sql  = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';
            $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';
            $sql .= 'WHERE cnt.content_id='.$this->params['content_id']." AND cnt.content_type='".$this->params['content_type']."' ";
            $sql .= 'AND com.approved=0';
            $unapproved = $db->countObjectsBySql($sql);
        } else {
            $unapproved = 0;
        }        
        
        $this->config = $this->params['config'];
        $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');
        $ratings = !empty($this->params['ratings']) ? true : false;

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

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

// Vulnerability class: CWE-20
public function edit()
    {
        if((isset($this->params['id']))) $record = new address(intval($this->params['id']));
        else $record = null;
        $config = ecomconfig::getConfig('address_allow_admins_all');
        assign_to_template(array(
            'record'=>$record,
            'admin_config'=>$config
        ));
        if (expSession::get('customer-signup')) {
            assign_to_template(array(
                'checkout'=>true
            ));
        }
    }

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

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

// Vulnerability class: CWE-400
static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,
                                   $onlyglobal = 0, $used = []) {
      global $CFG_GLPI;

      $rand     = mt_rand();

      $field_id = Html::cleanId("dropdown_".$myname.$rand);
      $param    = [
         'entity_restrict' => $entity_restrict,
         'fromtype'        => $fromtype,
         'itemtype'        => $itemtype,
         'onlyglobal'      => $onlyglobal,
         'used'            => $used,
         '_idor_token'     => Session::getNewIDORToken($itemtype),
      ];

      echo Html::jsAjaxDropdown($myname, $field_id,
                                $CFG_GLPI['root_doc']."/ajax/getDropdownConnect.php",
                                $param);

      return $rand;
   }

// Vulnerability class: CWE-862
public function checkHTTP($link, $get_body = false)
    {
        if (! function_exists('curl_init')) {
            return null;
        }
        $handle = curl_init($link);
        if ($handle === false) {
            return null;
        }
        PMA_Util::configureCurl($handle);
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 5);
        curl_setopt($handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        if (! defined('TESTSUITE')) {
            session_write_close();
        }
        $data = @curl_exec($handle);
        if (! defined('TESTSUITE')) {
            ini_set('session.use_only_cookies', '0');
            ini_set('session.use_cookies', '0');
            ini_set('session.use_trans_sid', '0');
            ini_set('session.cache_limiter', 'nocache');
            session_start();
        }
        if ($data === false) {
            return null;
        }
        $http_status = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        if ($http_status == 200) {
            return $get_body ? $data : true;
        }

        if ($http_status == 404) {
            return false;
        }
        return null;
    }

// Vulnerability class: CWE-20
public function testGetEventsPublicProfile(){
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('testuser');

        Yii::app()->settings->historyPrivacy = null;
        $lastEventId=0;
        $lastTimestamp=0;
        $myProfile = Profile::model()->findByAttributes(array('username' => 'testuser2'));
        $events=Events::getEvents(
            $lastEventId,$lastTimestamp,null,$myProfile, false);
        $this->assertEquals (
            array_map (
                function ($event) { return $event->id; }, 
                Events::model ()->findAllByAttributes (array (
                    'user' => 'testuser2',
                    'visibility' => 1 
                ))
            ),
            array_map (function ($event) { return $event->id; }, $events['events']));

        TestingAuxLib::restoreX2WebUser ();
    }

// Vulnerability class: CWE-20
public static function getItems($term) {
        $model = X2Model::model(Yii::app()->controller->modelClass);
        if (isset($model)) {
            $tableName = $model->tableName();
            $sql = 'SELECT id, name as value 
                 FROM ' . $tableName . ' WHERE name LIKE :qterm ORDER BY name ASC';
            $command = Yii::app()->db->createCommand($sql);
            $qterm = $term . '%';
            $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
            $result = $command->queryAll();
            echo CJSON::encode($result);
        }
        Yii::app()->end();
    }

// Vulnerability class: CWE-20
public function save_user() {
		if ( empty( $_POST['user_id'] ) ) {
			return false;
		}

		$user_id = $_POST['user_id'];

		if ( !is_numeric( $user_id ) ) {
			return $user_id;
		}

		if ( !current_user_can( 'edit_user', $user_id ) ) {
			return $user_id;
		}

		return $this->save_posted_object_location( $user_id );
	}

// Vulnerability class: CWE-20
private static function retrieveClosurePattern($pure, $closureName)
    {
        $pattern = '/';
        if (!$pure) {
            $pattern .= preg_quote(self::$registeredDelimiters[0]) . "\s*";
        }
        $pattern .= "$closureName\(([a-z0-9,\.\s]+)\)";
        if (!$pure) {
            $pattern .= "\s*" . preg_quote(self::$registeredDelimiters[1]);
        }
        return $pattern . "/i";
    }

// Vulnerability class: CWE-74
$query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
                /** @var Builder $permissionQuery */
                $permissionQuery->select(['role_id'])->from('joint_permissions')
                    ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
                    ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
                    ->where('action', '=', $action)
                    ->whereIn('role_id', $this->getCurrentUserRoles())
                    ->where(function (QueryBuilder $query) {
                        $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                    });
            });

// Vulnerability class: CWE-863
$tokens  = preg_split( '/ - */', $title );
			$newKey = '';
			foreach ( $tokens as $token ) {
				$initial = substr( $token, 0, 1 );
				if ( $initial >= '1' && $initial <= '7' ) {
					$newKey .= $initial;
					$suit = substr( $token, 1 );
					if ( $suit == '♣' ) {
						$newKey .= '1';
					} elseif ( $suit == '♦' ) {
						$newKey .= '2';
					} elseif ( $suit == '♥' ) {
						$newKey .= '3';
					} elseif ( $suit == '♠' ) {
						$newKey .= '4';
					} elseif ( strtolower( $suit ) == 'sa' || strtolower( $suit ) == 'nt' ) {
						$newKey .= '5 ';
					} else {
						$newKey .= $suit;
					}
				} elseif ( strtolower( $initial ) == 'p' ) {
					$newKey .= '0 ';
				} elseif ( strtolower( $initial ) == 'x' ) {
					$newKey .= '8 ';
				} else {
					$newKey .= $token;
				}
			}
			$sortKeys[$key] = $newKey;
		}
		asort( $sortKeys );
		foreach ( $sortKeys as $oldKey => $newKey ) {
			$sortedArticles[] = $articles[$oldKey];
		}
		return $sortedArticles;
	}

// Vulnerability class: CWE-400
public function testRemoveAuthorizationHeaderOnRedirect()
    {
        $mock = new MockHandler([
            new Response(302, ['Location' => 'http://test.com']),
            static function (RequestInterface $request) {
                self::assertFalse($request->hasHeader('Authorization'));
                return new Response(200);
            }
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);
    }

// Vulnerability class: CWE-200
private function _titlegt( $option ) {
		$where = '(';
		if ( substr( $option, 0, 2 ) == '=_' ) {
			if ( $this->parameters->getParameter( 'openreferences' ) ) {
				$where .= 'pl_title >= ' . $this->DB->addQuotes( substr( $sTitleGE, 2 ) );
			} else {
				$where .= $this->tableNames['page'] . '.page_title >= ' . $this->DB->addQuotes( substr( $option, 2 ) );
			}
		} else {
			if ( $this->parameters->getParameter( 'openreferences' ) ) {
				$where .= 'pl_title > ' . $this->DB->addQuotes( $option );
			} else {
				$where .= $this->tableNames['page'] . '.page_title > ' . $this->DB->addQuotes( $option );
			}
		}
		$where .= ')';
		$this->addWhere( $where );
	}

// Vulnerability class: CWE-400
public function enqueue_scripts() {
		global $geo_mashup_options, $pagenow, $post;

		// The location editor works only on posts
		if ( empty( $post ) )
			return null;

		$load_location_editor = (
				is_admin() and
				preg_match( '/(post|page)(-new|).php/', $pagenow ) and
				in_array( $post->post_type, $geo_mashup_options->get( 'overall', 'located_post_types' ) )
				);
		$load_location_editor = apply_filters( 'geo_mashup_load_location_editor', $load_location_editor );

		// If we're on a post editing page, queue up the form interface elements
		if ( $load_location_editor ) {

			$this->enqueue_form_client_items();

		} 
	}

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

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

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

// Vulnerability class: CWE-74
public function execute(&$params){
        $options = &$this->config['options'];

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

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

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

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

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

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

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

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

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

    }

// Vulnerability class: CWE-20
function fread($handle, $length)
    {
        if (\yiiunit\framework\base\SecurityTest::$fread !== null) {
            return \yiiunit\framework\base\SecurityTest::$fread;
        }
        if (\yiiunit\framework\base\SecurityTest::$fopen !== null) {
            return $length < 8 ? \str_repeat('s', $length) : 'test1234';
        }

        return \fread($handle, $length);
    }

// Vulnerability class: CWE-330
public function getClone($modelId = null)
    {
        $this->authorize('view', AssetModel::class);
        // Check if the model exists
        if (is_null($model_to_clone = AssetModel::find($modelId))) {
            return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));
        }

        $model = clone $model_to_clone;
        $model->id = null;

        // Show the page
        return view('models/edit')
            ->with('depreciation_list', Helper::depreciationList())
            ->with('item', $model)
            ->with('clone_model', $model_to_clone);
    }

// Vulnerability class: CWE-862
public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));

        if (! empty($action) && $this->actionModel->remove($action['id'])) {
            $this->flash->success(t('Action removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this action.'));
        }

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

// Vulnerability class: CWE-200
private static function init() {
		\DPL\Config::init();

		if ( !isset( self::$createdLinks ) ) {
			self::$createdLinks = [
				'resetLinks' => false,
				'resetTemplates' => false,
				'resetCategories' => false,
				'resetImages' => false,
				'resetdone' => false,
				'elimdone' => false
			];
		}
	}

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

// Vulnerability class: CWE-20
public function actionGetItems(){
        $model = X2Model::model ($this->modelClass);
        if (isset ($model)) {
            $tableName = $model->tableName ();
            $sql = 
                'SELECT id, subject as value
                 FROM '.$tableName.' WHERE subject LIKE :qterm ORDER BY subject ASC';
            $command = Yii::app()->db->createCommand($sql);
            $qterm = $_GET['term'].'%';
            $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
            $result = $command->queryAll();
            echo CJSON::encode($result);
        }
        Yii::app()->end();
    }

// Vulnerability class: CWE-20
private function _lastmodifiedby( $option ) {
	   $user = new \User;

	   $this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = (SELECT revactor_actor FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id ORDER BY ' . $this->tableNames['revision_actor_temp'] . '.revactor_timestamp DESC LIMIT 1)' );
	}

// Vulnerability class: CWE-400
function GoodAuthDigestTestController($serverPort) {
  $args = array('Authorization' => 'Digest username="admin", ' .
    'realm="Restricted area", nonce="564a12611dae8", ' .
    'uri="/test_auth_digest.php", cnonce="MjIyMTg1", nc=00000001, ' .
    'qop="auth", response="e544aaed06917adea3e5c74dd49f0e32", ' .
    'opaque="cdce8a5c95a1427d74df7acbf41c9ce0"');
  var_dump(request(php_uname('n'), $serverPort, "test_auth_digest.php",
                  [], [], $args));
}

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

// Vulnerability class: CWE-74
function login($redirectCallback = null)
    {
        $aConf = $GLOBALS['_MAX']['CONF'];

        if (!is_callable($redirectCallback)) {
            // Set the default callback
            $redirectCallback = array('OA_Auth', 'checkRedirect');
        }

        if (call_user_func($redirectCallback)) {
            header('location: http://'.$aConf['webpath']['admin']);
            exit();
        }

        if (defined('OA_SKIP_LOGIN')) {
            return OA_Auth::getFakeSessionData();
        }

        if (OA_Auth::suppliedCredentials()) {
            $doUser = OA_Auth::authenticateUser();

            if (!$doUser) {
                sleep(3);
                OA_Auth::restart($GLOBALS['strUsernameOrPasswordWrong']);
            }

            return OA_Auth::getSessionData($doUser);
        }

        OA_Auth::restart();
    }

// Vulnerability class: CWE-287
function delete() {
        global $db;

        if (empty($this->params['id'])) return false;
        $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);
        $product = new $product_type($this->params['id'], true, false);
        //eDebug($product_type);  
        //eDebug($product, true);
        //if (!empty($product->product_type_id)) {
        //$db->delete($product_type, 'id='.$product->product_id);
        //}

        $db->delete('option', 'product_id=' . $product->id . " AND optiongroup_id IN (SELECT id from " . $db->prefix . "optiongroup WHERE product_id=" . $product->id . ")");
        $db->delete('optiongroup', 'product_id=' . $product->id);
        //die();
        $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type="' . $product_type . '"');

        if ($product->product_type == "product") {
            if ($product->hasChildren()) {
                $this->deleteChildren();
            }
        }

        $product->delete();

        flash('message', gt('Product deleted successfully.'));
        expHistory::back();
    }

// Vulnerability class: CWE-74
public function testCheckHTTP()
    {
        if (! function_exists('curl_init')) {
            $this->markTestSkipped('Missing curl extension!');
        }
        $this->assertTrue(
            $this->object->checkHTTP("http://www.phpmyadmin.net/test/data")
        );
        $this->assertContains(
            "TEST DATA",
            $this->object->checkHTTP("http://www.phpmyadmin.net/test/data", true)
        );
        $this->assertFalse(
            $this->object->checkHTTP("http://www.phpmyadmin.net/test/nothing")
        );
    }

// Vulnerability class: CWE-20
public function testAuthHeader()
    {
        $restoreInstance = PMA\libraries\Response::getInstance();

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

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

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

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

// Vulnerability class: CWE-200
public function create_directory() {
        if (!AuthUser::hasPermission('file_manager_mkdir')) {
            Flash::set('error', __('You do not have sufficient permissions to create a directory.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }
        
        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_directory')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $data = $_POST['directory'];

        $path = str_replace('..', '', $data['path']);
        $dirname = str_replace('..', '', $data['name']);
        $dir = FILES_DIR . "/{$path}/{$dirname}";

        if (mkdir($dir)) {
            $mode = Plugin::getSetting('dirmode', 'file_manager');
            chmod($dir, octdec($mode));
        } else {
            Flash::set('error', __('Directory :name has not been created!', array(':name' => $dirname)));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }

// Vulnerability class: CWE-20
private function _namespace( $option ) {
		$option === 0 ?? $option = '0';
		if ( is_array( $option ) && count( $option ) ) {
			if ( $this->parameters->getParameter( 'openreferences' ) ) {
				$this->addWhere(
					[
						"{$this->tableNames['pagelinks']}.pl_namespace"	=> $option
					]
				);
			} else {
				$this->addWhere(
					[
						"{$this->tableNames['page']}.page_namespace"	=> $option
					]
				);
			}
		}
	}

// Vulnerability class: CWE-400
public function testIsExpiredReturnsTrueWhenModificationTimesWarrant()
    {
        $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);
        $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(true);
        $files->shouldReceive('lastModified')->once()->with('foo')->andReturn(100);
        $files->shouldReceive('lastModified')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(0);
        $this->assertTrue($compiler->isExpired('foo'));
    }

// Vulnerability class: CWE-327
public static function generate_location_json( ) {
		/* TODO: Try to track modification?
		if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
			$http_time = strtotime( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
			$mod_time = strtotime( $post->post_modified_gmt . ' GMT' );
			if ($mod_time <= $http_time) {
				return status_header(304); // Not modified
			}
		}

		status_header(200);
		header( 'Last-Modified: ' . mysql2date( 'D, d M Y H:i:s', $post->post_modified_gmt, false ) . ' GMT' );
		header( 'Content-type: text/xml; charset='.get_settings('blog_charset'), true);
		header( 'Cache-control: max-age=300, must-revalidate', true);
		header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 300 ) . " GMT" );
		header( 'Pragma:' );
		 */
		status_header(200);
		header('Content-type: application/json; charset='.get_option('blog_charset'), true);
		header('Cache-Control: no-cache;', true);
		header('Expires: -1;', true);

		$json = GeoMashup::get_locations_json($_REQUEST);
		if ( isset( $_REQUEST['callback'] ) )
			$json = $_REQUEST['callback'] . '(' . $json . ')';
		echo $json;
	}

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

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

// Vulnerability class: CWE-20
function edit_order_item() {
        $oi = new orderitem($this->params['id'], true, true);
        if (empty($oi->id)) {
            flash('error', gt('Order item doesn\'t exist.'));
            expHistory::back();
        }
        $oi->user_input_fields = expUnserialize($oi->user_input_fields);
        $params['options'] = $oi->opts;
        $params['user_input_fields'] = $oi->user_input_fields;
        $oi->product           = new product($oi->product->id, true, true);
        if ($oi->product->parent_id != 0) {
            $parProd = new product($oi->product->parent_id);
            //$oi->product->optiongroup = $parProd->optiongroup;   
            $oi->product = $parProd;
        }
        //FIXME we don't use selectedOpts?
//        $oi->selectedOpts = array();
//        if (!empty($oi->opts)) {
//            foreach ($oi->opts as $opt) {
//                $option = new option($opt[0]);
//                $og     = new optiongroup($option->optiongroup_id);
//                if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))
//                    $oi->selectedOpts[$og->id] = array($option->id);
//                else
//                    array_push($oi->selectedOpts[$og->id], $option->id);
//            }
//        }
        //eDebug($oi->selectedOpts);

        assign_to_template(array(
            'oi' => $oi,
            'params' => $params
        ));
    }

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

// Vulnerability class: CWE-200
public static function sortByPriority( $parameters ) {
		if ( !is_array( $parameters ) ) {
			throw new \MWException( __METHOD__ . ': A non-array was passed.' );
		}
		//'category' to get category headings first for ordermethod.
		//'include'/'includepage' to make sure section labels are ready for 'table'.
		$priority = [
			'distinct'			=> 1,
			'openreferences'	=> 2,
			'ignorecase'		=> 3,
			'category'			=> 4,
			'title'				=> 5,
			'goal'				=> 6,
			'ordercollation'	=> 7,
			'ordermethod'		=> 8,
			'includepage'		=> 9,
			'include'			=> 10
		];

		$_first = [];
		foreach ( $priority as $parameter => $order ) {
			if ( isset( $parameters[$parameter] ) ) {
				$_first[$parameter] = $parameters[$parameter];
				unset( $parameters[$parameter] );
			}
		}

		$parameters = $_first + $parameters;

		return $parameters;
	}

// Vulnerability class: CWE-400
public function testPopBeforeSmtpGood()
    {
        //Start a fake POP server
        $pid = shell_exec('nohup ./runfakepopserver.sh >/dev/null 2>/dev/null & printf "%u" $!');
        $this->pids[] = $pid;

        sleep(2);
        //Test a known-good login
        $this->assertTrue(
            POP3::popBeforeSmtp('localhost', 1100, 10, 'user', 'test', $this->Mail->SMTPDebug),
            'POP before SMTP failed'
        );
        //Kill the fake server
        shell_exec('kill -TERM '.escapeshellarg($pid));
        sleep(2);
    }

// Vulnerability class: CWE-20