mcanoglu/cwe-class-group huggingface dataset:
public function testPopBeforeSmtpBad()
    {
        //Start a fake POP server on a different port
        //so we don't inadvertently connect to the previous instance
        $pid = shell_exec('nohup ./runfakepopserver.sh 1101 >/dev/null 2>/dev/null & printf "%u" $!');
        $this->pids[] = $pid;

        sleep(2);
        //Test a known-bad login
        $this->assertFalse(
            POP3::popBeforeSmtp('localhost', 1101, 10, 'user', 'xxx', $this->Mail->SMTPDebug),
            'POP before SMTP should have failed'
        );
        shell_exec('kill -TERM '.escapeshellarg($pid));
        sleep(2);
    }

// Vulnerability class: CWE-20
function mci_account_get_array_by_id( $p_user_id ) {
	$t_result = array();
	$t_result['id'] = $p_user_id;

	if( user_exists( $p_user_id ) ) {
		$t_result['name'] = user_get_field( $p_user_id, 'username' );
		$t_dummy = user_get_field( $p_user_id, 'realname' );

		if( !empty( $t_dummy ) ) {
			$t_result['real_name'] = $t_dummy;
		}

		$t_dummy = user_get_field( $p_user_id, 'email' );

		if( !empty( $t_dummy ) ) {
			$t_result['email'] = $t_dummy;
		}
	}
	return $t_result;
}

// Vulnerability class: CWE-200
public static function validatePMAStorage($path, $values)
    {
        $result = array(
            'Server_pmadb' => '',
            'Servers/1/controluser' => '',
            'Servers/1/controlpass' => ''
        );
        $error = false;

        if ($values['Servers/1/pmadb'] == '') {
            return $result;
        }

        $result = array();
        if ($values['Servers/1/controluser'] == '') {
            $result['Servers/1/controluser'] = __(
                'Empty phpMyAdmin control user while using phpMyAdmin configuration '
                . 'storage!'
            );
            $error = true;
        }
        if ($values['Servers/1/controlpass'] == '') {
            $result['Servers/1/controlpass'] = __(
                'Empty phpMyAdmin control user password while using phpMyAdmin '
                . 'configuration storage!'
            );
            $error = true;
        }
        if (! $error) {
            $test = static::testDBConnection(
                $values['Servers/1/connect_type'],
                $values['Servers/1/host'], $values['Servers/1/port'],
                $values['Servers/1/socket'], $values['Servers/1/controluser'],
                $values['Servers/1/controlpass'], 'Server_pmadb'
            );
            if ($test !== true) {
                $result = array_merge($result, $test);
            }
        }
        return $result;
    }

// Vulnerability class: CWE-200
public static function validateRegex($path, $values)
    {
        $result = array($path => '');

        if ($values[$path] == '') {
            return $result;
        }

        static::testPHPErrorMsg();

        $matches = array();
        // in libraries/ListDatabase.php _checkHideDatabase(),
        // a '/' is used as the delimiter for hide_db
        preg_match('/' . $values[$path] . '/', '', $matches);

        static::testPHPErrorMsg(false);

        if (isset($php_errormsg)) {
            $error = preg_replace('/^preg_match\(\): /', '', $php_errormsg);
            return array($path => $error);
        }

        return $result;
    }

// Vulnerability class: CWE-200
function getResourceGroups($type="") {
	$return = array();
	$query = "SELECT g.id AS id, "
	       .        "g.name AS name, "
	       .        "t.name AS type, "
	       .        "g.ownerusergroupid AS ownerid, "
	       .        "CONCAT(u.name, '@', a.name) AS owner "
	       . "FROM resourcegroup g, "
	       .      "resourcetype t, "
	       .      "usergroup u, "
	       .      "affiliation a "
	       . "WHERE g.resourcetypeid = t.id AND "
	       .       "g.ownerusergroupid = u.id AND "
	       .       "u.affiliationid = a.id ";

	if(! empty($type))
		$query .= "AND t.name = '$type' ";

	$query .= "ORDER BY t.name, g.name";
	$qh = doQuery($query, 281);
	while($row = mysql_fetch_assoc($qh)) {
		if(empty($type))
			$return[$row["id"]]["name"] = $row["type"] . "/" . $row["name"];
		else
			$return[$row["id"]]["name"] = $row["name"];
		$return[$row["id"]]["ownerid"] = $row["ownerid"];
		$return[$row["id"]]["owner"] = $row["owner"];
	}
	return $return;
}

// Vulnerability class: CWE-20
function XMLRPCblockAllocation($imageid, $start, $end, $numMachines,
                               $usergroupid, $ignoreprivileges=0) {
	global $user, $xmlrpcBlockAPIUsers;
	if(! in_array($user['id'], $xmlrpcBlockAPIUsers)) {
		return array('status' => 'error',
		             'errorcode' => 34,
		             'errormsg' => 'access denied for managing block allocations');
	}
	$ownerid = getUserlistID('vclreload@Local');
	$name = "API:$start";
	$managementnodes = getManagementNodes('future');
	if(empty($managementnodes)) {
		return array('status' => 'error',
		             'errorcode' => 12,
		             'errormsg' => 'could not allocate a management node to handle block allocation');
	}
	$mnid = array_rand($managementnodes);
	$query = "INSERT INTO blockRequest "
	       .        "(name, "
	       .        "imageid, "
	       .        "numMachines, "
	       .        "groupid, "
	       .        "repeating, "
	       .        "ownerid, "
	       .        "admingroupid, "
	       .        "managementnodeid, "
	       .        "expireTime, "
	       .        "status) "
	       . "VALUES "
	       .        "('$name', "
	       .        "$imageid, "
	       .        "$numMachines, "
	       .        "$usergroupid, "
	       .        "'list', "
	       .        "$ownerid, "
	       .        "0, "
	       .        "$mnid, "
	       .        "'$end', "
	       .        "'accepted')";
	doQuery($query, 101);
	$brid = dbLastInsertID();
	$query = "INSERT INTO blockTimes "
	       .        "(blockRequestid, "
	       .        "start, "
	       .        "end) "
	       . "VALUES "
	       .        "($brid, "
	       .        "'$start', "
	       .        "'$end')";
	doQuery($query, 101);
	$btid = dbLastInsertID();
	$return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);
	$return['blockTimesid'] = $btid;
	return $return;
}

// Vulnerability class: CWE-20
function XMLRPCgetUserGroups($groupType=0, $affiliationid=0) {
    global $user;
    $groups = getUserGroups($groupType, $affiliationid);

    // Filter out any groups to which the user does not have access.
    $usergroups = array();
    foreach($groups as $id => $group){
        if($group['ownerid'] == $user['id'] || 
            (array_key_exists("editgroupid", $group) &&
            array_key_exists($group['editgroupid'], $user["groups"])) || 
            (array_key_exists($id, $user["groups"]))){
            array_push($usergroups, $group);
        }
    }
    return array(
            "status" => "success",
            "groups" => $usergroups);
}

// Vulnerability class: CWE-20
private function mail_passthru($to, $subject, $body, $header, $params) {
    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
    } else {
        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
    }
    return $rt;
  }

// Vulnerability class: CWE-20
public function Mail($from) {
    $this->error = null; // so no confusion is caused

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

    $useVerp = ($this->do_verp ? " XVERP" : "");
    fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $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 != 250) {
      $this->error =
        array("error" => "MAIL 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;
    }
    return true;
  }

// Vulnerability class: CWE-20
public function SendAndMail($from) {
    $this->error = null; // so no confusion is caused

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

    fputs($this->smtp_conn,"SAML FROM:" . $from . $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 != 250) {
      $this->error =
        array("error" => "SAML 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;
    }
    return true;
  }

// Vulnerability class: CWE-20
public function actionEditDropdown() {
        $model = new Dropdowns;

        if (isset($_POST['Dropdowns'])) {
            $model = Dropdowns::model()->findByPk(
                    $_POST['Dropdowns']['id']);
            if ($model->id == Actions::COLORS_DROPDOWN_ID) {
                if (AuxLib::issetIsArray($_POST['Dropdowns']['values']) &&
                        AuxLib::issetIsArray($_POST['Dropdowns']['labels']) &&
                        count($_POST['Dropdowns']['values']) ===
                        count($_POST['Dropdowns']['labels'])) {

                    if (AuxLib::issetIsArray($_POST['Admin']) &&
                            isset($_POST['Admin']['enableColorDropdownLegend'])) {

                        Yii::app()->settings->enableColorDropdownLegend = 
                            $_POST['Admin']['enableColorDropdownLegend'];
                        Yii::app()->settings->save();
                    }

                    $options = array_combine(
                            $_POST['Dropdowns']['values'], $_POST['Dropdowns']['labels']);
                    $temp = array();
                    foreach ($options as $value => $label) {
                        if ($value != "")
                            $temp[$value] = $label;
                    }
                    $model->options = json_encode($temp);
                    $model->save();
                }
            } else {
                $model->attributes = $_POST['Dropdowns'];
                $temp = array();
                if (is_array($model->options) && count($model->options) > 0) {
                    foreach ($model->options as $option) {
                        if ($option != "")
                            $temp[$option] = $option;
                    }
                    $model->options = json_encode($temp);
                    if ($model->save()) {
                        
                    }
                }
            }
        }
        $this->redirect(
                'manageDropDowns'
        );
    }

// Vulnerability class: CWE-20
public function actionGetItems() {
        $sql = 'SELECT id, name as value FROM x2_accounts 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 actionView($id) {
		$model = CActiveRecord::model('Docs')->findByPk($id);
        if (!$this->checkPermissions($model, 'view')) $this->denied ();

		if(isset($model)){
			$permissions=explode(", ",$model->editPermissions);
			if(in_array(Yii::app()->user->getName(),$permissions))
				$editFlag=true;
			else
				$editFlag=false;
		}
		//echo $model->visibility;exit;
		if (!isset($model) ||
			   !(($model->visibility==1 ||
				($model->visibility==0 && $model->createdBy==Yii::app()->user->getName())) ||
				Yii::app()->params->isAdmin|| $editFlag))
			$this->redirect(array('/docs/docs/index'));

        // add doc to user's recent item list
        User::addRecentItem('d', $id, Yii::app()->user->getId());
        X2Flow::trigger('RecordViewTrigger',array('model'=>$model));
		$this->render('view', array(
			'model' => $model,
		));
	}

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

// Vulnerability class: CWE-20
public function testGetFilteredEventsDataProvider () {
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('testuser');
        Yii::app()->settings->historyPrivacy = null;
        $profile = Profile::model()->findByAttributes(array('username' => 'testuser'));
        $retVal = Events::getFilteredEventsDataProvider ($profile, true, null, false);
        $dataProvider = $retVal['dataProvider'];
        $events = $dataProvider->getData ();
        $expectedEvents = Events::getEvents (0, 0, count ($events), $profile);

        // verify events from getData
        $this->assertEquals (
            Yii::app()->db->createCommand ("
                select id
                from x2_events
                where user='testuser' or visibility
                order by timestamp desc, id desc
            ")->queryColumn (),
            array_map (
                function ($event) { return $event->id; }, 
                $expectedEvents['events']
            )
        );

        // ensure that getFilteredEventsDataProvider returns same events as getData
        $this->assertEquals (
            array_map (
                function ($event) { return $event->id; }, 
                $expectedEvents['events']
            ),
            array_map (
                function ($event) { return $event->id; }, 
                $events
            )
        );
        TestingAuxLib::restoreX2WebUser ();
    }

// Vulnerability class: CWE-20
static public function getStatusText($_lng, $_status = 0)
	{
		switch($_status)
		{
			case 0:
				return $_lng['ticket']['open'];
				break;
			case 1:
				return $_lng['ticket']['wait_reply'];
				break;
			case 2:
				return $_lng['ticket']['replied'];
				break;
			default:
				return $_lng['ticket']['closed'];
				break;
		}
	}

// Vulnerability class: CWE-732
static public function getLastArchived($_num = 10, $_admin = 1) {

		if ($_num > 0) {

			$archived = array();
			$counter = 0;
			$result_stmt = Database::prepare("
				SELECT *, (
					SELECT COUNT(`sub`.`id`)
					FROM `" . TABLE_PANEL_TICKETS . "` `sub`
					WHERE `sub`.`answerto` = `main`.`id`
				) as `ticket_answers`
				FROM `" . TABLE_PANEL_TICKETS . "` `main`
				WHERE `main`.`answerto` = '0' AND `main`.`archived` = '1'
				AND `main`.`adminid` = :adminid
				ORDER BY `main`.`lastchange` DESC LIMIT 0, ".(int)$_num
			);
			Database::pexecute($result_stmt, array('adminid' => $_admin));

			while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {

				$archived[$counter]['id'] = $row['id'];
				$archived[$counter]['customerid'] = $row['customerid'];
				$archived[$counter]['adminid'] = $row['adminid'];
				$archived[$counter]['lastreplier'] = $row['lastreplier'];
				$archived[$counter]['ticket_answers'] = $row['ticket_answers'];
				$archived[$counter]['category'] = $row['category'];
				$archived[$counter]['priority'] = $row['priority'];
				$archived[$counter]['subject'] = $row['subject'];
				$archived[$counter]['message'] = $row['message'];
				$archived[$counter]['dt'] = $row['dt'];
				$archived[$counter]['lastchange'] = $row['lastchange'];
				$archived[$counter]['status'] = $row['status'];
				$archived[$counter]['by'] = $row['by'];
				$counter++;
			}

			if (isset($archived[0]['id'])) {
				return $archived;
			} else {
				return false;
			}
		}

// Vulnerability class: CWE-732
public function settings() {
        AuthUser::load();
        if (!AuthUser::isLoggedIn()) {
            redirect(get_url('login'));
        } else if (!AuthUser::hasPermission('admin_edit')) {
            Flash::set('error', __('You do not have permission to access the requested page!'));
            redirect(get_url());
        }
        
        $settings = Plugin::getAllSettings('file_manager');

        if (!$settings) {
            Flash::set('error', 'Files - ' . __('unable to retrieve plugin settings.'));
            return;
        }

        $this->display('file_manager/views/settings', array('settings' => $settings));
    }

// Vulnerability class: CWE-20
public function rename() {
        if (!AuthUser::hasPermission('file_manager_rename')) {
            Flash::set('error', __('You do not have sufficient permissions to rename this 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/rename')) {
                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['current_name'] = str_replace('..', '', $data['current_name']);
        $data['new_name'] = str_replace('..', '', $data['new_name']);

        // Clean filenames
        $data['new_name'] = preg_replace('/ /', '_', $data['new_name']);
        $data['new_name'] = preg_replace('/[^a-z0-9_\-\.]/i', '', $data['new_name']);

        $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));
        $file = FILES_DIR . '/' . $data['current_name'];

        // Check another file doesn't already exist with same name
        if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {
            Flash::set('error', __('A file or directory with that name already exists!'));
            redirect(get_url('plugin/file_manager/browse/' . $path));
        }

        if (file_exists($file)) {
            if (!rename($file, FILES_DIR . '/' . $path . '/' . $data['new_name']))
                Flash::set('error', __('Permission denied!'));
        }
        else {
            Flash::set('error', __('File or directory not found!' . $file));
        }

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

// Vulnerability class: CWE-20
function article_save()
{
    global $txp_user, $vars, $prefs;

    extract($prefs);

    $incoming = array_map('assert_string', psa($vars));

    $oldArticle = safe_row('Status, url_title, Title, '.
        'unix_timestamp(LastMod) as sLastMod, LastModID, '.
        'unix_timestamp(Posted) as sPosted, '.
        'unix_timestamp(Expires) as sExpires',
        'textpattern', 'ID = '.(int) $incoming['ID']);

// Vulnerability class: CWE-269
function insertObject($object, $table) {
        //if ($table=="text") eDebug($object,true); 
        $sql = "INSERT INTO `" . $this->prefix . "$table` (";
        $values = ") VALUES (";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            if ($var{0} != '_') {
                $sql .= "`$var`,";
                if ($values != ") VALUES (") {
                    $values .= ",";
                }
                $values .= "'" . $this->escapeString($val) . "'";
            }
        }
        $sql = substr($sql, 0, -1) . substr($values, 0) . ")";
        //if($table=='text')eDebug($sql,true);
        if (@mysqli_query($this->connection, $sql) != false) {
            $id = mysqli_insert_id($this->connection);
            return $id;
        } else
            return 0;
    }

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

// Vulnerability class: CWE-74
public function update() {
        global $user;

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

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

        $object = new stdClass();
        $object->id = $this->params['id'];
        $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], "user_id=" . $user->id);
        flash("message", gt("Successfully updated address."));
        expHistory::back(); 
    }

// Vulnerability class: CWE-74
public function toolbar() {
//        global $user;

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

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

        // sort the top level menus alphabetically by filename
		ksort($menu);		
		$sorted = array();
		foreach($menu as $m) $sorted[] = $m;
        
        // slingbar position
        if (isset($_COOKIE['slingbar-top'])){
            $top = $_COOKIE['slingbar-top'];
        } else {
            $top = SLINGBAR_TOP;
        }
        
		assign_to_template(array(
            'menu'=>(bs3()) ? $sorted : json_encode($sorted),
            "top"=>$top
        ));
    }

// Vulnerability class: CWE-74
function reset_stats() {
//        global $db;

        // reset the counters
//        $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');
        banner::resetImpressions();
//        $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');
        banner::resetClicks();
        
        // let the user know we did stuff.      
        flash('message', gt("Banner statistics reset."));
        expHistory::back();
    }

// Vulnerability class: CWE-74
public function approve_submit() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('No ID supplied for comment to approve'));
	        expHistory::back();
	    }
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];
	    
	    $comment = new expComment($this->params['id']);
	    $comment->body = $this->params['body'];
	    $comment->approved = $this->params['approved'];
	    $comment->save();
	    expHistory::back();
	}

// Vulnerability class: CWE-74
public function subscriptions() {
        global $db;
        
        expHistory::set('manageable', $this->params);
        // 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    
        $sub = new subscribers($this->params['id']);
        if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));
        
        // get this users subscriptions
        $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);
        
        // get a list of all available E-Alerts
        $ealerts = new expeAlerts();
        assign_to_template(array(
            'subscriber'=>$sub,
            'subscriptions'=>$subscriptions,
            'ealerts'=>$ealerts->find('all')
        ));
    }

// Vulnerability class: CWE-74
function delete_option_master() {
        global $db;

        $masteroption = new option_master($this->params['id']);
        
        // delete any implementations of this option master
        $db->delete('option', 'option_master_id='.$masteroption->id);
        $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);
        //eDebug($masteroption);
        expHistory::back();
    }

// Vulnerability class: CWE-74
function edit_optiongroup_master() {
        expHistory::set('editable', $this->params);
        
        $id = isset($this->params['id']) ? $this->params['id'] : null;
        $record = new optiongroup_master($id);       
        assign_to_template(array(
            'record'=>$record
        ));
    }

// Vulnerability class: CWE-74
function import() {
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname);
        $modules = new expPaginator(array(
            'records' => $pullable_modules,
            'controller' => $this->loc->mod,
            'action' => $this->params['action'],
            'order'   => isset($this->params['order']) ? $this->params['order'] : 'section',
            'dir'     => isset($this->params['dir']) ? $this->params['dir'] : '',
            'page'    => (isset($this->params['page']) ? $this->params['page'] : 1),
            'columns' => array(
                gt('Title') => 'title',
                gt('Page')  => 'section'
            ),
        ));

        assign_to_template(array(
            'modules' => $modules,
        ));
    }

// Vulnerability class: CWE-74
$body = str_replace(array("\n"), "<br />", $body);
                    } else {
                        // It's going elsewhere (doesn't like quoted-printable)
                        $body = str_replace(array("\n"), " -- ", $body);
                    }
                    $title = $items[$i]->title;

                    $msg .= "BEGIN:VEVENT\n";
                    $msg .= $dtstart . $dtend;
                    $msg .= "UID:" . $items[$i]->date_id . "\n";
                    $msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
                    if ($title) {
                        $msg .= "SUMMARY:$title\n";
                    }
                    if ($body) {
                        $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
                    }
                    //	if($link_url) { $msg .= "URL: $link_url\n";}
                    if (!empty($this->config['usecategories'])) {
                        if (!empty($items[$i]->expCat[0]->title)) {
                            $msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
                        } else {
                            $msg .= "CATEGORIES:".$this->config['uncat']."\n";
                        }
                    }
                    $msg .= "END:VEVENT\n";
                }

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

// Vulnerability class: CWE-74
public function buildControl() {
        $control = new colorcontrol();
        if (!empty($this->params['value'])) $control->value = $this->params['value'];
        if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];
        $control->default = $this->params['value'];
        if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];
        if (isset($this->params['flip'])) $control->flip = $this->params['flip'];
        $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';
        $control->name  = $this->params['name'];
        $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';
        $control->id  = isset($this->params['id']) && $this->params['id'] != "" ? $this->params['id'] : "";
        //echo $control->id;
        if (empty($control->id)) $control->id = $this->params['name'];
        if (empty($control->name)) $control->name = $this->params['id'];

        // attempt to translate the label
        if (!empty($this->params['label'])) {
            $this->params['label'] = gt($this->params['label']);
        } else {
            $this->params['label'] = null;
        }
        echo $control->toHTML($this->params['label'], $this->params['name']);
//        $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));
//        $ar->send();
    }

// Vulnerability class: CWE-74
function delete_selected() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item && $item->is_recurring == 1) {
            $event_remaining = false;
            $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);
            foreach ($eventdates as $ed) {
                if (array_key_exists($ed->id, $this->params['dates'])) {
                    $ed->delete();
                } else {
                    $event_remaining = true;
                }
            }
            if (!$event_remaining) {
                $item->delete(); // model will also ensure we delete all event dates
            }
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }

// Vulnerability class: CWE-74
public function get_view_config() {
        global $template;
        
        // set paths we will search in for the view
        $paths = array(
            BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',
            BASE.'framework/modules/common/views/file/configure',
        );

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

// Vulnerability class: CWE-74
public function editTitle() {
        global $user;
        $file = new expFile($this->params['id']);
        if ($user->id==$file->poster || $user->isAdmin()) {
            $file->title = $this->params['newValue'];
            $file->save();
            $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);
        } else {
            $ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
        }
        $ar->send();
    } 

// Vulnerability class: CWE-74
$src = substr($ref->source, strlen($prefix)) . $section->id;
            if (call_user_func(array($ref->module, 'hasContent'))) {
                $oloc = expCore::makeLocation($ref->module, $ref->source);
                $nloc = expCore::makeLocation($ref->module, $src);
                if ($ref->module != "container") {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);
                } else {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);
                }
            }
        }

// Vulnerability class: CWE-74
function remove() {
        global $db;

        $section = $db->selectObject('section', 'id=' . $this->params['id']);
        if ($section) {
            section::removeLevel($section->id);
            $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);
            $section->parent = -1;
            $db->updateObject($section, 'section');
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_authorized();
        }
    }

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

// Vulnerability class: CWE-74
$section  = new section($this->params);
        } else {
            notfoundController::handle_not_found();
            exit;
        }
        if (!empty($section->id)) {
            $check_id = $section->id;
        } else {
            $check_id = $section->parent;
        }
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {
            if (empty($section->id)) {
                $section->active = 1;
                $section->public = 1;
                if (!isset($section->parent)) {
                    // This is another precaution.  The parent attribute
                    // should ALWAYS be set by the caller.
                    //FJD - if that's the case, then we should die.
                    notfoundController::handle_not_authorized();
                    exit;
                    //$section->parent = 0;
                }
            }
            assign_to_template(array(
                'section' => $section,
                'glyphs' => self::get_glyphs(),
            ));
        } else {  // User does not have permission to manage sections.  Throw a 403
            notfoundController::handle_not_authorized();
        }
    }

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

// Vulnerability class: CWE-74
public function showall() {
        expHistory::set('viewable', $this->params);
        // figure out if should limit the results
        if (isset($this->params['limit'])) {
            $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];
        } else {
            $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
        }       
        $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';

        // pull the news posts from the database
        $items = $this->news->find('all', $this->aggregateWhereClause(), $order);

        // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.
        if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);
        
        // setup the pagination object to paginate the news stories.
        $page = new expPaginator(array(
            'records'=>$items,
            'limit'=>$limit,
            'order'=>$order,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'view'=>empty($this->params['view']) ? null : $this->params['view']
        ));
            
        assign_to_template(array(
            'page'=>$page,
            'items'=>$page->records,
            'rank'=>($order==='rank')?1:0,
            'params'=>$this->params,
        ));
    }

// Vulnerability class: CWE-74
public function autocomplete() {
        return;
        global $db;

        $model = $this->params['model'];
        $mod = new $model();
        $srchcol = explode(",",$this->params['searchoncol']);
        /*for ($i=0; $i<count($srchcol); $i++) {
            if ($i>=1) $sql .= " OR ";
            $sql .= $srchcol[$i].' LIKE \'%'.$this->params['query'].'%\'';
        }*/
        //    $sql .= ' AND parent_id=0';
        //eDebug($sql);
        
        //$res = $mod->find('all',$sql,'id',25);
        $sql = "select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from ".$db->prefix."product as p INNER JOIN ".$db->prefix."content_expfiles as cef ON p.id=cef.content_id INNER JOIN ".$db->prefix."expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') desc LIMIT 25";
        //$res = $db->selectObjectsBySql($sql);
        //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');
        
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }

// Vulnerability class: CWE-74
function addDiscountToCart() {
//        global $user, $order;
        global $order;
        //lookup discount to see if it's real and valid, and not already in our cart
        //this will change once we allow more than one coupon code

        $discount = new discounts();
        $discount = $discount->getCouponByName($this->params['coupon_code']);

        if (empty($discount)) {
            flash('error', gt("This discount code you entered does not exist."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));       
            expHistory::back();
        }

        //check to see if it's in our cart already
        if ($this->isDiscountInCart($discount->id)) {
            flash('error', gt("This discount code is already in your cart."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
            expHistory::back();
        }

        //this should really be reworked, as it shoudn't redirect directly and not return
        $validateDiscountMessage = $discount->validateDiscount();
        if ($validateDiscountMessage == "") {
            //if all good, add to cart, otherwise it will have redirected
            $od               = new order_discounts();
            $od->orders_id    = $order->id;
            $od->discounts_id = $discount->id;
            $od->coupon_code  = $discount->coupon_code;
            $od->title        = $discount->title;
            $od->body         = $discount->body;
            $od->save();
            // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;
            flash('message', gt("The discount code has been applied to your cart."));
        } else {
            flash('error', $validateDiscountMessage);
        }
        //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));                           
        expHistory::back();
    }

// Vulnerability class: CWE-20
function searchByModelForm() {
        // get the search terms
        $terms = $this->params['search_string'];

        $sql = "model like '%" . $terms . "%'";

        $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;
        $page = new expPaginator(array(
            'model'      => 'product',
            'where'      => $sql,
            'limit'      => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,
            'order'      => 'title',
            'dir'        => 'DESC',
            'page'       => (isset($this->params['page']) ? $this->params['page'] : 1),
            'controller' => $this->params['controller'],
            'action'     => $this->params['action'],
            'columns'    => array(
                gt('Model #')      => 'model',
                gt('Product Name') => 'title',
                gt('Price')        => 'base_price'
            ),
        ));

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

// Vulnerability class: CWE-20
function showallSubcategories() {
//        global $db;

        expHistory::set('viewable', $this->params);
//        $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');
        $catid = expSession::get('catid');
        $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);
        $category = new storeCategory($parent);
        $categories = $category->getEcomSubcategories();
        $ancestors = $category->pathToNode();
        assign_to_template(array(
            'categories' => $categories,
            'ancestors'  => $ancestors,
            'category'   => $category
        ));
    }

// Vulnerability class: CWE-20
protected function createSubRequest($uri, Request $request)
    {
        $cookies = $request->cookies->all();
        $server = $request->server->all();

        // Override the arguments to emulate a sub-request.
        // Sub-request object will point to localhost as client ip and real client ip
        // will be included into trusted header for client ip
        try {
            if ($trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
                $currentXForwardedFor = $request->headers->get($trustedHeaderName, '');

                $server['HTTP_'.$trustedHeaderName] = ($currentXForwardedFor ? $currentXForwardedFor.', ' : '').$request->getClientIp();
            }
        } catch (\InvalidArgumentException $e) {
            // Do nothing
        }

        $server['REMOTE_ADDR'] = $this->resolveTrustedProxy();

        unset($server['HTTP_IF_MODIFIED_SINCE']);
        unset($server['HTTP_IF_NONE_MATCH']);

        $subRequest = Request::create($uri, 'get', array(), $cookies, array(), $server);
        if ($request->headers->has('Surrogate-Capability')) {
            $subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability'));
        }

        if ($session = $request->getSession()) {
            $subRequest->setSession($session);
        }

        return $subRequest;
    }

// Vulnerability class: CWE-20
public function testXForwarderForHeaderForPassRequests()
    {
        $this->setNextResponse();
        $server = array('REMOTE_ADDR' => '10.0.0.1');
        $this->request('POST', '/', $server);

        $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
    }

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

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }

// Vulnerability class: CWE-200