mcanoglu/cwe-class-group huggingface dataset:
public function approve_toggle() {
        global $history;
        
        if (empty($this->params['id'])) return;
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? 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'];
        
        
        $simplenote = new expSimpleNote($this->params['id']);
        $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;
        $simplenote->save();
        
        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }

// Vulnerability class: CWE-74
private function _notuses( $option ) {
		if ( count( $option ) > 0 ) {
			$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['templatelinks'] . '.tl_from FROM ' . $this->tableNames['templatelinks'] . ' WHERE (';
			$ors = [];
			foreach ( $option as $linkGroup ) {
				foreach ( $linkGroup as $link ) {
					$_or = '(' . $this->tableNames['templatelinks'] . '.tl_namespace=' . intval( $link->getNamespace() );
					if ( $this->parameters->getParameter( 'ignorecase' ) ) {
						$_or .= ' AND LOWER(CAST(' . $this->tableNames['templatelinks'] . '.tl_title AS char))=LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';
					} else {
						$_or .= ' AND ' . $this->tableNames['templatelinks'] . '.tl_title=' . $this->DB->addQuotes( $link->getDbKey() ) . ')';
					}
					$ors[] = $_or;
				}
			}
			$where .= implode( ' OR ', $ors ) . '))';
		}
		$this->addWhere( $where );
	}

// Vulnerability class: CWE-400
public function addTags($tags) {
        $result = false;
        $addedTags = array();

        foreach ((array) $tags as $tagName) {
            if (empty($tagName))
                continue;
            if (!in_array($tagName, $this->getTags())) { // check for duplicate tag
                $tag = new Tags;
                $tag->tag = '#' . ltrim($tagName, '#');
                $tag->itemId = $this->getOwner()->id;
                $tag->type = get_class($this->getOwner());
                $tag->taggedBy = Yii::app()->getSuName();
                $tag->timestamp = time();
                $tag->itemName = $this->getOwner()->name;

                if ($tag->save()) {
                    $this->_tags[] = $tag->tag; // update tag cache
                    $addedTags[] = $tagName;
                    $result = true;
                } else {
                    throw new CHttpException(422, 'Failed saving tag due to errors: ' . json_encode($tag->errors));
                }
            }
        }
        if ($this->flowTriggersEnabled)
            X2Flow::trigger('RecordTagAddTrigger', array(
                'model' => $this->getOwner(),
                'tags' => $addedTags,
            ));

        return $result;
    }

// Vulnerability class: CWE-20
imagepng( $im_crop, $output );
	}

	$new_avatar = false;

	if ( file_exists( $output ) ) {

		$old_avatar = get_user_meta( $user_id, '_lp_profile_picture', true );

		if ( file_exists( $upload_dir['basedir'] . '/' . $old_avatar ) ) {
			@unlink( $upload_dir['basedir'] . '/' . $old_avatar );
		}

		$new_avatar = preg_replace( '!^/!', '', $upload_dir['subdir'] ) . '/' . $newname;
		update_user_meta( $user_id, '_lp_profile_picture', $new_avatar );
		update_user_meta( $user_id, '_lp_profile_picture_changed', 'yes' );

		$new_avatar = $upload_dir['baseurl'] . '/' . $new_avatar;
	}

	@unlink( $path );

	return $new_avatar;
}

// Vulnerability class: CWE-610
$db->insertObject($obj, 'expeAlerts_subscribers');
        }
        
        $count = count($this->params['ealerts']);
        
        if ($count > 0) {
            flash('message', gt("Your subscriptions have been updated.  You are now subscriber to")." ".$count.' '.gt('E-Alerts.'));
        } else {
            flash('error', gt("You have been unsubscribed from all E-Alerts."));
        }
        
        expHistory::back();
    }

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

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

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

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

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

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

		return true;
	}

// Vulnerability class: CWE-20
public static function validateServer($path, $values)
    {
        $result = array(
            'Server' => '',
            'Servers/1/user' => '',
            'Servers/1/SignonSession' => '',
            'Servers/1/SignonURL' => ''
        );
        $error = false;
        if ($values['Servers/1/auth_type'] == 'config'
            && empty($values['Servers/1/user'])
        ) {
            $result['Servers/1/user'] = __(
                'Empty username while using [kbd]config[/kbd] authentication method!'
            );
            $error = true;
        }
        if ($values['Servers/1/auth_type'] == 'signon'
            && empty($values['Servers/1/SignonSession'])
        ) {
            $result['Servers/1/SignonSession'] = __(
                'Empty signon session name '
                . 'while using [kbd]signon[/kbd] authentication method!'
            );
            $error = true;
        }
        if ($values['Servers/1/auth_type'] == 'signon'
            && empty($values['Servers/1/SignonURL'])
        ) {
            $result['Servers/1/SignonURL'] = __(
                'Empty signon URL while using [kbd]signon[/kbd] authentication '
                . 'method!'
            );
            $error = true;
        }

        if (! $error && $values['Servers/1/auth_type'] == 'config') {
            $password = $values['Servers/1/nopassword'] ? null
                : $values['Servers/1/password'];
            $test = static::testDBConnection(
                $values['Servers/1/connect_type'],
                $values['Servers/1/host'],
                $values['Servers/1/port'],
                $values['Servers/1/socket'],
                $values['Servers/1/user'],
                $password,
                'Server'
            );
            if ($test !== true) {
                $result = array_merge($result, $test);
            }
        }
        return $result;
    }

// Vulnerability class: CWE-200
function token($str) {
		$fw=$this->fw;
		$str=trim(preg_replace('/\{\{(.+?)\}\}/s',trim('\1'),
			$fw->compile($str)));
		if (preg_match('/^(.+)(?<!\|)\|((?:\h*\w+(?:\h*[,;]?))+)$/s',
			$str,$parts)) {
			$str=trim($parts[1]);
			foreach ($fw->split(trim($parts[2],"\xC2\xA0")) as $func)
				$str=((empty($this->filter[$cmd=$func]) &&
					function_exists($cmd)) ||
					is_string($cmd=$this->filter($func)))?
					$cmd.'('.$str.')':
					'Base::instance()->'.
						'call($this->filter(\''.$func.'\'),['.$str.'])';
		}
		return $str;
	}

// Vulnerability class: CWE-20
public function testLogoutDelete()
    {
        $GLOBALS['cfg']['Server']['auth_swekey_config'] = '';
        $GLOBALS['cfg']['CaptchaLoginPrivateKey'] = '';
        $GLOBALS['cfg']['CaptchaLoginPublicKey'] = '';
        $_REQUEST['old_usr'] = 'pmaolduser';
        $GLOBALS['cfg']['LoginCookieDeleteAll'] = true;
        $GLOBALS['cfg']['Servers'] = array(1);

        $_COOKIE['pmaPass-0'] = 'test';

        $this->object->authCheck();

        $this->assertFalse(
            isset($_COOKIE['pmaPass-0'])
        );
    }

// Vulnerability class: CWE-200
protected function parseImageUrlWithPath( $article ) {
		$imageUrl = '';
		if ( $article instanceof \DPL\Article ) {
			if ( $article->mNamespace == NS_FILE ) {
				// calculate URL for existing images
				// $img = Image::newFromName($article->mTitle->getText());
				$img = wfFindFile( \Title::makeTitle( NS_FILE, $article->mTitle->getText() ) );
				if ( $img && $img->exists() ) {
					$imageUrl = $img->getURL();
				} else {
					$fileTitle = \Title::makeTitleSafe( NS_FILE, $article->mTitle->getDBKey() );
					$imageUrl = \RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();
				}
			}
		} else {
			$title = \Title::newfromText( 'File:' . $article );
			if ( $title !== null ) {
				$fileTitle   = \Title::makeTitleSafe( 6, $title->getDBKey() );
				$imageUrl = \RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();
			}
		}

		//@TODO: Check this preg_replace.  Probably only works for stock file repositories.  --Alexia
		$imageUrl = preg_replace( '~^.*images/(.*)~', '\1', $imageUrl );

		return $imageUrl;
	}

// Vulnerability class: CWE-400
public function actionGetItems(){
        $sql = 'SELECT id, name as value, subject FROM x2_bug_reports 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
public function getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}

// Vulnerability class: CWE-20
private function _allrevisionssince( $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
public static function checkPermissions($permission,$location) {
        global $exponent_permissions_r, $router;

        // only applies to the 'manage' method
        if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {
            if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {
                foreach ($page as $pageperm) {
                    if (!empty($pageperm['manage'])) return true;
                }
            }
        }
        return false;
    }

// Vulnerability class: CWE-74
public function Quit($close_on_error = true) {
    $this->error = null; // so there is no confusion

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

    // send the quit command to the server
    fputs($this->smtp_conn,"quit" . $this->CRLF);

    // get any good-bye messages
    $byemsg = $this->get_lines();

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

    $rval = true;
    $e = null;

    $code = substr($byemsg,0,3);
    if($code != 221) {
      // use e as a tmp var cause Close will overwrite $this->error
      $e = array("error" => "SMTP server rejected quit command",
                 "smtp_code" => $code,
                 "smtp_rply" => substr($byemsg,4));
      $rval = false;
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />');
      }
    }

    if(empty($e) || $close_on_error) {
      $this->Close();
    }

    return $rval;
  }

// Vulnerability class: CWE-20
public function testAuthCheckToken()
    {
        $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';
        $GLOBALS['cfg']['Server']['SignonSession'] = 'session123';
        $GLOBALS['cfg']['Server']['host'] = 'localhost';
        $GLOBALS['cfg']['Server']['port'] = '80';
        $GLOBALS['cfg']['Server']['user'] = 'user';
        $GLOBALS['cfg']['Server']['SignonScript'] = '';
        $_COOKIE['session123'] = true;
        $_REQUEST['old_usr'] = 'oldUser';
        $_SESSION['PMA_single_signon_user'] = 'user123';
        $_SESSION['PMA_single_signon_password'] = 'pass123';
        $_SESSION['PMA_single_signon_host'] = 'local';
        $_SESSION['PMA_single_signon_port'] = '12';
        $_SESSION['PMA_single_signon_cfgupdate'] = array('foo' => 'bar');
        $_SESSION['PMA_single_signon_token'] = 'pmaToken';
        $sessionName = session_name();
        $sessionID = session_id();

        $this->assertFalse(
            $this->object->authCheck()
        );

        $this->assertEquals(
            array(
                'SignonURL' => 'http://phpmyadmin.net/SignonURL',
                'SignonScript' => '',
                'SignonSession' => 'session123',
                'host' => 'local',
                'port' => '12',
                'user' => 'user',
                'foo' => 'bar'
            ),
            $GLOBALS['cfg']['Server']
        );

        $this->assertEquals(
            'pmaToken',
            $_SESSION[' PMA_token ']
        );

        $this->assertEquals(
            $sessionName,
            session_name()
        );

        $this->assertEquals(
            $sessionID,
            session_id()
        );

        $this->assertFalse(
            isset($_SESSION['LAST_SIGNON_URL'])
        );
    }

// Vulnerability class: CWE-200
public function testRenderWithTrustedHeaderDisabled()
    {
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
        $this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());
    }

// Vulnerability class: CWE-20
public function test_valid_comment_0_content() {
		$result = $this->myxmlrpcserver->wp_newComment(
			array(
				1,
				'administrator',
				'administrator',
				self::$post->ID,
				array(
					'content' => '0',
				),
			)
		);

		$this->assertNotIXRError( $result );
	}

// Vulnerability class: CWE-862
function checkPassword($username, $password)
    {
        $doUser = OA_Dal::factoryDO('users');
        $doUser->username = strtolower($username);
        $doUser->password = md5($password);
        $doUser->find();

        if ($doUser->fetch()) {
            return $doUser;
        } else {
            return false;
        }
    }

// Vulnerability class: CWE-287
$sloc = expCore::makeLocation('navigation', null, $section->id);
            // remove any manage permissions for this page and it's children
            // $db->delete('userpermission', "module='navigationController' AND internal=".$section->id);
            // $db->delete('grouppermission', "module='navigationController' AND internal=".$section->id);
            foreach ($allusers as $uid) {
                $u = user::getUserById($uid);
                expPermissions::grant($u, 'manage', $sloc);
            }
            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }
        }
    }

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

        $paths = func_get_args();

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

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

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

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

// Vulnerability class: CWE-20
public function __construct( \DPL\Parameters $parameters, \Parser $parser ) {
		$this->setHeadListAttributes( $parameters->getParameter( 'hlistattr' ) );
		$this->setHeadItemAttributes( $parameters->getParameter( 'hitemattr' ) );
		$this->setListAttributes( $parameters->getParameter( 'listattr' ) );
		$this->setItemAttributes( $parameters->getParameter( 'itemattr' ) );
		$this->setDominantSectionCount( $parameters->getParameter( 'dominantsection' ) );
		$this->setTemplateSuffix( $parameters->getParameter( 'defaulttemplatesuffix' ) );
		$this->setTrimIncluded( $parameters->getParameter( 'includetrim' ) );
		$this->setTableSortColumn( $parameters->getParameter( 'tablesortcol' ) );
		$this->setTableSortMethod($parameters->getParameter('tablesortmethod'));
		$this->setTitleMaxLength( $parameters->getParameter( 'titlemaxlen' ) );
		$this->setEscapeLinks( $parameters->getParameter( 'escapelinks' ) );
		$this->setSectionSeparators( $parameters->getParameter( 'secseparators' ) );
		$this->setMultiSectionSeparators( $parameters->getParameter( 'multisecseparators' ) );
		$this->setIncludePageText( $parameters->getParameter( 'incpage' ) );
		$this->setIncludePageMaxLength( $parameters->getParameter( 'includemaxlen' ) );
		$this->setPageTextMatch( (array)$parameters->getParameter( 'seclabels' ) );
		$this->setPageTextMatchRegex( (array)$parameters->getParameter( 'seclabelsmatch' ) );
		$this->setPageTextMatchNotRegex( (array)$parameters->getParameter( 'seclabelsnotmatch' ) );
		$this->setIncludePageParsed( $parameters->getParameter( 'incparsed' ) );
		$this->parameters = $parameters;
		$this->parser = clone $parser;
	}

// Vulnerability class: CWE-400
public function getLayout(){
        $layout = $this->getAttribute('layout');

        $initLayout = $this->initLayout();

        if(!$layout){ // layout hasn't been initialized?
            $layout = $initLayout;
            $this->layout = json_encode($layout);
            $this->update(array('layout'));
        }else{
            $layout = json_decode($layout, true); // json to associative array
            $this->addRemoveLayoutElements('center', $layout, $initLayout);
            $this->addRemoveLayoutElements('left', $layout, $initLayout);
            $this->addRemoveLayoutElements('right', $layout, $initLayout);
        }

        return $layout;
    }

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

// Vulnerability class: CWE-400
protected function checkMaintenanceMode()
    {
        if (Yii::$app->settings->get('maintenanceMode')) {
            if (!Yii::$app->user->isGuest) {
                Yii::$app->user->logout();
                Yii::$app->getView()->warn(Yii::t('error', 'Maintenance mode activated: You have been automatically logged out and will no longer have access the platform until the maintenance has been completed.'));
            }
            return Yii::$app->getResponse()->redirect(['/user/auth/login']);
        }
    }

// Vulnerability class: CWE-863
public function actionPublishPost() {
        $post = new Events;
        // $user = $this->loadModel($id);
        if (isset($_POST['text']) && $_POST['text'] != "") {
            $post->text = $_POST['text'];
            $post->visibility = $_POST['visibility'];
            if (isset($_POST['associationId']))
                $post->associationId = $_POST['associationId'];
            //$soc->attributes = $_POST['Social'];
            //die(var_dump($_POST['Social']));
            $post->user = Yii::app()->user->getName();
            $post->type = 'feed';
            $post->subtype = $_POST['subtype'];
            $post->lastUpdated = time();
            $post->timestamp = time();
            if ($post->save()) {
                if (!empty($post->associationId) && $post->associationId != Yii::app()->user->getId()) {

                    $notif = new Notification;

                    $notif->type = 'social_post';
                    $notif->createdBy = $post->user;
                    $notif->modelType = 'Profile';
                    $notif->modelId = $post->associationId;

                    $notif->user = Yii::app()->db->createCommand()
                            ->select('username')
                            ->from('x2_users')
                            ->where('id=:id', array(':id' => $post->associationId))
                            ->queryScalar();

                    // $prof = X2Model::model('Profile')->findByAttributes(array('username'=>$post->user));
                    // $notif->text = "$prof->fullName posted on your profile.";
                    // $notif->record = "profile:$prof->id";
                    // $notif->viewed = 0;
                    $notif->createDate = time();
                    // $subject=X2Model::model('Profile')->findByPk($id);
                    // $notif->user = $subject->username;
                    $notif->save();
                }
            }
        }
    }

// Vulnerability class: CWE-20
public function search() {
//        global $db, $user;
        global $db;

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

// Vulnerability class: CWE-74
public function confirm() {
        global $db;
        
        // make sure we have what we need.
        if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));
        
        // verify the id/key pair    
        $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash="'.$this->params['key'].'"');
        if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));
        
        // activate this users pending subscriptions
        $sub = new stdClass();
        $sub->enabled = 1;
        $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);
        
        // find the users active subscriptions
        $ealerts = expeAlerts::getBySubscriber($id);
        assign_to_template(array(
            'ealerts'=>$ealerts
        ));
    }

// Vulnerability class: CWE-74
$modelName = ucfirst ($module->name);
                    if (class_exists ($modelName)) {
                        // prefix widget class name with custom module model name and a delimiter
                        $cache[$widgetType][$modelName.'::TemplatesGridViewProfileWidget'] =
                            Yii::t(
                                'app', '{modelName} Summary', array ('{modelName}' => $modelName));
                    }
                }
            }
        }
        return $cache[$widgetType];
    }

// Vulnerability class: CWE-20
public function Set($_var = '', $_value = '', $_vartrusted = false, $_valuetrusted = false) {

		if ($_var != ''
			&& $_value != ''
		) {
			if (!$_vartrusted) {
				$_var = strip_tags($_var);
			}

			if (!$_valuetrusted) {
				$_value = strip_tags($_value, '<br />');
			}

			if (strtolower($_var) == 'message'
				|| strtolower($_var) == 'subject'
			) {
				$_value = $this->convertLatin1ToHtml($_value);
			}

			$this->t_data[$_var] = $_value;
		}
	}

// Vulnerability class: CWE-732
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;
    }

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

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

// Vulnerability class: CWE-20
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;
}

// Vulnerability class: CWE-20
public function approve_submit() {
        global $history;
        
        if (empty($this->params['id'])) {
            flash('error', gt('No ID supplied for comment to approve'));
            $lastUrl = expHistory::getLast('editable');
        }
        
        /* 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'];
        
        $simplenote = new expSimpleNote($this->params['id']);
        //FIXME here is where we might sanitize the note before approving it
        $simplenote->body = $this->params['body'];
        $simplenote->approved = $this->params['approved'];
        $simplenote->save();
        
        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }

// Vulnerability class: CWE-74
function manage_upcharge() {
		$this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
		$this->config = $config->config;

		$gc = new geoCountry();             
        $countries = $gc->find('all');
        
        $gr = new geoRegion();             
        $regions = $gr->find('all',null,'rank asc,name asc');
        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions,
            'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
        ));
	 }

// Vulnerability class: CWE-74
public function update()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->swimlaneValidator->validateModification($values);

        if ($valid) {
            if ($this->swimlaneModel->update($values['id'], $values)) {
                $this->flash->success(t('Swimlane updated successfully.'));
                return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
            } else {
                $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));
            }
        }

        return $this->edit($values, $errors);
    }

// Vulnerability class: CWE-200
public function replace_save_pre_shortcode( $shortcode_match ) {
		$content = $shortcode_match[0];
		$tag_index = array_search( 'geo_mashup_save_location',  $shortcode_match ); 
		if ( $tag_index !== false ) {
			// There is an inline location - save the attributes
			$this->inline_location = shortcode_parse_atts( stripslashes( $shortcode_match[$tag_index+1] ) );

			// If lat and lng are missing, try to geocode based on address
			$success = false;
			if ( ( empty( $this->inline_location['lat'] ) or empty( $this->inline_location['lng'] ) ) and !empty( $this->inline_location['address'] ) ) {
				$query = $this->inline_location['address'];
				$this->inline_location = GeoMashupDB::blank_object_location( ARRAY_A );
				$success = GeoMashupDB::geocode( $query, $this->inline_location );
				if ( !$success ) {
					// Delay and try again
					sleep( 1 );
					$success = GeoMashupDB::geocode( $query, $this->inline_location );
				}
			} else if ( is_numeric ( $this->inline_location['lat'] ) and is_numeric( $this->inline_location['lng'] ) ) {
				// lat and lng were supplied
				$success = true;
			}

			if ( $success ) {
				// Remove the tag
				$content = '';
			} else {
				$message = ( is_wp_error( GeoMashupDB::$geocode_error ) ? GeoMashupDB::$geocode_error->get_error_message() : __( 'Address not found - try making it less detailed', 'GeoMashup' ) );
				$content = str_replace( ']', ' geocoding_error="' . $message . '"]', $content );
				$this->inline_location = null;
			}
		} 
		return $content;
	}

// Vulnerability class: CWE-20
private function generateTempFileData()
    {
        return [
            'name' => md5(mt_rand()),
            'tmp_name' => tempnam(sys_get_temp_dir(), ''),
            'type' => 'image/jpeg',
            'size' => mt_rand(1000, 10000),
            'error' => '0',
        ];
    }

// Vulnerability class: CWE-330
public static function login() {
		user::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));
		if (!isset($_SESSION[SYS_SESSION_KEY]['user'])) {  // didn't successfully log in
			flash('error', gt('Invalid Username / Password'));
			if (expSession::is_set('redirecturl_error')) {
				$url = expSession::get('redirecturl_error');
				expSession::un_set('redirecturl_error');
				header("Location: ".$url);
			} else {
				expHistory::back();
			}
		} else {  // we're logged in
			global $user;

            if (expSession::get('customer-login')) expSession::un_set('customer-login');
			if (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));
            if ($user->isAdmin()) {
                expHistory::back();
            } else {
                foreach ($user->groups as $g) {
                    if (!empty($g->redirect)) {
                        $url = URL_FULL.$g->redirect;
                        break;
                    }
                }
                if (isset($url)) {
                    header("Location: ".$url);
                } else {
                    expHistory::back();
                }
            }
		}
	}

// Vulnerability class: CWE-74
public function getCookiePathsDataProvider()
    {
        return [
            ['', '/'],
            ['/', '/'],
            ['/foo', '/'],
            ['/foo/bar', '/foo'],
            ['/foo/bar/', '/foo/bar'],
            ['foo', '/'],
            ['foo/bar', '/'],
            ['foo/bar/', '/'],
        ];
    }

// Vulnerability class: CWE-200
public function testOnKernelResponseListenerRemovesItself()
    {
        $session = $this->createMock(SessionInterface::class);
        $session->expects($this->any())->method('getName')->willReturn('SESSIONNAME');
        $tokenStorage = $this->createMock(TokenStorageInterface::class);
        $dispatcher = $this->createMock(EventDispatcherInterface::class);

        $listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher);

        $request = new Request();
        $request->attributes->set('_security_firewall_run', true);
        $request->setSession($session);

        $event = new ResponseEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, new Response());

        $dispatcher->expects($this->once())
            ->method('removeListener')
            ->with(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);

        $listener->onKernelResponse($event);
    }

// Vulnerability class: CWE-287
$evs = $this->event->find('all', "id=" . $edate->event_id . $featuresql);
            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }
            if (count($events) < 500) {  // magic number to not crash loop?
                $events = array_merge($events, $evs);
            } else {
//                $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');
//                $events = array_merge($events, $evs);
                flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));
                break; // keep from breaking system by too much data
            }
        }

// Vulnerability class: CWE-74
public function showall_tags() {
        $images = $this->image->find('all');
        $used_tags = array();
        foreach ($images as $image) {
            foreach($image->expTag as $tag) {
                if (isset($used_tags[$tag->id])) {
                    $used_tags[$tag->id]->count++;
                } else {
                    $exptag = new expTag($tag->id);
                    $used_tags[$tag->id] = $exptag;
                    $used_tags[$tag->id]->count = 1;
                }
                
            }
        }
        
        assign_to_template(array(
            'tags'=>$used_tags
        ));
    }           

// Vulnerability class: CWE-74
function test_anon_comments_require_email() {
		add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );

		$comment_args = array(
			1,
			'',
			'',
			self::$post->ID,
			array(
				'author'       => 'WordPress',
				'author_email' => 'noreply at wordpress.org',
				'content'      => 'Test Anon Comments',
			),
		);

		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$this->assertIXRError( $result );
		$this->assertSame( 403, $result->code );
	}

// Vulnerability class: CWE-862
public function StartTLS() {
    $this->error = null; # to avoid confusion

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

    fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);

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

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

    if($code != 220) {
      $this->error =
         array("error"     => "STARTTLS 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 . '<br />');
      }
      return false;
    }

    // Begin encrypted connection
    if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
      return false;
    }

    return true;
  }

// Vulnerability class: CWE-20
$name = ucfirst($module->name);
            if (in_array($name, $skipModules)) {
                continue;
            }
            if($name != 'Document'){
                $controllerName = $name.'Controller';
                if(file_exists('protected/modules/'.$module->name.'/controllers/'.$controllerName.'.php')){
                    Yii::import("application.modules.$module->name.controllers.$controllerName");
                    $controller = new $controllerName($controllerName);
                    $model = $controller->modelClass;
                    if(class_exists($model)){
                        $moduleList[$model] = Yii::t('app', $module->title);
                    }
                }
            }
        }
        return $moduleList;
    }

// Vulnerability class: CWE-20
public function manage() {
        expHistory::set('viewable', $this->params);
        
        $page = new expPaginator(array(
			'model'=>'order_status',
			'where'=>1,
            'limit'=>10,
			'order'=>'rank',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            //'columns'=>array('Name'=>'title')
        ));

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

// Vulnerability class: CWE-74
private static function dumpParsedRefs( $parser, $label ) {
		// if (!preg_match("/Query Q/",$parser->mTitle->getText())) return '';
		echo '<pre>parser mLinks: ';
		ob_start();
		var_dump( $parser->getOutput()->mLinks );
		$a = ob_get_contents();
		ob_end_clean();
		echo htmlspecialchars( $a, ENT_QUOTES );
		echo '</pre>';
		echo '<pre>parser mTemplates: ';
		ob_start();
		var_dump( $parser->getOutput()->mTemplates );
		$a = ob_get_contents();
		ob_end_clean();
		echo htmlspecialchars( $a, ENT_QUOTES );
		echo '</pre>';
	}

// Vulnerability class: CWE-400
public function actionHideWidget() {
        if (isset($_POST['name'])) {
            $name = $_POST['name'];

            $layout = Yii::app()->params->profile->getLayout();

            // the widget could be in any of the blocks in the page, so check all of them
            foreach ($layout as $b => &$block) {
                if (isset($block[$name])) {
                    if ($b == 'right') {
                        $layout['hiddenRight'][$name] = $block[$name];
                    } else {
                        $layout['hidden'][$name] = $block[$name];
                    }
                    unset($block[$name]);
                    Yii::app()->params->profile->saveLayout($layout);
                    break;
                }
            }

            // make a list of hidden widgets, using <li>, to send back to the browser
            $list = "";
            foreach ($layout['hidden'] as $name => $widget) {
                $list .= "<li><span class=\"x2-widget-menu-item\" id=\"$name\">{$widget['title']}</span></li>";
            }
            foreach ($layout['hiddenRight'] as $name => $widget) {
                $list .= "<li><span class=\"x2-widget-menu-item right\" id=\"$name\">{$widget['title']}</span></li>";
            }

            echo Yii::app()->params->profile->getWidgetMenu();
        }
    }

// Vulnerability class: CWE-20
public function testGetDropdownConnect($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::getDropdownConnect($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
$text = wfMessage( 'intersection_noincludecats', $args )->text();
				}
			}
			if ( empty( $text ) ) {
				$text = wfMessage( 'dpl_log_' . $errorMessageId, $args )->text();
			}
			$this->buffer[] = '<p>Extension:DynamicPageList (DPL), version ' . DPL_VERSION . ': ' . $text . '</p>';
		}
		return false;
	}

// Vulnerability class: CWE-400
$controller = new $ctlname();
		    if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {
//			    $mods[$controller->name()] = $controller->addContentToSearch();
                $mods[$controller->searchName()] = $controller->addContentToSearch();
		    }
	    }
	
	    uksort($mods,'strnatcasecmp');
	    assign_to_template(array(
            'mods'=>$mods
        ));
    }

// Vulnerability class: CWE-74
public function manage_sitemap() {
        global $db, $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(
            'sasections'   => $db->selectObjects('section', 'parent=-1'),
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }

// Vulnerability class: CWE-74
} elseif ( $sSecLabel[0] == '{' ) {
					// Uses LST::includeTemplate() from LabeledSectionTransclusion extension to include templates from the page
					// primary syntax {template}suffix
					$template1 = trim( substr( $sSecLabel, 1, strpos( $sSecLabel, '}' ) - 1 ) );
					$template2 = trim( str_replace( '}', '', substr( $sSecLabel, 1 ) ) );
					// alternate syntax: {template|surrogate}
					if ( $template2 == $template1 && strpos( $template1, '|' ) > 0 ) {
						$template1 = preg_replace( '/\|.*/', '', $template1 );
						$template2 = preg_replace( '/^.+\|/', '', $template2 );
					}
					//Why the hell was defaultTemplateSuffix be passed all over the place for just fucking here?  --Alexia
					$secPieces    = LST::includeTemplate( $this->parser, $this, $s, $article, $template1, $template2, $template2 . $this->getTemplateSuffix(), $mustMatch, $mustNotMatch, $this->includePageParsed, implode( ', ', $article->mCategoryLinks ) );
					$secPiece[$s] = implode( isset( $this->multiSectionSeparators[$s] ) ? $this->replaceTagCount( $this->multiSectionSeparators[$s], $filteredCount ) : '', $secPieces );
					if ( $this->getDominantSectionCount() >= 0 && $s == $this->getDominantSectionCount() && count( $secPieces ) > 1 ) {
						$dominantPieces = $secPieces;
					}
					if ( ( $mustMatch != '' || $mustNotMatch != '' ) && count( $secPieces ) <= 1 && $secPieces[0] == '' ) {
						$matchFailed = true; // NOTHING MATCHED
						break;
					}
				} else {

// Vulnerability class: CWE-400
private function setDefaults() {
		$this->setParameter( 'defaulttemplatesuffix', '.default' );

		$parameters = $this->getParametersForRichness();
		foreach ( $parameters as $parameter ) {
			if ( $this->getData( $parameter )['default'] !== null && !( $this->getData( $parameter )['default'] === false && $this->getData( $parameter )['boolean'] === true ) ) {
				if ( $parameter == 'debug' ) {
					\DynamicPageListHooks::setDebugLevel( $this->getData( $parameter )['default'] );
				}
				$this->setParameter( $parameter, $this->getData( $parameter )['default'] );
			}
		}
	}

// Vulnerability class: CWE-400