mcanoglu/cwe-class-group huggingface dataset:
protected function sort(&$rowsKey, $sortColumn) {
		$sortMethod = $this->getTableSortMethod();
	
		if ($sortColumn < 0) {
			switch ($sortMethod) {
				case 'natural':
					// Reverse natsort()
                    uasort($rowsKey, function($first, $second) {
                    	return strnatcmp($second, $first);
					});
					break;
				case 'standard':
				default:
					arsort($rowsKey);
					break;
			}
		} else {
			switch ($sortMethod) {
				case 'natural':
				natsort($rowsKey);
				break;
			case 'standard':
			default:
				asort($rowsKey);
				break;
			}
		}
	}

// Vulnerability class: CWE-400
public function __construct() {
		global $wgRequest;

		$this->DB			= wfGetDB( DB_REPLICA, 'dpl' );
		$this->parameters	= new Parameters();
		$this->logger		= new Logger( $this->parameters->getData( 'debug' )['default'] );
		$this->tableNames	= Query::getTableNames();
		$this->wgRequest	= $wgRequest;
	}

// Vulnerability class: CWE-400
public function browse() {
        $params = func_get_args();

        $this->path = join('/', $params);
        // make sure there's a / at the end
        if (substr($this->path, -1, 1) != '/')
            $this->path .= '/';

        //security
        // we dont allow back link
        if (strpos($this->path, '..') !== false) {
            /*
            if (Plugin::isEnabled('statistics_api')) {
                $user = null;
                if (AuthUser::isLoggedIn())
                    $user = AuthUser::getUserName();
                $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);
                $event = array('event_type' => 'hack_attempt', // simple event type identifier
                    'description' => __('A possible hack attempt was detected.'), // translatable description
                    'ipaddress' => $ip,
                    'username' => $user);
                Observer::notify('stats_file_manager_hack_attempt', $event);
            }
             */
        }
        $this->path = str_replace('..', '', $this->path);

        // clean up nicely
        $this->path = str_replace('//', '', $this->path);

        // we dont allow leading slashes
        $this->path = preg_replace('/^\//', '', $this->path);

        $this->fullpath = FILES_DIR . '/' . $this->path;

        // clean up nicely
        $this->fullpath = preg_replace('/\/\//', '/', $this->fullpath);

        $this->display('file_manager/views/index', array(
            'dir' => $this->path,
            //'files' => $this->_getListFiles()
            'files' => $this->_listFiles()
        ));
    }

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

// Vulnerability class: CWE-20
public function renderAttribute ($name) {
        switch ($name) {
            case 'name':
                echo $this->relatedModel->getLink (/*array (
                    'class' => 'quick-read-link',
                    'data-id' => $this->relatedModel->id,
                    'data-class' => get_class ($this->relatedModel),
                    'data-name' => CHtml::encode ($this->relatedModel->name),
                )*/);
                break;
            case 'relatedModelName':
                echo $this->getRelatedModelName ();
                break;
            case 'assignedTo':
                echo $this->relatedModel->renderAttribute ('assignedTo');
                break;
            case 'label':
                echo $this->getLabel ();
                break;
            case 'createDate':
                echo X2Html::dynamicDate ($this->relatedModel->createDate);
                break;
        }
    }

// Vulnerability class: CWE-20
public function show()
    {
        $task = $this->getTask();
        $subtask = $this->getSubtask();

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

// Vulnerability class: CWE-200
public function Connect($host, $port = 0, $tval = 30) {
    // set the error val to null so there is no confusion
    $this->error = null;

    // make sure we are __not__ connected
    if($this->connected()) {
      // already connected, generate error
      $this->error = array("error" => "Already connected to a server");
      return false;
    }

    if(empty($port)) {
      $port = $this->SMTP_PORT;
    }

    // connect to the smtp server
    $this->smtp_conn = @fsockopen($host,    // the host of the server
                                 $port,    // the port to use
                                 $errno,   // error number if any
                                 $errstr,  // error message if any
                                 $tval);   // give up after ? secs
    // verify we connected properly
    if(empty($this->smtp_conn)) {
      $this->error = array("error" => "Failed to connect to server",
                           "errno" => $errno,
                           "errstr" => $errstr);
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />');
      }
      return false;
    }

    // SMTP server can take longer to respond, give longer timeout for first read
    // Windows does not have support for this timeout function
    if(substr(PHP_OS, 0, 3) != "WIN") {
     $max = ini_get('max_execution_time');
     if ($max != 0 && $tval > $max) { // don't bother if unlimited
      @set_time_limit($tval);
     }
     stream_set_timeout($this->smtp_conn, $tval, 0);
    }

    // get any announcement
    $announce = $this->get_lines();

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

    return true;
  }

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

// Vulnerability class: CWE-74
function getTypes($subtype="both") {
	$types = array("users" => array(),
	               "resources" => array());
	if($subtype == "users" || $subtype == "both") {
		$query = "SELECT id, name FROM userprivtype";
		$qh = doQuery($query, 365);
		while($row = mysql_fetch_assoc($qh)) {
			if($row["name"] == "block" || $row["name"] == "cascade")
				continue;
			$types["users"][$row["id"]] = $row["name"];
		}
	}
	if($subtype == "resources" || $subtype == "both") {
		$query = "SELECT id, name FROM resourcetype";
		$qh = doQuery($query, 366);
		while($row = mysql_fetch_assoc($qh)) {
			if($row["name"] == "block" || $row["name"] == "cascade")
				continue;
			$types["resources"][$row["id"]] = $row["name"];
		}
	}
	return $types;
}

// Vulnerability class: CWE-20
public function delete() {
        global $db, $history;
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];
        
        if (empty($this->params['id'])) {
            flash('error', gt('Missing id for the comment you would like to delete'));
            $lastUrl = expHistory::getLast('editable');
        }
        
        // delete the note
        $simplenote = new expSimpleNote($this->params['id']);
        $rows = $simplenote->delete();
        
        // delete the assocication too
        $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);        
        
        // send the user back where they came from.
        $lastUrl = expHistory::getLast('editable');
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }

// Vulnerability class: CWE-74
$payment->write();
                $i++;
            }

            // Ugly hack to set the money amount
            $this->payment->Status = 'Created';
            $this->payment->setAmount($total);

            // If not everything was refunded, the payment should still have the "Captured" status
            if ($total > 0) {
                $endStatus = 'Captured';
            }
        }

        parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
        if ($endStatus === 'Captured') {
            $this->createMessage(Message\PartiallyRefundedResponse::class, $gatewayMessage);
        } else {
            $this->createMessage(Message\RefundedResponse::class, $gatewayMessage);
        }

        ErrorHandling::safeExtend($this->payment, 'onRefunded', $serviceResponse);
    }

// Vulnerability class: CWE-436
public function urlProvider()
    {
        return array(
            array('http://till:test@svn.example.org/', $this->getCmd(" --username 'till' --password 'test' ")),
            array('http://svn.apache.org/', ''),
            array('svn://johndoe@example.org', $this->getCmd(" --username 'johndoe' --password '' ")),
        );
    }

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

// Vulnerability class: CWE-74
public function formatItem( Article $article, $pageText = null ) {
		$item = $article->mTitle;

		if ( $pageText !== null ) {
			//Include parsed/processed wiki markup content after each item before the closing tag.
			$item .= $pageText;
		}

		$item = $this->getItemStart() . $item . $this->itemEnd;

		$item = $this->replaceTagParameters( $item, $article );

		return $item;
	}

// Vulnerability class: CWE-400
public function showall() {
        expHistory::set('viewable', $this->params);
        $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
        if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {
            $limit = '0';
        }
        $order = isset($this->config['order']) ? $this->config['order'] : "rank";
        $page = new expPaginator(array(
            'model'=>'photo',
            'where'=>$this->aggregateWhereClause(),
            'limit'=>$limit,
            'order'=>$order,
            'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],
            'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),
            'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),
            'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title'
            ),
        ));
                    
        assign_to_template(array(
            'page'=>$page,
            'params'=>$this->params,
        ));
    }

// Vulnerability class: CWE-74
public function event()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

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

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

// Vulnerability class: CWE-200
function getUserGroupID($name, $affilid=DEFAULT_AFFILID) {
	$query = "SELECT id "
	       . "FROM usergroup "
	       . "WHERE name = '$name' AND "
	       .       "affiliationid = $affilid";
	$qh = doQuery($query, 300);
	if($row = mysql_fetch_row($qh)) {
		return $row[0];
	}
	$query = "INSERT INTO usergroup "
	       .        "(name, "
	       .        "affiliationid, "
	       .        "custom, "
	       .        "courseroll) "
	       . "VALUES "
	       .        "('$name', "
	       .        "$affilid, "
	       .        "0, "
	       .        "0)";
	doQuery($query, 301);
	$qh = doQuery("SELECT LAST_INSERT_ID() FROM usergroup", 302);
	if(! $row = mysql_fetch_row($qh)) {
		abort(303);
	}
	return $row[0];
}

// Vulnerability class: CWE-20
public function Connected() {
    if(!empty($this->smtp_conn)) {
      $sock_status = socket_get_status($this->smtp_conn);
      if($sock_status["eof"]) {
        // the socket is valid but we are not connected
        if($this->do_debug >= 1) {
            $this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
        }
        $this->Close();
        return false;
      }
      return true; // everything looks good
    }
    return false;
  }

// Vulnerability class: CWE-20
public function manage() {
        expHistory::set('manageable', $this->params);
        
        // build out a SQL query that gets all the data we need and is sortable.
        $sql  = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';
        $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';
        $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type="banner")';
		
		$page = new expPaginator(array(
			'model'=>'banner',
			'sql'=>$sql,
			'order'=>'title',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
			'columns'=>array(
                gt('Title')=>'title',
                gt('Company')=>'companyname',
                gt('Impressions')=>'impressions',
                gt('Clicks')=>'clicks'
            )
        ));

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

// Vulnerability class: CWE-74
function categoryBreadcrumb() {
//        global $db, $router;

        //eDebug($this->category);

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

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

// Vulnerability class: CWE-74
public function uploadCustomLogoAction(Request $request)
    {
        $fileExt = File::getFileExtension($_FILES['Filedata']['name']);
        if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {
            throw new \Exception('Unsupported file format');
        }

        if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), '<script')) {
            throw new \Exception('Scripts in SVG files are not supported');
        }

        $storage = Tool\Storage::get('admin');
        $storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));

        // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in
        // Ext.form.Action.Submit and mark the submission as failed

        $response = $this->adminJson(['success' => true]);
        $response->headers->set('Content-Type', 'text/html');

        return $response;
    }

// Vulnerability class: CWE-200
public function afterSave($event) {
        // look up current tags
        $oldTags = $this->getTags();
        $newTags = array();

        foreach ($this->scanForTags() as $tag) {
            if (!in_array($tag, $oldTags)) { // don't add duplicates if there are already tags
                $tagModel = new Tags;
                $tagModel->tag = $tag;  // includes the #
                $tagModel->type = get_class($this->getOwner());
                $tagModel->itemId = $this->getOwner()->id;
                $tagModel->itemName = $this->getOwner()->name;
                $tagModel->taggedBy = Yii::app()->getSuName();
                $tagModel->timestamp = time();
                if ($tagModel->save())
                    $newTags[] = $tag;
            }
        }
        $this->_tags = $newTags + $oldTags; // update tag cache

        if (!empty($newTags) && $this->flowTriggersEnabled) {
            X2Flow::trigger('RecordTagAddTrigger', array(
                'model' => $this->getOwner(),
                'tags' => $newTags,
            ));
        }
    }

// Vulnerability class: CWE-20
public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
        //echo "1<br>"; eDebug($str); 

        $str = str_replace("�", "&rsquo;", $str);
        $str = str_replace("�", "&lsquo;", $str);
        $str = str_replace("�", "&#174;", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "&#151;", $str);
        $str = str_replace("�", "&rdquo;", $str);
        $str = str_replace("�", "&ldquo;", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\t", " ", $str);
        $str = str_replace(",", "\,", $str);
        $str = str_replace("�", "&#188;", $str);
        $str = str_replace("�", "&#189;", $str);
        $str = str_replace("�", "&#190;", $str);

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

        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
        $str = trim(str_replace("�", "&trade;", $str));
        //echo "2<br>"; eDebug($str,die);
        return $str;
    }

// Vulnerability class: CWE-74
public static function getModelTypes($assoc = false) {
        $modelTypes = Yii::app()->db->createCommand()
                ->selectDistinct('modelName')
                ->from('x2_fields')
                ->where('modelName!="Calendar"')
                ->order('modelName ASC')
                ->queryColumn();

        if ($assoc === true) {
            return array_combine($modelTypes, array_map(function($term) {
                return Yii::t('app', X2Model::getModelTitle($term));
            }, $modelTypes));
        }
        $modelTypes = array_map(function($term) {
            return Yii::t('app', $term);
        }, $modelTypes);
        return $modelTypes;
    }

// Vulnerability class: CWE-20
protected function renderImageByGD($code)
    {
        $image = imagecreatetruecolor($this->width, $this->height);

        $backColor = imagecolorallocate(
            $image,
            (int) ($this->backColor % 0x1000000 / 0x10000),
            (int) ($this->backColor % 0x10000 / 0x100),
            $this->backColor % 0x100
        );
        imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
        imagecolordeallocate($image, $backColor);

        if ($this->transparent) {
            imagecolortransparent($image, $backColor);
        }

        $foreColor = imagecolorallocate(
            $image,
            (int) ($this->foreColor % 0x1000000 / 0x10000),
            (int) ($this->foreColor % 0x10000 / 0x100),
            $this->foreColor % 0x100
        );

        $length = strlen($code);
        $box = imagettfbbox(30, 0, $this->fontFile, $code);
        $w = $box[4] - $box[0] + $this->offset * ($length - 1);
        $h = $box[1] - $box[5];
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);
            $angle = mt_rand(-10, 10);
            $letter = $code[$i];
            $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
            $x = $box[2] + $this->offset;
        }

        imagecolordeallocate($image, $foreColor);

        ob_start();
        imagepng($image);
        imagedestroy($image);

        return ob_get_clean();
    }

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

// Vulnerability class: CWE-74
public static function newFromStyle( $style, \DPL\Parameters $parameters ) {
		$style = strtolower( $style );
		switch ( $style ) {
			case 'definition':
				$class = 'DefinitionHeading';
				break;
			case 'h1':
			case 'h2':
			case 'h3':
			case 'h4':
			case 'h5':
			case 'h6':
			case 'header':
				$class = 'TieredHeading';
				break;
			case 'ordered':
				$class = 'OrderedHeading';
				break;
			case 'unordered':
				$class = 'UnorderedHeading';
				break;
			default:
				return null;
				break;
		}
		$class = '\DPL\Heading\\' . $class;

		return new $class( $parameters );
	}

// Vulnerability class: CWE-400
$fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');
            if (empty($fileName)) {
                continue;
            }
            $templateBase = $inflector->filter(array(
                'module' => $moduleName,
                'controller' => $controllerName,
                'file' => $fileName)
            );

            $templateExtend = $inflector->filter(array(
                'module' => $moduleName,
                'controller' => $this->Request()->getControllerName(),
                'file' => $fileName)
            );
            if ($this->View()->templateExists($templateBase)) {
                $template .= '{include file="' . $templateBase. '"}' . "\n";
            }
            if ($this->View()->templateExists($templateExtend)) {
                $template .= '{include file="' . $templateExtend. '"}' . "\n";
            }
        }

// Vulnerability class: CWE-20
static function searchUser(AuthLDAP $authldap) {

      if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),
                                $authldap->getField('rootdn'),
                                Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),
                                $authldap->getField('use_tls'),
                                $authldap->getField('deref_option'))) {
         self::showLdapUsers();

      } else {
         echo "<div class='center b firstbloc'>".__('Unable to connect to the LDAP directory');
      }
   }

// Vulnerability class: CWE-327
public function approve() {
        expHistory::set('editable', $this->params);
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];
        
        if (empty($this->params['id'])) {
            flash('error', gt('No ID supplied for note to approve'));
            $lastUrl = expHistory::getLast('editable');
        }
        
        $simplenote = new expSimpleNote($this->params['id']);
        assign_to_template(array(
            'simplenote'=>$simplenote,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'tab'=>$this->params['tab']
        ));
    }

// Vulnerability class: CWE-74
$return[$index] = strip_tags($value);
			if($return[$index] == 'zero')
				$return[$index] = '0';
		}
	}
	elseif($type == ARG_MULTISTRING) {
		foreach($return as $index => $value) {
			$return[$index] = strip_tags($value);
		}
	}
	else
		$return = strip_tags($return);

	if(! empty($return) && $type == ARG_NUMERIC) {
		if(! is_numeric($return)) {
			return preg_replace('([^\d])', '', $return);
		}
	}
	elseif(! empty($return) && $type == ARG_STRING) {
		if(! is_string($return))
			$return = $defaultvalue;
	}
	elseif(! empty($return) && $type == ARG_MULTINUMERIC) {
		foreach($return as $index => $value) {
			if(! is_numeric($value)) {
				$return[$index] = preg_replace('([^\d])', '', $value);
			}
		}
		return $return;
	}
	elseif(! empty($return) && $type == ARG_MULTISTRING) {
		foreach($return as $index => $value) {
			if(! is_string($value))
				$return[$index] = $defaultvalue;
			elseif($addslashes)
				$return[$index] = addslashes($value);
		}
		return $return;
	}

	if(is_string($return)) {
		if(strlen($return) == 0)
			$return = $defaultvalue;
		elseif($addslashes)
			$return = addslashes($return);
	}

	return $return;
}

// Vulnerability class: CWE-20
public function searchNew() {
        global $db, $user;
        //$this->params['query'] = str_ireplace('-','\-',$this->params['query']);
        $sql = "select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, ";
        $sql .= "match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) as relevance, ";
        $sql .= "CASE when p.model like '" . $this->params['query'] . "%' then 1 else 0 END as modelmatch, ";
        $sql .= "CASE when p.title like '%" . $this->params['query'] . "%' then 1 else 0 END as titlematch ";
        $sql .= "from " . $db->prefix . "product as p INNER JOIN " .
            $db->prefix . "content_expFiles as cef ON p.id=cef.content_id AND cef.content_type IN ('product','eventregistration','donation','giftcard') AND cef.subtype='mainimage'  INNER JOIN " . $db->prefix .
            "expFiles as f ON cef.expFiles_id = f.id WHERE ";
        if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';
        $sql .= " match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) AND p.parent_id=0 ";
        $sql .= " HAVING relevance > 0 ";
        //$sql .= "GROUP BY p.id "; 
        $sql .= "order by modelmatch,titlematch,relevance desc LIMIT 10";

        eDebug($sql);
        $res = $db->selectObjectsBySql($sql);
        eDebug($res, true);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }

// Vulnerability class: CWE-74
foreach ($day as $extevent) {
                        $event_cache = new stdClass();
                        $event_cache->feed = $extgcalurl;
                        $event_cache->event_id = $extevent->event_id;
                        $event_cache->title = $extevent->title;
                        $event_cache->body = $extevent->body;
                        $event_cache->eventdate = $extevent->eventdate->date;
                        if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)
                            $event_cache->dateFinished = $extevent->dateFinished;
                        if (isset($extevent->eventstart))
                            $event_cache->eventstart = $extevent->eventstart;
                        if (isset($extevent->eventend))
                            $event_cache->eventend = $extevent->eventend;
                        if (isset($extevent->is_allday))
                            $event_cache->is_allday = $extevent->is_allday;
                        $found = false;
                        if ($extevent->eventdate->date < $start)   // prevent duplicating events crossing month boundaries
                            $found = $db->selectObject('event_cache','feed="'.$extgcalurl.'" AND event_id="'.$event_cache->event_id.'" AND eventdate='.$event_cache->eventdate);
                        if (!$found)
                            $db->insertObject($event_cache,'event_cache');
                    }

// Vulnerability class: CWE-74
foreach ($matches[1] as $index => $body) {
                    $parts = explode('_', $body);
                    $fileID = $parts[0];
                    $hash = $parts[1];
                    try {
                        $file = erLhcoreClassModelChatFile::fetch($fileID);
                        if (is_object($file) && $hash == $file->security_hash) {

                            $url = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect('file/downloadfile') . "/{$file->id}/{$hash}";

                            $media[] = array(
                                'id' => $file->id,
                                'size' => $file->size,
                                'upload_name' => $file->upload_name,
                                'type' => $file->type,
                                'extension' => $file->extension,
                                'hash' => $hash,
                                'url' => $url,
                            );

                            $msg_text_cleaned = str_replace($matches[0][$index],'',$msg_text_cleaned);
                        }

                    } catch (Exception $e) {

                    }
                }

// Vulnerability class: CWE-116
foreach ($week as $dayNum => $day) {
                        if ($dayNum == $now['mday']) {
                            $currentweek = $weekNum;
                        }
                        if ($dayNum <= $endofmonth) {
//                            $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects("eventdate", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
                            $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find("count", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
                        }
                    }

// Vulnerability class: CWE-74
public function test_valid_comment_allow_empty_content() {
		add_filter( 'allow_empty_comment', '__return_true' );
		$result = $this->myxmlrpcserver->wp_newComment(
			array(
				1,
				'administrator',
				'administrator',
				self::$post->ID,
				array(
					'content' => '   ',
				),
			)
		);

		$this->assertNotIXRError( $result );
	}

// Vulnerability class: CWE-862
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-74
private function _modifiedby( $option ) {
		$this->addTable( 'revision_actor_temp', 'change_rev' );
		$user = new \User;

		$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = change_rev.revactor_actor AND change_rev.revactor_page = page_id' );
	}

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

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

// Vulnerability class: CWE-863
public function handle($stanza, $parent = false)
    {
        $message = $stanza->forwarded->message;

        $jid = explode('/',(string)$message->attributes()->from);
        $to = current(explode('/',(string)$message->attributes()->to));

        if($message->composing)
            $this->event('composing', array($jid[0], $to));
        if($message->paused)
            $this->event('paused', array($jid[0], $to));
        if($message->gone)
            $this->event('gone', array($jid[0], $to));

        if($message->body || $message->subject) {
            $m = new \Modl\Message;
            $m->set($message, $stanza->forwarded);

            if(!preg_match('#^\?OTR#', $m->body)) {
                $md = new \Modl\MessageDAO;
                $md->set($m);

                $this->pack($m);
                $this->deliver();
            }
        }
    }

// Vulnerability class: CWE-346
function process_subsections($parent_section, $subtpl) {
        global $db, $router;

        $section              = new stdClass();
        $section->parent      = $parent_section->id;
        $section->name        = $subtpl->name;
        $section->sef_name    = $router->encode($section->name);
        $section->subtheme    = $subtpl->subtheme;
        $section->active      = $subtpl->active;
        $section->public      = $subtpl->public;
        $section->rank        = $subtpl->rank;
        $section->page_title  = $subtpl->page_title;
        $section->keywords    = $subtpl->keywords;
        $section->description = $subtpl->description;
        $section->id          = $db->insertObject($section, 'section');
        self::process_section($section, $subtpl);
    }

// Vulnerability class: CWE-74
$layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair
            $changed = true;
        }

        // remove obsolete widgets
        $arrayDiff =
                array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));
        foreach($arrayDiff as $elem){
            if(in_array ($elem, array_keys ($layout[$position]))) {
                unset($layout[$position][$elem]);
                $changed = true;
            } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {
                unset($layout['hidden'][$elem]);
                $changed = true;
            }
        }


        // ensure that widget properties are the same as those in the default layout
        foreach($layout[$position] as $name=>$arr){
            if (in_array ($name, array_keys ($initLayout[$position])) &&
                $initLayout[$position][$name]['title'] !== $arr['title']) {

                $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];
                $changed = true;
            }
        }
        if ($position === 'center') {
            foreach($layout['hidden'] as $name=>$arr){
                if (in_array ($name, array_keys ($initLayout[$position])) &&
                    $initLayout[$position][$name]['title'] !== $arr['title']) {

                    $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];
                    $changed = true;
                }
            }
        }

        if($changed){
            $this->layout = json_encode($layout);
            $this->update(array('layout'));
        }
    }

// Vulnerability class: CWE-20
foreach($row as $key => $value) {
			$type = gettype($value);
			$sqltype=NULL;
			switch($type) {
				case "integer":
					$sqltype = SQLITE3_INTEGER;
				break;
				case "string":
					$sqltype = SQLITE3_TEXT;
				break;
				case "NULL":
					$sqltype = SQLITE3_NULL;
				break;
				default:
					$sqltype = "UNK";
			}
			$stmt->bindValue(":".$key, $value, $sqltype);
		}

// Vulnerability class: CWE-862
public function getBranches()
    {
        if (null === $this->branches) {
            $branches = array();

            $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {
                    if (Preg::isMatch('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {
                        $branches[$match[1]] = $match[2];
                    }
                }
            }

            $this->branches = $branches;
        }

        return $this->branches;
    }

// Vulnerability class: CWE-20
public function params()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

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

        $action = $this->actionManager->getAction($values['action_name']);
        $action_params = $action->getActionRequiredParameters();

        if (empty($action_params)) {
            $this->doCreation($project, $values + array('params' => array()));
        }

        $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
        unset($projects_list[$project['id']]);

        $this->response->html($this->template->render('action_creation/params', array(
            'values' => $values,
            'action_params' => $action_params,
            'columns_list' => $this->columnModel->getList($project['id']),
            'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
            'projects_list' => $projects_list,
            'colors_list' => $this->colorModel->getList(),
            'categories_list' => $this->categoryModel->getList($project['id']),
            'links_list' => $this->linkModel->getList(0, false),
            'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'swimlane_list' => $this->swimlaneModel->getList($project['id']),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }

// Vulnerability class: CWE-200
public function beforeSave () {
        $valid = parent::beforeSave ();
        if ($valid) {
            $table = Yii::app()->db->schema->tables[$this->myTableName];
            $existing = array_key_exists($this->fieldName, $table->columns) && 
                $table->columns[$this->fieldName] instanceof CDbColumnSchema;
            if($existing){ 
                $valid = $this->modifyColumn();
            }
        }
        return $valid;
    }

// Vulnerability class: CWE-20
public function testPOSTForRegularUser()
    {
        $post_resource = json_encode([
            'label' => 'Test Request 9747 regular user',
            'shortname'  => 'test9747-regular-user',
            'description' => 'Test of Request 9747 for REST API Project Creation',
            'is_public' => true,
            'template_id' => 100,
        ]);

        $response = $this->getResponseByName(
            REST_TestDataBuilder::TEST_USER_2_NAME,
            $this->request_factory->createRequest(
                'POST',
                'projects'
            )->withBody(
                $this->stream_factory->createStream($post_resource)
            )
        );

        self::assertEquals(201, $response->getStatusCode());

        $create_project_id = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR)['id'];

        $this->removeAdminFromProjectMembers(
            $create_project_id,
            REST_TestDataBuilder::TEST_USER_2_NAME,
        );
    }

// Vulnerability class: CWE-863
private function __checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)
    {
        // check if the event already exist (using the uuid)
        $existingEvent = $eventModel->find('first', array('conditions' => array('Event.uuid' => $event['Event']['uuid'])));
        $passAlong = $server['Server']['id'];
        if (!$existingEvent) {
            // add data for newly imported events
            $result = $eventModel->_add($event, true, $user, $server['Server']['org_id'], $passAlong, true, $jobId);
            if ($result === true) {
                $successes[] = $eventId;
            } else {
                $fails[$eventId] = __('Failed (partially?) because of errors: ') . $result;
            }
        } else {
            if (!$existingEvent['Event']['locked'] && !$server['Server']['internal']) {
                $fails[$eventId] = __('Blocked an edit to an event that was created locally. This can happen if a synchronised event that was created on this instance was modified by an administrator on the remote side.');
            } else {
                $result = $eventModel->_edit($event, $user, $existingEvent['Event']['id'], $jobId, $passAlong);
                if ($result === true) {
                    $successes[] = $eventId;
                } elseif (isset($result['error'])) {
                    $fails[$eventId] = $result['error'];
                } else {
                    $fails[$eventId] = json_encode($result);
                }
            }
        }
    }

// Vulnerability class: CWE-269
$object->size = convert_size($cur->getSize());
                $object->mtime = date('D, j M, Y', $cur->getMTime());
                list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());
                
                // Find the file type
                $object->type = $this->_getFileType($cur);

                // make the link depending on if it's a file or a dir
                if ($cur->isDir()) {
                    $object->link = '<a href="' . get_url('plugin/file_manager/browse/' . $this->path . $object->name) . '">' . $object->name . '</a>';
                } else {
                    $object->link = '<a href="' . get_url('plugin/file_manager/view/' . $this->path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '">' . $object->name . '</a>';
                }

                $files[$object->name] = $object;
            }

// Vulnerability class: CWE-20
function current_user_get_bug_filter( $p_project_id = null ) {
	$f_filter_string = gpc_get_string( 'filter', '' );
	$t_filter = '';

	if( !is_blank( $f_filter_string ) ) {
		if( is_numeric( $f_filter_string ) ) {
			$t_token = token_get_value( TOKEN_FILTER );
			if( null != $t_token ) {
				$t_filter = json_decode( $t_token, true );
			}
		} else {
			$t_filter = json_decode( $f_filter_string, true );
		}
		$t_filter = filter_ensure_valid_filter( $t_filter );
	} else if( !filter_is_cookie_valid() ) {
		$t_filter = filter_get_default();
	} else {
		$t_user_id = auth_get_current_user_id();
		$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );
	}

	return $t_filter;
}

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

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

		$result  = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$comment = get_comment( $result );
		$user_id = get_user_by( 'login', 'administrator' )->ID;

		$this->assertSame( $user_id, (int) $comment->user_id );
	}

// Vulnerability class: CWE-862
function prepareInputForUpdate($input) {

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

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

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

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

// Vulnerability class: CWE-327