mcanoglu/cwe-class-group huggingface dataset:
public function confirm()
    {
        $project = $this->getProject();

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

// Vulnerability class: CWE-200
function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
        if (empty($endtimestamp)) {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
        } else {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
        }
        if ($multiday)
            $date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
        $date_sql .= ")";
        return $date_sql;
    }

// Vulnerability class: CWE-74
static function encrypt($string, $key) {

      $result = '';
      for ($i=0; $i<strlen($string); $i++) {
         $char    = substr($string, $i, 1);
         $keychar = substr($key, ($i % strlen($key))-1, 1);
         $char    = chr(ord($char)+ord($keychar));
         $result .= $char;
      }
      return base64_encode($result);
   }

// Vulnerability class: CWE-327
public function Login ($username = '', $password = '') {
    if ($this->connected == false) {
      $this->error = 'Not connected to POP3 server';

      if ($this->do_debug >= 1) {
        $this->displayErrors();
      }
    }

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

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

    $pop_username = "USER $username" . $this->CRLF;
    $pop_password = "PASS $password" . $this->CRLF;

    //  Send the Username
    $this->sendString($pop_username);
    $pop3_response = $this->getResponse();

    if ($this->checkResponse($pop3_response)) {
      //  Send the Password
      $this->sendString($pop_password);
      $pop3_response = $this->getResponse();

      if ($this->checkResponse($pop3_response)) {
        return true;
      }
    }
    return false;
  }

// Vulnerability class: CWE-20
function reparent_standalone() {
        $standalone = $this->section->find($this->params['page']);
        if ($standalone) {
            $standalone->parent = $this->params['parent'];
            $standalone->update();
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }

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

		$this->assertIXRError( $result );
		$this->assertSame( 403, $result->code );
	}

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

// Vulnerability class: CWE-20
public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
    {
        if (\strpos((string) $response->getStatusCode(), '3') !== 0
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request, $response, $options);
        $nextRequest = $this->modifyRequest($request, $options, $response);

        // If authorization is handled by curl, unset it if host is different.
        if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()
            && defined('\CURLOPT_HTTPAUTH')
        ) {
            unset(
                $options['curl'][\CURLOPT_HTTPAUTH],
                $options['curl'][\CURLOPT_USERPWD]
            );
        }

        if (isset($options['allow_redirects']['on_redirect'])) {
            ($options['allow_redirects']['on_redirect'])(
                $request,
                $response,
                $nextRequest->getUri()
            );
        }

        $promise = $this($nextRequest, $options);

        // Add headers to be able to track history of redirects.
        if (!empty($options['allow_redirects']['track_redirects'])) {
            return $this->withTracking(
                $promise,
                (string) $nextRequest->getUri(),
                $response->getStatusCode()
            );
        }

        return $promise;
    }

// Vulnerability class: CWE-200
public function configure() {
        $this->config['defaultbanner'] = array();
        if (!empty($this->config['defaultbanner_id'])) {
            $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);
        }  
	    parent::configure();
	    $banners = $this->banner->find('all', null, 'companies_id');
	    assign_to_template(array(
            'banners'=>$banners,
            'title'=>static::displayname()
        ));
	}

// Vulnerability class: CWE-74
protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 20) {
            $this->maxLength = 20;
        }
        $length = mt_rand($this->minLength, $this->maxLength);

        $letters = 'bcdfghjklmnpqrstvwxyz';
        $vowels = 'aeiou';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
                $code .= $vowels[mt_rand(0, 4)];
            } else {
                $code .= $letters[mt_rand(0, 20)];
            }
        }

        return $code;
    }

// Vulnerability class: CWE-330
function __construct() {
		$this->mDb = GlobalNewFilesHooks::getGlobalDB( DB_REPLICA, 'gnf_files' );

		if ( $this->getRequest()->getText( 'sort', 'files_date' ) == 'files_date' ) {
			$this->mDefaultDirection = IndexPager::DIR_DESCENDING;
		} else {
			$this->mDefaultDirection = IndexPager::DIR_ASCENDING;
		}

		parent::__construct( $this->getContext() );
	}

// Vulnerability class: CWE-20
foreach ($flatArray as $key => $value) {
            $pattern = '/' . $key . '([^.]|$)/';
            if (preg_match($pattern, $expression, $matches)) {

                switch (gettype($flatArray[$key])) {
                    case 'boolean':
                        $expression = str_replace($key, $flatArray[$key] ? 'true' : 'false', $expression);
                        break;
                    case 'NULL':
                        $expression = str_replace($key, 'false', $expression);
                        break;
                    case 'string':
                        $expression = str_replace($key, '"' . $flatArray[$key] . '"', $expression);
                        break;
                    case 'object':
                        $expression = self::executeClosure($expression, $key, $flatArray[$key], $flatArray);
                        break;
                    default:
                        $expression = str_replace($key, $flatArray[$key], $expression);
                        break;
                }
                $bool = eval("return $expression;");
            }
        }

// Vulnerability class: CWE-74
public static function endReset( &$parser, $text ) {
		if ( !self::$createdLinks['resetdone'] ) {
			self::$createdLinks['resetdone'] = true;
			foreach ( $parser->getOutput()->mCategories as $key => $val ) {
				if ( array_key_exists( $key, self::$fixedCategories ) ) {
					self::$fixedCategories[$key] = $val;
				}
			}
			// $text .= self::dumpParsedRefs($parser,"before final reset");
			if ( self::$createdLinks['resetLinks'] ) {
				$parser->getOutput()->mLinks = [];
			}
			if ( self::$createdLinks['resetCategories'] ) {
				$parser->getOutput()->mCategories = self::$fixedCategories;
			}
			if ( self::$createdLinks['resetTemplates'] ) {
				$parser->getOutput()->mTemplates = [];
			}
			if ( self::$createdLinks['resetImages'] ) {
				$parser->getOutput()->mImages = [];
			}
			// $text .= self::dumpParsedRefs( $parser, 'after final reset' );
			self::$fixedCategories = [];
		}
		return true;
	}

// Vulnerability class: CWE-400
private function _getMetaTags()
    {
        $retval  = '<meta charset="utf-8" />';
        $retval .= '<meta name="referrer" content="none" />';
        $retval .= '<meta name="robots" content="noindex,nofollow" />';
        $retval .= '<meta http-equiv="X-UA-Compatible" content="IE=Edge">';
        if (! $GLOBALS['cfg']['AllowThirdPartyFraming']) {
            $retval .= '<style id="cfs-style">html{display: none;}</style>';
        }
        return $retval;
    }

// Vulnerability class: CWE-200
$parser->getOutput()->mTemplates[$nsp] = array_diff_assoc( $parser->getOutput()->mTemplates[$nsp], self::$createdLinks[1][$nsp] );
					// echo ("<pre> elim: parser  Tpls [$nsp] nachher = ". count($parser->getOutput()->mTemplates[$nsp])	 ."</pre>\n");
					if ( count( $parser->getOutput()->mTemplates[$nsp] ) == 0 ) {
						unset( $parser->getOutput()->mTemplates[$nsp] );
					}
				}
			}

// Vulnerability class: CWE-400
function XMLRPCgetResourceGroupPrivs($name, $type, $nodeid){
    require_once(".ht-inc/privileges.php");
    global $user;

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

    if($typeid = getResourceTypeID($type)){
        if(!checkForGroupName($name, 'resource', '', $typeid)){
            return array('status' => 'error',
                         'errorcode' => 28,
                         'errormsg' => 'resource group does not exist');
        }
        $nodePrivileges = getNodePrivileges($nodeid, 'resources');
        $nodePrivileges = getNodeCascadePrivileges($nodeid, 'resources', $nodePrivileges); 
        foreach($nodePrivileges['resources'] as $resource => $privs){
            if(strstr($resource, "$type/$name")){
                return array(
                    'status' => 'success',
                    'privileges' => $privs);
            }
        }
        return array(
            'status' => 'error',
            'errorcode' => 29,
            'errormsg' => 'could not find resource name in privilege list');
    } else {
        return array('status' => 'error',
                     'errorcode' => 56,
                     'errormsg' => 'Invalid resource type');
    }
}

// Vulnerability class: CWE-20
public function upload() {
        if (!AuthUser::hasPermission('file_manager_upload')) {
            Flash::set('error', __('You do not have sufficient permissions to upload a file.'));
            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/upload')) {
                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/'));
        }
        
        $mask = Plugin::getSetting('umask', 'file_manager');
        umask(octdec($mask));

        $data = $_POST['upload'];
        $path = str_replace('..', '', $data['path']);
        $overwrite = isset($data['overwrite']) ? true : false;

        // Clean filenames
        $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);
        $filename = preg_replace('/[^a-z0-9_\-\.]/i', '', $filename);

        if (isset($_FILES)) {
            $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);

            if ($file === false)
                Flash::set('error', __('File has not been uploaded!'));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }

// Vulnerability class: CWE-20
public static function validateNumber(
        $path,
        $values,
        $allow_neg,
        $allow_zero,
        $max_value,
        $error_string
    ) {
        if ($values[$path] === '') {
            return '';
        }

        if (intval($values[$path]) != $values[$path]
            || (! $allow_neg && $values[$path] < 0)
            || (! $allow_zero && $values[$path] == 0)
            || $values[$path] > $max_value
        ) {
            return $error_string;
        }

        return '';
    }

// Vulnerability class: CWE-200
static public function getHighestOrderNumber($_uid = 0) {

		$where = '';
		$sel_data = array();
		if ($_uid > 0) {
			$where = " WHERE `adminid` = :adminid";
			$sel_data['adminid'] = $_uid;
		}
		$sql = "SELECT MAX(`logicalorder`) as `highestorder` FROM `" . TABLE_PANEL_TICKET_CATS . "`".$where.";";
		$result_stmt = Database::prepare($sql);
		$result = Database::pexecute_first($result_stmt, $sel_data);
		return (isset($result['highestorder']) ? (int)$result['highestorder'] : 0);
	}

// Vulnerability class: CWE-732
public static function init( $settings = false ) {
		if ( $settings === false ) {
			global $wgDplSettings;

			$settings = $wgDplSettings;
		}

		if ( !is_array( $settings ) ) {
			throw new MWException( __METHOD__ . ": Invalid settings passed." );
		}

		self::$settings = array_merge( self::$settings, $settings );
	}

// Vulnerability class: CWE-400
static function testLDAPConnection($auths_id, $replicate_id = -1) {

      $config_ldap = new self();
      $res         = $config_ldap->getFromDB($auths_id);

      // we prevent some delay...
      if (!$res) {
         return false;
      }

      //Test connection to a replicate
      if ($replicate_id != -1) {
         $replicate = new AuthLdapReplicate();
         $replicate->getFromDB($replicate_id);
         $host = $replicate->fields["host"];
         $port = $replicate->fields["port"];

      } else {
         //Test connection to a master ldap server
         $host = $config_ldap->fields['host'];
         $port = $config_ldap->fields['port'];
      }
      $ds = self::connectToServer($host, $port, $config_ldap->fields['rootdn'],
                                  Toolbox::decrypt($config_ldap->fields['rootdn_passwd'], GLPIKEY),
                                  $config_ldap->fields['use_tls'],
                                  $config_ldap->fields['deref_option']);
      if ($ds) {
         return true;
      }
      return false;
   }

// Vulnerability class: CWE-327
$curVal[$key] = $tp->post_toForm($val);
			}
		}

		$target = e107::getUrl()->create('user/myprofile/edit',array('id'=>USERID));

		$text = '<form method="post" action="'.$target.'" id="dataform" class="usersettings-form form-horizontal"  enctype="multipart/form-data" autocomplete="off">';

		//$text = (is_numeric($_uid) ? $rs->form_open("post", e_SELF."?".e_QUERY, "dataform", "", " class='form-horizontal' role='form' enctype='multipart/form-data'") : $rs->form_open("post", e_SELF, "dataform", "", " class='form-horizontal' role='form' enctype='multipart/form-data'"));

		if (e_QUERY == "update")
		{
			$text .= "<div class='fborder' style='text-align:center'><br />".str_replace("*", "<span class='required'>*</span>", LAN_USET_9)."<br />".LAN_USET_10."<br /><br /></div>";
		}

		// e107::scStyle($sc_style);
		e107::getScBatch('usersettings')->setVars($curVal)->reset();

		$USERSETTINGS_EDIT = $this->getTemplate('edit');
		$USERSETTINGS_EDIT_CAPTION = $this->getTemplate('edit_caption');

		$text .= $tp->parseTemplate($USERSETTINGS_EDIT, true, $this->sc); //ParseSC must be set to true so that custom plugin -shortcodes can be utilized.


		$text .= "<div><input type='hidden' name='_uid' value='{$uuid}' /></div>
		</form>
		";

		$caption = (isset($USERSETTINGS_EDIT_CAPTION)) ? $USERSETTINGS_EDIT_CAPTION : LAN_USET_39; // 'Update User Settings'

		$ns->tablerender($caption, $text);





	}

// Vulnerability class: CWE-326
function update_optiongroup_master() {
        global $db;

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $og = new optiongroup_master($id);
        $oldtitle = $og->title;
        $og->update($this->params);
        
        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $og->title) {
            $db->sql('UPDATE '.$db->prefix.'optiongroup SET title="'.$og->title.'" WHERE title="'.$oldtitle.'"');
        }
        
        expHistory::back();
    }

// Vulnerability class: CWE-74
private function _createdby( $option ) {
		$this->addTable( 'revision', 'creation_rev' );
		$this->addTable( 'revision_actor_temp', 'creation_rev_actor' );
		$this->_adduser( null, 'creation_rev_actor' );
		$user = new \User;

		$this->addWhere(
			[
				$this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = creation_rev_actor.revactor_actor',
				'creation_rev_actor.revactor_page = page_id',
				'creation_rev.rev_parent_id = 0'
			]
		);
	}

// Vulnerability class: CWE-400
$dplArg = $this->wgRequest->getVal( $arg, '' );
			if ( $dplArg == '' ) {
				$input = preg_replace( '/\{%' . $arg . ':(.*)%\}/U', '\1', $input );
				$input = str_replace( '{%' . $arg . '%}', '', $input );
			} else {
				$input = preg_replace( '/\{%' . $arg . ':.*%\}/U  ', $dplArg, $input );
				$input = str_replace( '{%' . $arg . '%}', $dplArg, $input );
			}
		}
		return $input;
	}

// Vulnerability class: CWE-400
public function assets_path($file = NULL, $path = NULL, $module = NULL, $absolute = NULL)
	{
		$cache = '';
		if (!isset($absolute)) $absolute = $this->assets_absolute_path;
		
		$CI = $this->_get_assets_config();
		if ($this->asset_append_cache_timestamp AND in_array($path, $this->asset_append_cache_timestamp) AND !empty($file))
		{
			$q_str = (strpos($file, '?') === FALSE) ? '?' : '&';
			$cache = $q_str.'c='.strtotime($this->assets_last_updated);
		}
	
		// if it is an absolute path already provided, then we just return it without any caching
		if (!$this->_is_local_path($file))
		{
			return $file.$cache;
		}
		
		$assets_folders = $this->assets_folders;

		$asset_type = (!empty($assets_folders[$path])) ? $assets_folders[$path] : $CI->config->item($path);

		// if absolute path, then we just return that
		if (!$this->_is_local_path($this->assets_path))
		{
			return $this->assets_path.$asset_type.$file.$cache;
		}

		$assets_path = $this->_get_assets_path($module);
		
		$path = WEB_PATH.$assets_path.$asset_type.$file.$cache;

		if ($absolute)
		{
			$protocol = ($_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
			$path = $protocol.$_SERVER['HTTP_HOST'].$path;
		}
		return $path;
	}

// Vulnerability class: CWE-74
public function behaviors() {
		return array_merge(parent::behaviors(),array(
			'X2LinkableBehavior'=>array(
				'class'=>'X2LinkableBehavior',
				'module'=>'marketing'
			),
			'ERememberFiltersBehavior' => array(
				'class'=>'application.components.ERememberFiltersBehavior',
				'defaults'=>array(),
				'defaultStickOnClear'=>false
			)
		));
	}

// Vulnerability class: CWE-20
static public function customerHasTickets($_cid = 0) {

		if ($_cid != 0) {
			$result_stmt = Database::prepare("
				SELECT `id` FROM `" . TABLE_PANEL_TICKETS . "` WHERE `customerid` = :cid"
			);
			Database::pexecute($result_stmt, array('cid' => $_cid));

			$tickets = array();
			while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {
				$tickets[] = $row['id'];
			}

			return $tickets;
		}

		return false;
	}

// Vulnerability class: CWE-732
function manage() {
        expHistory::set('viewable', $this->params);
        //         $category = new storeCategory();
        //         $categories = $category->getFullTree();
        //         
        //         // foreach($categories as $i=>$val){
        //         //  if (!empty($this->values) && in_array($val->id,$this->values)) {
        //         //      $this->tags[$i]->value = true;
        //         //  } else {
        //         //      $this->tags[$i]->value = false;
        //         //  }
        //         //  $this->tags[$i]->draggable = $this->draggable; 
        //         //  $this->tags[$i]->checkable = $this->checkable; 
        //         // }
        //
        // $obj = json_encode($categories);  
    }

// Vulnerability class: CWE-74
public function isLocal() {
    $localhosts = array('::1', '127.0.0.1', '0.0.0.0');
    return (
      in_array(server::get('SERVER_ADDR'), $localhosts) ||
      server::get('SERVER_NAME') == 'localhost' ||
      str::endsWith(server::get('SERVER_NAME'), '.localhost') ||
      str::endsWith(server::get('SERVER_NAME'), '.test')
    );
  }

// Vulnerability class: CWE-346
public function getListStart() {
		// increase start value of ordered lists at multi-column output
		//The offset that comes from the URL parameter is zero based, but has to be +1'ed for display.
		$offset = $this->getParameters()->getParameter( 'offset' ) + 1;

		if ( $offset != 0 ) {
			//@TODO: So this adds the total count of articles to the offset.  I have not found a case where this does not mess up the displayed count.  I am commenting this out for now.
			//$offset += $this->offsetCount;
		}

		return sprintf( $this->listStart, $this->listAttributes . ' start="' . $offset . '"' );
	}

// Vulnerability class: CWE-400
$connecttext = preg_replace("/#connectport#/", $connectport, $connecttext); 
            $connectMethods[$key]["connecttext"] = $connecttext;
        }
		return array('status' => 'ready',
		             'serverIP' => $serverIP,
		             'user' => $thisuser,
                     'password' => $passwd,
                     'connectport' => $connectport,
                     'connectMethods' => $connectMethods);
	}
	return array('status' => 'notready');
}

// Vulnerability class: CWE-20
function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}
		
		return $records;
	}

// Vulnerability class: CWE-74
public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $swimlane_id = $this->request->getIntegerParam('swimlane_id');

        if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this swimlane.'));
        }

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

// Vulnerability class: CWE-200
private function get_lines() {
    $data = "";
    $endtime = 0;
    /* If for some reason the fp is bad, don't inf loop */
    if (!is_resource($this->smtp_conn)) {
      return $data;
    }
    stream_set_timeout($this->smtp_conn, $this->Timeout);
    if ($this->Timelimit > 0) {
      $endtime = time() + $this->Timelimit;
    }
    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
      $str = @fgets($this->smtp_conn,515);
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />');
        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />');
      }
      $data .= $str;
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />');
      }
      // if 4th character is a space, we are done reading, break the loop
      if(substr($str,3,1) == " ") { break; }
      // Timed-out? Log and break
      $info = stream_get_meta_data($this->smtp_conn);
      if ($info['timed_out']) {
        if($this->do_debug >= 4) {
          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds) <br />");
        }
        break;
      }
      // Now check if reads took too long
      if ($endtime) {
        if (time() > $endtime) {
          if($this->do_debug >= 4) {
            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds) <br />");
          }
          break;
        }
      }
    }
    return $data;
  }

// Vulnerability class: CWE-20
public function testAuth()
    {
        if (! defined('PMA_TEST_HEADERS')) {
            $this->markTestSkipped(
                'Cannot redefine constant/function - missing runkit extension'
            );
        }

        // case 1

        $GLOBALS['cfg']['Server']['SignonURL'] = '';

        ob_start();
        $this->object->auth();
        $result = ob_get_clean();

        $this->assertContains(
            'You must set SignonURL!',
            $result
        );

        // case 2

        $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';
        $_REQUEST['old_usr'] = 'oldUser';
        $GLOBALS['cfg']['Server']['LogoutURL'] = 'http://phpmyadmin.net/logoutURL';

        $this->object->auth();

        $this->assertContains(
            'Location: http://phpmyadmin.net/logoutURL?PHPSESSID=',
            $GLOBALS['header'][0]
        );

        // case 3

        $GLOBALS['header'] = array();
        $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';
        $_REQUEST['old_usr'] = '';
        $GLOBALS['cfg']['Server']['LogoutURL'] = '';

        $this->object->auth();

        $this->assertContains(
            'Location: http://phpmyadmin.net/SignonURL?PHPSESSID=',
            $GLOBALS['header'][0]
        );
    }

// Vulnerability class: CWE-200
private function _notmodifiedby( $option ) {
		$user = new \User;
		$this->addWhere( 'NOT EXISTS (SELECT 1 FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id AND ' . $this->tableNames['revision_actor_temp'] . '.revactor_actor = ' . $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' LIMIT 1)' );
	}

// Vulnerability class: CWE-400
static public function addCategory($_category = null, $_admin = 1, $_order = 1) {

		if ($_category != null
			&& $_category != ''
		) {
			if ($_order < 1) {
				$_order = 1;
			}

			$ins_stmt = Database::prepare("
				INSERT INTO `" . TABLE_PANEL_TICKET_CATS . "` SET
					`name` = :name,
					`adminid` = :adminid,
					`logicalorder` = :lo"
			);
			$ins_data = array(
				'name' => $_category,
				'adminid' => $_admin,
				'lo' => $_order
			);
			Database::pexecute($ins_stmt, $ins_data);
			return true;
		}
		return false;
	}

// Vulnerability class: CWE-732
$iloc = expUnserialize($container->internal);
			if ($db->selectObject('sectionref',"module='".$iloc->mod."' AND source='".$iloc->src."'") == null) {
			// There is no sectionref for this container.  Populate sectionref
                if ($container->external != "N;") {
                    $newSecRef = new stdClass();
                    $newSecRef->module   = $iloc->mod;
                    $newSecRef->source   = $iloc->src;
                    $newSecRef->internal = '';
                    $newSecRef->refcount = 1;
//                    $newSecRef->is_original = 1;
					$eloc = expUnserialize($container->external);
//					$section = $db->selectObject('sectionref',"module='containermodule' AND source='".$eloc->src."'");
                    $section = $db->selectObject('sectionref',"module='container' AND source='".$eloc->src."'");
					if (!empty($section)) {
						$newSecRef->section = $section->id;
						$db->insertObject($newSecRef,"sectionref");
						$missing_sectionrefs[] = gt("Missing sectionref for container replaced").": ".$iloc->mod." - ".$iloc->src." - PageID #".$section->id;
					} else {
                        $db->delete('container','id="'.$container->id.'"');
                        $missing_sectionrefs[] = gt("Cant' find the container page for container").": ".$iloc->mod." - ".$iloc->src.' - '.gt('deleted');
					}
				}
			}
		}
        assign_to_template(array(
            'missing_sectionrefs'=>$missing_sectionrefs,
        ));
	}

// Vulnerability class: CWE-74
public static function fixName($name) {
        $name = preg_replace('/[^A-Za-z0-9\.]/','_',$name);
        if ($name[0] == '.')
            $name[0] = '_';
        return $name;
//        return preg_replace('/[^A-Za-z0-9\.]/', '-', $name);
    }

// Vulnerability class: CWE-74
private function _notlinksto( $option ) {
		if ( $this->parameters->getParameter( 'distinct' ) == 'strict' ) {
			$this->addGroupBy( 'page_title' );
		}
		if ( count( $option ) ) {
			$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['pagelinks'] . '.pl_from FROM ' . $this->tableNames['pagelinks'] . ' WHERE ';
			$ors = [];
			foreach ( $option as $linkGroup ) {
				foreach ( $linkGroup as $link ) {
					$_or = '(' . $this->tableNames['pagelinks'] . '.pl_namespace=' . intval( $link->getNamespace() );
					if ( strpos( $link->getDbKey(), '%' ) >= 0 ) {
						$operator = 'LIKE';
					} else {
						$operator = '=';
					}
					if ( $this->parameters->getParameter( 'ignorecase' ) ) {
						$_or .= ' AND LOWER(CAST(' . $this->tableNames['pagelinks'] . '.pl_title AS char)) ' . $operator . ' LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';
					} else {
						$_or .= ' AND ' . $this->tableNames['pagelinks'] . '.pl_title ' . $operator . ' ' . $this->DB->addQuotes( $link->getDbKey() ) . ')';
					}
					$ors[] = $_or;
				}
			}
			$where .= '(' . implode( ' OR ', $ors ) . '))';
		}
		$this->addWhere( $where );
	}

// Vulnerability class: CWE-400
public static function setArray( $arg ) {
		$numargs = count( $arg );
		if ( $numargs < 5 ) {
			return '';
		}
		$var       = trim( $arg[2] );
		$value     = $arg[3];
		$delimiter = $arg[4];
		if ( $var == '' ) {
			return '';
		}
		if ( $value == '' ) {
			self::$memoryArray[$var] = [];
			return;
		}
		if ( $delimiter == '' ) {
			self::$memoryArray[$var] = [
				$value
			];
			return;
		}
		if ( 0 !== strpos( $delimiter, '/' ) || ( strlen( $delimiter ) - 1 ) !== strrpos( $delimiter, '/' ) ) {
			$delimiter = '/\s*' . $delimiter . '\s*/';
		}
		self::$memoryArray[$var] = preg_split( $delimiter, $value );
		return "value={$value}, delimiter={$delimiter}," . count( self::$memoryArray[$var] );
	}

// Vulnerability class: CWE-400
$rndString = function ($len = 10) {
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $randomString = '';
            for ($i = 0; $i < $len; $i++) {
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
            }

            return $randomString;
        };

// Vulnerability class: CWE-330
public function actionDeleteDropdown() {
        $dropdowns = Dropdowns::model()->findAll();

        if (isset($_POST['dropdown'])) {
            if ($_POST['dropdown'] != Actions::COLORS_DROPDOWN_ID) {
                $model = Dropdowns::model()->findByPk($_POST['dropdown']);
                $model->delete();
                $this->redirect('manageDropDowns');
            }
        }

        $this->render('deleteDropdowns', array(
            'dropdowns' => $dropdowns,
        ));
    }

// Vulnerability class: CWE-20
function delete_recurring() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item->is_recurring == 1) { // need to give user options
            expHistory::set('editable', $this->params);
            assign_to_template(array(
                'checked_date' => $this->params['date_id'],
                'event'        => $item,
            ));
        } else { // Process a regular delete
            $item->delete();
        }
    }

// Vulnerability class: CWE-74
protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)
    {
        parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
        $this->createMessage(Message\PurchasedResponse::class, $gatewayMessage);
        ErrorHandling::safeExtend($this->payment, 'onCaptured', $serviceResponse);
    }

// Vulnerability class: CWE-436
function selectArraysBySql($sql) {        
        $res = @mysqli_query($this->connection, $this->injectProof($sql));
        if ($res == null)
            return array();
        $arrays = array();
        for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)
            $arrays[] = mysqli_fetch_assoc($res);
        return $arrays;
    }

// Vulnerability class: CWE-74
public function addTable( $table, $alias ) {
		if ( empty( $table ) ) {
			throw new \MWException( __METHOD__ . ': An empty table name was passed.' );
		}
		if ( empty( $alias ) || is_numeric( $alias ) ) {
			throw new \MWException( __METHOD__ . ': An empty or numeric table alias was passed.' );
		}
		if ( !isset( $this->tables[$alias] ) ) {
			$this->tables[$alias] = $this->DB->tableName( $table );
			return true;
		} else {
			return false;
		}
	}

// Vulnerability class: CWE-400
$navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
            if (!$view) {
//                unset($navs[$i]);  //FIXME this breaks jstree if we remove a parent and not the child
                $attr = new stdClass();
                $attr->class = 'hidden';  // bs3 class to hide elements
                $navs[$i]->li_attr = $attr;
            }
        }

// Vulnerability class: CWE-74
public function shouldRun(DateTime $date)
    {
        global $timedate;

        $runDate = clone $date;
        $this->handleTimeZone($runDate);

        $cron = Cron\CronExpression::factory($this->schedule);
        if (empty($this->last_run) && $cron->isDue($runDate)) {
            return true;
        }

        $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);
        
        $this->handleTimeZone($lastRun);
        $next = $cron->getNextRunDate($lastRun);

        return $next <= $runDate;
    }

// Vulnerability class: CWE-287
$rest  = $count - ( floor( $nsize ) * floor( $iGroup ) );
			if ( $rest > 0 ) {
				$nsize += 1;
			}
			$output .= "{|" . $rowColFormat . "\n|\n";
			for ( $g = 0; $g < $iGroup; $g++ ) {
				$output .= $lister->formatList( $articles, $nstart, $nsize );
				if ( $columns != 1 ) {
					$output .= "\n|valign=top|\n";
				} else {
					$output .= "\n|-\n|\n";
				}
				$nstart = $nstart + $nsize;
				// if ($rest != 0 && $g+1==$rest) $nsize -= 1;
				if ( $nstart + $nsize > $count ) {
					$nsize = $count - $nstart;
				}
			}
			$output .= "\n|}\n";
		} elseif ( $rowSize > 0 ) {

// Vulnerability class: CWE-400
public function manage()
    {
        expHistory::set('manageable',$this->params);
        $gc = new geoCountry();
        $countries = $gc->find('all');
        
        $gr = new geoRegion();             
        $regions = $gr->find('all',null,'rank asc,name asc');
        
        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions
        ));
    }

// Vulnerability class: CWE-74
public function testOnKernelResponseWithoutSession()
    {
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));
        $request = new Request();
        $request->attributes->set('_security_firewall_run', true);
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

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

        $listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());
        $listener->onKernelResponse($event);

        $this->assertTrue($session->isStarted());
    }

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

// Vulnerability class: CWE-200
public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)
    {
        if (!defined('\CURLOPT_HTTPAUTH')) {
            self::markTestSkipped('ext-curl is required for this test');
        }

        $mock = new MockHandler([
            new Response(302, ['Location' => 'http://test.com']),
            static function (RequestInterface $request, $options) {
                self::assertFalse(
                    isset($options['curl'][\CURLOPT_HTTPAUTH]),
                    'curl options still contain CURLOPT_HTTPAUTH entry'
                );
                self::assertFalse(
                    isset($options['curl'][\CURLOPT_USERPWD]),
                    'curl options still contain CURLOPT_USERPWD entry'
                );
                return new Response(200);
            }
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
    }

// Vulnerability class: CWE-200
protected function getBodyTagAttributes()
    {
        $formEngineParameters = [];
        $parameters = parent::getBodyTagAttributes();

        $formEngineParameters['fieldChangeFunc'] = $this->parameters['fieldChangeFunc'];
        $formEngineParameters['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($this->parameters['fieldChangeFunc']));

        $parameters['data-add-on-params'] .= HttpUtility::buildQueryString(['P' => $formEngineParameters], '&');

        return $parameters;
    }

// Vulnerability class: CWE-327
public function showall() {
        global $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }

// Vulnerability class: CWE-74
public function __get($var) {

        switch ($var) {
            case 'configuration_array':
                $this->configuration_array = array();
                if ($this->configuration != ''){
                    $jsonData = json_decode($this->configuration,true);
                    if ($jsonData !== null) {
                        $this->configuration_array = $jsonData;
                    } else {
                        $this->configuration_array = array();
                    }
                }
                return $this->configuration_array;
                break;

            case 'name_support':
                return $this->name_support = $this->nick;
                break;

            case 'has_photo':
                return $this->filename != '';
                break;

            case 'photo_path':
                $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;
                return $this->photo_path;
                break;

            case 'file_path_server':
                return $this->filepath . $this->filename;
                break;

            default:
                break;
        }
    }

// Vulnerability class: CWE-116
private static function thumb($source_path, $thumb_path){
		ini_set('memory_limit', '128M');

		$source_details = getimagesize($source_path);
		$source_w = $source_details[0];
		$source_h = $source_details[1];

		if($source_w > $source_h){
			$new_w = self::THUMB_W;
			$new_h = intval($source_h * $new_w / $source_w);
		} else {
			$new_h = self::THUMB_H;
			$new_w = intval($source_w * $new_h / $source_h);
		}

		switch($source_details[2]){
			case IMAGETYPE_GIF:
				$imgt = "imagegif";
				$imgcreatefrom = "imagecreatefromgif";
				break;

			case IMAGETYPE_JPEG:
				$imgt = "imagejpeg";
				$imgcreatefrom = "imagecreatefromjpeg";
				break;

			case IMAGETYPE_PNG:
				$imgt = "imagepng";
				$imgcreatefrom = "imagecreatefrompng";
				break;

			case IMAGETYPE_WEBP:
				$imgt = "imagewebp";
				$imgcreatefrom = "imagecreatefromwebp";
				break;

			case IMAGETYPE_WBMP:
				$imgt = "imagewbmp";
				$imgcreatefrom = "imagecreatefromwbmp";
				break;

			case IMAGETYPE_BMP:
				$imgt = "imagebmp";
				$imgcreatefrom = "imagecreatefrombmp";
				break;

			default:
				return false;
		}

		$old_image = $imgcreatefrom($source_path);
		$new_image = imagecreatetruecolor($new_w, $new_h);
		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_w, $new_h, $source_w, $source_h);

		$new_image = self::fix_orientation($source_path, $new_image);
		$old_image = self::fix_orientation($source_path, $old_image);

		$imgt($new_image, $thumb_path);
		$imgt($old_image, $source_path);
		return true;
	}

// Vulnerability class: CWE-20
public function execute(&$params){
        $options = &$this->config['options'];
        $notif = new Notification;
        $notif->user = $this->parseOption('user', $params);
        $notif->createdBy = 'API';
        $notif->createDate = time();
        // file_put_contents('triggerLog.txt',"\n".$notif->user,FILE_APPEND);
        // if($this->parseOption('type',$params) == 'auto') {
        // if(!isset($params['model']))
        // return false;
        // $notif->modelType = get_class($params['model']);
        // $notif->modelId = $params['model']->id;
        // $notif->type = $this->getNotifType();
        // } else {
        $notif->type = 'custom';
        $notif->text = $this->parseOption('text', $params);
        // }

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

    }

// Vulnerability class: CWE-20
public function actionAppendTag() {
        if (isset($_POST['Type'], $_POST['Id'], $_POST['Tag']) &&
                preg_match('/^[\w\d_-]+$/', $_POST['Type'])) {

            if (!class_exists($_POST['Type'])) {
                echo 'false';
                return;
            }
            $model = X2Model::model($_POST['Type'])->findByPk($_POST['Id']);
            echo $model->addTags($_POST['Tag']);
            exit;
            if ($model !== null && $model->addTags($_POST['Tag'])) {
                echo 'true';
                return;
            }
        }
        echo 'false';
    }

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

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

// Vulnerability class: CWE-74
function columnUpdate($table, $col, $val, $where=1) {         
        $res = @mysqli_query($this->connection, "UPDATE `" . $this->prefix . "$table` SET `$col`='" . $val . "' WHERE $where");
        /*if ($res == null)
            return array();
        $objects = array();
        for ($i = 0; $i < mysqli_num_rows($res); $i++)
            $objects[] = mysqli_fetch_object($res);*/
        //return $objects;
    }

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

        $data = $_POST['file'];

        $path = str_replace('..', '', $data['path']);
        $filename = str_replace('..', '', $data['name']);
        $file = FILES_DIR . DS . $path . DS . $filename;

        if (file_put_contents($file, '') !== false) {
            $mode = Plugin::getSetting('filemode', 'file_manager');
            chmod($file, octdec($mode));
        } else {
            Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }

// Vulnerability class: CWE-20
function formatValue( $name, $value ) {
		$row = $this->mCurrentRow;

		$wiki = $row->files_dbname;

		switch ( $name ) {
			case 'files_timestamp':
				$formatted = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $row->files_timestamp, $this->getUser() ) );
				break;
			case 'files_dbname':
				$formatted = $row->files_dbname;
				break;
			case 'files_url':
				$formatted = "<img src=\"{$row->files_url}\" style=\"width:135px;height:135px;\">";
				break;
			case 'files_name':
				$formatted = "<a href=\"{$row->files_page}\">{$row->files_name}</a>";
				break;
			case 'files_user':
				$formatted = "<a href=\"/wiki/Special:CentralAuth/{$row->files_user}\">{$row->files_user}</a>";
				break;
			default:
				$formatted = "Unable to format $name";
				break;
		}

		return $formatted;
	}

// Vulnerability class: CWE-20