mcanoglu/cwe-class-group huggingface dataset:
function edit_internalalias() {
        $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 configure() {
        expHistory::set('editable', $this->params);
        // little bit of trickery so that that categories can have their own configs
        
        $this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
        $this->config = $config->config;
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);
        $views = expTemplate::get_config_templates($this, $this->loc);
        
        $gc = new geoCountry();             
        $countries = $gc->find('all');
        
        $gr = new geoRegion();             
        $regions = $gr->find('all');
        
        assign_to_template(array(
            'config'=>$this->config,
            'pullable_modules'=>$pullable_modules,
            'views'=>$views,
            'countries'=>$countries,
            'regions'=>$regions,
            'title'=>static::displayname()
        ));
    }   

// Vulnerability class: CWE-74
public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $category = $this->getCategory();

        if ($this->categoryModel->remove($category['id'])) {
            $this->flash->success(t('Category removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this category.'));
        }

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

// Vulnerability class: CWE-200
foreach ($days as $event) {
                            if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))
                                break;
                            if (empty($event->eventstart))
                                $event->eventstart = $event->eventdate->date;
                            $extitem[] = $event;
                        }

// Vulnerability class: CWE-74
public function delete() {
	    global $db;
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];
	    
	    if (empty($this->params['id'])) {
	        flash('error', gt('Missing id for the comment you would like to delete'));
	        expHistory::back();
	    }
	    
	    // delete the comment
        $comment = new expComment($this->params['id']);
        $comment->delete();
        
        // delete the association too
        $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']);        
        
        // send the user back where they came from.
        expHistory::back();
	}

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

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

		$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
		$this->assertNotIXRError( $result );
		$this->assertInternalType( 'int', $result );
	}

// Vulnerability class: CWE-862
public function testAuthCheckAuthFails()
    {
        $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';
        $GLOBALS['server'] = 1;
        $_REQUEST['old_usr'] = '';
        $_REQUEST['pma_username'] = '';
        $_COOKIE['pmaServer-1'] = 'pmaServ1';
        $_COOKIE['pmaUser-1'] = 'pmaUser1';
        $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');
        $GLOBALS['cfg']['blowfish_secret'] = 'secret';
        $_SESSION['last_access_time'] = 1;
        $_SESSION['last_valid_captcha'] = true;
        $GLOBALS['cfg']['LoginCookieValidity'] = 0;
        $_SESSION['last_access_time'] = -1;
        // mock for blowfish function
        $this->object = $this->getMockBuilder('AuthenticationCookie')
            ->disableOriginalConstructor()
            ->setMethods(array('authFails'))
            ->getMock();

        $this->object->expects($this->once())
            ->method('authFails');

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

        $this->assertTrue(
            $GLOBALS['no_activity']
        );
    }

// Vulnerability class: CWE-200
public function register()
	{
		JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));

		// Get the application
		$app = JFactory::getApplication();

		// Get the form data.
		$data = $this->input->post->get('user', array(), 'array');

		// Get the model and validate the data.
		$model  = $this->getModel('Registration', 'UsersModel');

		$form = $model->getForm();

		if (!$form)
		{
			JError::raiseError(500, $model->getError());

			return false;
		}

		$return = $model->validate($form, $data);

		// Check for errors.
		if ($return === false)
		{
			// Get the validation messages.
			$errors = $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if ($errors[$i] instanceof Exception)
				{
					$app->enqueueMessage($errors[$i]->getMessage(), 'notice');

					continue;
				}

				$app->enqueueMessage($errors[$i], 'notice');
			}

			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$this->setRedirect('index.php?option=com_users&view=registration');

			return false;
		}

		// Finish the registration.
		$return = $model->register($data);

		// Check for errors.
		if ($return === false)
		{
			// Save the data in the session.
			$app->setUserState('users.registration.form.data', $data);

			// Redirect back to the registration form.
			$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());
			$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');

			return false;
		}

		// Flush the data from the session.
		$app->setUserState('users.registration.form.data', null);

		return true;
	}

// Vulnerability class: CWE-20
public static function upload_user_avatar() {
			$file       = $_FILES['lp-upload-avatar'];
			$upload_dir = learn_press_user_profile_picture_upload_dir();

			add_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );

			$result = wp_handle_upload(
				$file,
				array(
					'test_form' => false,
				)
			);

			remove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );

			if ( is_array( $result ) ) {
				$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );
				unset( $result['file'] );
			} else {
				$result = array(
					'error' => __( 'Profile picture upload failed', 'learnpress' ),
				);
			}

			learn_press_send_json( $result );
		}

// Vulnerability class: CWE-610
function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {

        if ($is_revisioned) {
            $object->revision_id++;
            //if ($table=="text") eDebug($object);
            $res = $this->insertObject($object, $table);
            //if ($table=="text") eDebug($object,true); 
            $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);
            return $res;
        }
        $sql = "UPDATE " . $this->prefix . "$table SET ";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            //if($is_revisioned && $var=='revision_id') $val++;
            if ($var{0} != '_') {
                if (is_array($val) || is_object($val)) {
                    $val = serialize($val);   
                    $sql .= "`$var`='".$val."',";
                } else {
                    $sql .= "`$var`='" . $this->escapeString($val) . "',";
                }
            }
        }
        $sql = substr($sql, 0, -1) . " WHERE ";
        if ($where != null)
            $sql .= $this->injectProof($where);
        else
            $sql .= "`" . $identifier . "`=" . $object->$identifier;
        //if ($table == 'text') eDebug($sql,true);        
        $res = (@mysqli_query($this->connection, $sql) != false);
        return $res;
    }

// Vulnerability class: CWE-74
function edit() {
        global $user;
        
        /* 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['formtitle'])) 
        {
            if (empty($this->params['id']))
            {
                $formtitle = gt("Add New Note");
            }
            else
            {
                $formtitle = gt("Edit Note");
            }
        }
        else
        {
            $formtitle = $this->params['formtitle'];
        }
        
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $simpleNote = new expSimpleNote($id);
        //FIXME here is where we might sanitize the note before displaying/editing it

        assign_to_template(array(
            'simplenote'=>$simpleNote,
            'user'=>$user,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'formtitle'=>$formtitle,
            'content_type'=>$this->params['content_type'],
            'content_id'=>$this->params['content_id'],
            'tab'=>empty($this->params['tab'])?0:$this->params['tab']
        ));
    }    

// Vulnerability class: CWE-74
public static function DragnDropReRank2() {
        global $router, $db;

        $id = $router->params['id'];
        $page = new section($id);
        $old_rank = $page->rank;
        $old_parent = $page->parent;
        $new_rank = $router->params['position'] + 1;  // rank
        $new_parent = intval($router->params['parent']);

        $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent);  // close in hole
        $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent);  // make room

        $params = array();
        $params['parent'] = $new_parent;
        $params['rank'] = $new_rank;
        $page->update($params);

        self::checkForSectionalAdmins($id);
        expSession::clearAllUsersSessionCache('navigation');
    }

// Vulnerability class: CWE-74
function productFeed() {
//        global $db;
        //check query password to avoid DDOS
        /*
            * condition  = new
            * description      
            * id - SKU      
            * link      
            * price      
            * title      
            * brand - manufacturer      
            * image link - fullsized image, up to 10, comma seperated          
            * product type - category - "Electronics > Audio > Audio Accessories MP3 Player Accessories","Health & Beauty > Healthcare > Biometric Monitors > Pedometers"      
         */
        $out = '"id","condition","description","like","price","title","brand","image link","product type"' . chr(13) . chr(10);

        $p = new product();
        $prods = $p->find('all', 'parent_id=0 AND ');
        //$prods =  $db->selectObjects('product','parent_id=0 AND');
    }

// Vulnerability class: CWE-74
$text = preg_replace($exp, '', $text);
        }

        // Primary expression to filter out tags
        $exp = '/(?:^|\s|\.)(#\w+[-\w]+\w+|#\w+)(?:$|[^\'"])/u';

        $matches = array();
        preg_match_all($exp, $text, $matches);

        return $matches;
    }

// Vulnerability class: CWE-20
public function validate() {
        global $db;
        // check for an sef url field.  If it exists make sure it's valid and not a duplicate
        //this needs to check for SEF URLS being turned on also: TODO

        if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {
            if (empty($this->sef_url)) $this->makeSefUrl();
            if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();
            if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url']         = array();
        }

        // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router
        // mapped view and src hasn't been passed in via link to the form 
        if (isset($this->id) && empty($this->location_data)) {
            $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);
            if (!empty($loc)) $this->location_data = $loc;
        }

        // run the validation as defined in the models
        if (!isset($this->validates)) return true;
        $messages = array();
        $post     = empty($_POST) ? array() : expString::sanitize($_POST);
        foreach ($this->validates as $validation=> $field) {
            foreach ($field as $key=> $value) {
                $fieldname = is_numeric($key) ? $value : $key;
                $opts      = is_numeric($key) ? array() : $value;
                $ret       = expValidator::$validation($fieldname, $this, $opts);
                if (!is_bool($ret)) {
                    $messages[] = $ret;
                    expValidator::setErrorField($fieldname);
                    unset($post[$fieldname]);
                }
            }
        }

        if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);
    }

// Vulnerability class: CWE-74
recyclebin::sendToRecycleBin($loc, $parent);
            //FIXME if we delete the module & sectionref the module completely disappears
//            if (class_exists($secref->module)) {
//                $modclass = $secref->module;
//                //FIXME: more module/controller glue code
//                if (expModules::controllerExists($modclass)) {
//                    $modclass = expModules::getControllerClassName($modclass);
//                    $mod = new $modclass($loc->src);
//                    $mod->delete_instance();
//                } else {
//                    $mod = new $modclass();
//                    $mod->deleteIn($loc);
//                }
//            }
        }
//        $db->delete('sectionref', 'section=' . $parent);
        $db->delete('section', 'parent=' . $parent);
    }

// Vulnerability class: CWE-74
$this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');
            }
        }

        static::$functions = $functions;

        // test various string lengths
        for ($length = 1; $length < 64; $length++) {
            $key1 = $this->security->generateRandomKey($length);
            $this->assertInternalType('string', $key1);
            $this->assertEquals($length, strlen($key1));
            $key2 = $this->security->generateRandomKey($length);
            $this->assertInternalType('string', $key2);
            $this->assertEquals($length, strlen($key2));
            if ($length >= 7) { // avoid random test failure, short strings are likely to collide
                $this->assertNotEquals($key1, $key2);
            }
        }

        // test for /dev/urandom, reading larger data to see if loop works properly
        $length = 1024 * 1024;
        $key1 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key1);
        $this->assertEquals($length, strlen($key1));
        $key2 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key2);
        $this->assertEquals($length, strlen($key2));
        $this->assertNotEquals($key1, $key2);

        // force /dev/urandom reading loop to deal with chunked data
        // the above test may have read everything in one run.
        // not sure if this can happen in real life but if it does
        // we should be prepared
        static::$fopen = fopen('php://memory', 'rwb');
        $length = 1024 * 1024;
        $key1 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key1);
        $this->assertEquals($length, strlen($key1));
    }

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

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

        $this->object->authCheck();

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

// Vulnerability class: CWE-200
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
                } else {
                    // escape trailing backslash
                    if ('\\' === substr($part, -1)) {
                        $part .= '\\';
                    }
                    $quote = true;
                    $escapedArgument .= $part;
                }
            }
            if ($quote) {
                $escapedArgument = '"'.$escapedArgument.'"';
            }

            return $escapedArgument;
        }

// Vulnerability class: CWE-77
private static function verifySignature($signature, $input, $key, $algo = 'HS256')
    {
        switch ($algo) {
            case'HS256':
            case'HS384':
            case'HS512':
                return JWT::sign($input, $key, $algo) === $signature;

            case 'RS256':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA256);

            case 'RS384':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA384);

            case 'RS512':
                return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA512);

            default:
                throw new Exception("Unsupported or invalid signing algorithm.");
        }
    }

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

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

// Vulnerability class: CWE-863
function XMLRPCaddImageGroupToComputerGroup($imageGroup, $computerGroup){
    $imageid = getResourceGroupID("image/$imageGroup");
    $compid = getResourceGroupID("computer/$computerGroup");
    if($imageid && $compid){
        $tmp = getUserResources(array("imageAdmin"),
                                array("manageMapping"), 1);
        $imagegroups = $tmp['image'];
        $tmp = getUserResources(array("computerAdmin"),
                                array("manageMapping"), 1);
        $computergroups = $tmp['computer'];

        if(array_key_exists($compid, $computergroups) &&
            array_key_exists($imageid, $imagegroups)){
            $mapping = getResourceMapping("image", "computer",
                                          $imageid,
                                          $compid);
            if(!array_key_exists($imageid, $mapping) ||
                !array_key_exists($compid, $mapping[$imageid])){
                $query = "INSERT INTO resourcemap "
                       .        "(resourcegroupid1, "
			           .        "resourcetypeid1, "
			           .        "resourcegroupid2, "
			           .        "resourcetypeid2) "
			           . "VALUES ($imageid, "
			           .         "13, "
			           .         "$compid, "
			           .         "12)";
                doQuery($query, 101);
            }
            return array('status' => 'success');
        } else {
            return array('status' => 'error',
                         'errorcode' => 84,
                         'errormsg' => 'cannot access computer and/or image group');
        }
    } else {
        return array('status' => 'error',
                     'errorcode' => 83,
                     'errormsg' => 'invalid resource group name');
    }
}

// Vulnerability class: CWE-20
function _setupMcrypt()
    {
        $this->_clearBuffers();
        $this->enchanged = $this->dechanged = true;

        if (!isset($this->enmcrypt)) {
            static $mcrypt_modes = array(
                self::MODE_CTR    => 'ctr',
                self::MODE_ECB    => MCRYPT_MODE_ECB,
                self::MODE_CBC    => MCRYPT_MODE_CBC,
                self::MODE_CFB    => 'ncfb',
                self::MODE_OFB    => MCRYPT_MODE_NOFB,
                self::MODE_STREAM => MCRYPT_MODE_STREAM,
            );

            $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
            $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');

            // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
            // to workaround mcrypt's broken ncfb implementation in buffered mode
            // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
            if ($this->mode == self::MODE_CFB) {
                $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
            }

        } // else should mcrypt_generic_deinit be called?

        if ($this->mode == self::MODE_CFB) {
            mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
        }
    }

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

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

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

// Vulnerability class: CWE-74
$stmt->bindValue(":$field", $domain, SQLITE3_TEXT);
		if($bindcomment) {
			$stmt->bindValue(":comment", $comment, SQLITE3_TEXT);
		}

		if($stmt->execute() && $stmt->reset())
			$num++;
		else
		{
			$stmt->close();
			if($returnnum)
				return $num;
			else
			{
				if($num === 1)
					$plural = "";
				else
					$plural = "s";
				return "Error: ".$db->lastErrorMsg().", added ".$num." domain".$plural;
			}
		}
	}

	// Close prepared statement and return number of processed rows
	$stmt->close();
	$db->exec("COMMIT;");

	if($returnnum)
		return $num;
	else
	{
		$finalcount = intval($db->querySingle($countquery));
		$modified = $finalcount - $initialcount;

		// If we add less domains than the user specified, then they wanted to add duplicates
		if($modified !== $num)
		{
			$delta = $num - $modified;
			$extra = " (skipped ".$delta." duplicates)";
		}
		else
		{
			$extra = "";
		}

		if($num === 1)
			$plural = "";
		else
			$plural = "s";
		return "Success, added ".$modified." of ".$num." domain".$plural.$extra;
	}
}

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

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

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

// Vulnerability class: CWE-200
public function editspeed() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        assign_to_template(array(
            'calculator'=>$calc
        ));
		
    }

// Vulnerability class: CWE-74
} elseif ( $rowSize > 0 ) {
			// repeat row header after n lines of output
			$nstart = 0;
			$nsize  = $rowSize;
			$count  = count( $articles );
			$output .= '{|' . $rowColFormat . "\n|\n";
			do {
				if ( $nstart + $nsize > $count ) {
					$nsize = $count - $nstart;
				}
				$output .= $lister->formatList( $articles, $nstart, $nsize );
				$output .= "\n|-\n|\n";
				$nstart = $nstart + $nsize;
				if ( $nstart >= $count ) {
					break;
				}
			} while ( true );
			$output .= "\n|}\n";
		} else {

// Vulnerability class: CWE-400
public function actionGetItems(){
		$sql = 'SELECT id, name as value FROM x2_docs 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
static public function deleteCategory($_id = 0) {

		if ($_id != 0) {

			$result_stmt = Database::prepare("
				SELECT COUNT(`id`) as `numtickets` FROM `" . TABLE_PANEL_TICKETS . "`
				WHERE `category` = :cat"
			);
			$result = Database::pexecute_first($result_stmt, array('cat' => $_id));

			if ($result['numtickets'] == "0") {
				$del_stmt = Database::prepare("
					DELETE FROM `" . TABLE_PANEL_TICKET_CATS . "` WHERE `id` = :id"
				);
				Database::pexecute($del_stmt, array('id' => $_id));
				return true;
			} else {
				return false;
			}
		}

		return false;
	}

// Vulnerability class: CWE-732
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']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];
	    
	    if (empty($this->params['id'])) {
	        flash('error', gt('No ID supplied for comment to approve'));
	        expHistory::back();
	    }
	    
	    $comment = new expComment($this->params['id']);
	    assign_to_template(array(
            'comment'=>$comment
        ));
	}

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

        $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;

        if (!$user->isAdmin() && !$isuser) {
            flash('error', gt('You do not have permissions to change this users password.'));
            expHistory::back();
        }

        if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {
            flash('error', gt('The current password you entered is not correct.'));
            expHistory::returnTo('editable');
        }
        //eDebug($user);
        $u = new user($this->params['uid']);

        $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);
        //eDebug($u, true);
        if (is_string($ret)) {
            flash('error', $ret);
            expHistory::returnTo('editable');
        } else {
            $params = array();
            $params['is_admin'] = !empty($u->is_admin);
            $params['is_acting_admin'] = !empty($u->is_acting_admin);
            $u->update($params);
        }

        if (!$isuser) {
            flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));
        } else {
            $user->password = $u->password;
            flash('message', gt('Your password has been changed.'));
        }
        expHistory::back();
    }

// Vulnerability class: CWE-74
function XMLRPCremoveImageGroupFromComputerGroup($imageGroup, $computerGroup){
    $imageid = getResourceGroupID("image/$imageGroup");
    $compid = getResourceGroupID("computer/$computerGroup");
    if($imageid && $compid){
        $tmp = getUserResources(array("imageAdmin"),
                                array("manageMapping"), 1);
        $imagegroups = $tmp['image'];
        $tmp = getUserResources(array("computerAdmin"),
                                array("manageMapping"), 1);
        $computergroups = $tmp['computer'];

        if(array_key_exists($compid, $computergroups) &&
            array_key_exists($imageid, $imagegroups)){
            $mapping = getResourceMapping("image", "computer",
                                          $imageid,
                                          $compid);
            if(array_key_exists($imageid, $mapping) &&
                array_key_exists($compid, $mapping[$imageid])){
                $query = "DELETE FROM resourcemap "
					   . "WHERE resourcegroupid1 = $imageid AND "
					   .       "resourcetypeid1 = 13 AND "
					   .       "resourcegroupid2 = $compid AND "
					   .       "resourcetypeid2 = 12";
			    doQuery($query, 101);
            }
            return array('status' => 'success');
        } else {
            return array('status' => 'error',
                         'errorcode' => 84,
                         'errormsg' => 'cannot access computer and/or image group');
        }
    } else {
        return array('status' => 'error',
                     'errorcode' => 83,
                     'errormsg' => 'invalid resource group name');
    }
}

// Vulnerability class: CWE-20
function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }

// Vulnerability class: CWE-74
public function theme_switch() {
        if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) {  // we can't write to the config.php file
            flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));
        }
    	expSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);
	    expSession::set('display_theme',$this->params['theme']);
	    $sv = isset($this->params['sv'])?$this->params['sv']:'';
	    if (strtolower($sv)=='default') {
	       $sv = '';
	    }
	    expSettings::change('THEME_STYLE_REAL',$sv);
	    expSession::set('theme_style',$sv);
	    expDatabase::install_dbtables();  // update tables to include any custom definitions in the new theme

        // $message = (MINIFY != 1) ? "Exponent is now minifying Javascript and CSS" : "Exponent is no longer minifying Javascript and CSS" ;
        // flash('message',$message);
	    $message = gt("You have selected the")." '".$this->params['theme']."' ".gt("theme");
	    if ($sv != '') {
		    $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');
	    }
	    flash('message',$message);
//        expSession::un_set('framework');
        expSession::set('force_less_compile', 1);
//        expTheme::removeSmartyCache();
        expSession::clearAllUsersSessionCache();
    	expHistory::returnTo('manageable');
    }	

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

        $this->checkPermission($project, $filter);

        if ($this->customFilterModel->remove($filter['id'])) {
            $this->flash->success(t('Custom filter removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this custom filter.'));
        }

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

// Vulnerability class: CWE-200
public function Hello($host = '') {
    $this->error = null; // so no confusion is caused

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

    // if hostname for HELO was not specified send default
    if(empty($host)) {
      // determine appropriate default to send to server
      $host = "localhost";
    }

    // Send extended hello first (RFC 2821)
    if(!$this->SendHello("EHLO", $host)) {
      if(!$this->SendHello("HELO", $host)) {
        return false;
      }
    }

    return true;
  }

// Vulnerability class: CWE-20
public function execute(&$params){
        $model = new Actions;
        $model->type = 'note';
        $model->complete = 'Yes';
        $model->associationId = $params['model']->id;
        $model->associationType = $params['model']->module;
        $model->actionDescription = $this->parseOption('comment', $params);
        $model->assignedTo = $this->parseOption('assignedTo', $params);
        $model->completedBy = $this->parseOption('assignedTo', $params);

        if(empty($model->assignedTo) && $params['model']->hasAttribute('assignedTo')){
            $model->assignedTo = $params['model']->assignedTo;
            $model->completedBy = $params['model']->assignedTo;
        }

        if($params['model']->hasAttribute('visibility'))
            $model->visibility = $params['model']->visibility;
        $model->createDate = time();
        $model->completeDate = time();

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

// Vulnerability class: CWE-20
unset($sql, $parameters, $row);
								}

								//download compressed file
								if (@sizeof($email_files) != 0) {

									//define compressed file name
										$compressed_filename = 'emails_'.date('Ymd_His').'.zip';

									//compress email files
										$command = 'zip -mj '.$_SESSION['server']['temp']['dir'].'/'.$compressed_filename.' '.implode(' ', $email_files).' 2>&1';
										exec($command, $response, $restore_errlevel);
										unset($command);

									//push download
										if (file_exists($_SESSION['server']['temp']['dir'].'/'.$compressed_filename)) {

											//open file
												session_cache_limiter('public');
												$fd = fopen($_SESSION['server']['temp']['dir'].'/'.$compressed_filename, 'rb');

											//set headers
												header("Content-Type: application/zip");
												header('Content-Disposition: attachment; filename="'.$compressed_filename.'"');
												header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
												header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
												header("Content-Length: ".filesize($_SESSION['server']['temp']['dir'].'/'.$compressed_filename));

											//output file content
												ob_clean();
												fpassthru($fd);
												fclose($fd);

											//remove compressed file
												@unlink($_SESSION['server']['temp']['dir'].'/'.$compressed_filename);
												exit;

										}

								}

							}

					}

			}

		} //method

// Vulnerability class: CWE-77
public function getAcl($node) {
      if (is_string($node)) {
         $node = $this->server->tree->getNodeForPath($node);
      }

      $acl = parent::getAcl($node);

      // Authenticated user have read access to all nodes, as node list only contains elements
      // that user can read.
      $acl[] = [
         'principal' => '{DAV:}authenticated',
         'privilege' => '{DAV:}read',
         'protected' => true,
      ];

      if ($node instanceof Calendar && \Session::haveRight(\PlanningExternalEvent::$rightname, UPDATE)) {
         // If user can update external events, then he is able to write on calendar to create new events.
         $acl[] = [
            'principal' => '{DAV:}authenticated',
            'privilege' => '{DAV:}write',
            'protected' => true,
         ];
      } else if ($node instanceof CalendarObject) {
         $item = $this->getCalendarItemForPath($node->getName());
         if ($item instanceof \CommonDBTM && $item->can($item->fields['id'], UPDATE)) {
            $acl[] = [
               'principal' => '{DAV:}authenticated',
               'privilege' => '{DAV:}write',
               'protected' => true,
            ];
         }
      }

      return $acl;
   }

// Vulnerability class: CWE-862
public function setModelAttributes(&$model,&$attributeList,&$params) {
        $data = array ();
        foreach($attributeList as &$attr) {
            if(!isset($attr['name'],$attr['value']))
                continue;

            if(null !== $field = $model->getField($attr['name'])) {
                // first do variable/expression evaluation, // then process with X2Fields::parseValue()
                $type = $field->type;
                $value = $attr['value'];
                if(is_string($value)){
                    if(strpos($value, '=') === 0){
                        $evald = X2FlowFormatter::parseFormula($value, $params);
                        if(!$evald[0])
                            return false;
                        $value = $evald[1];
                    } elseif($params !== null){

                        if(is_string($value) && isset($params['model'])){
                            $value = X2FlowFormatter::replaceVariables(
                                $value, $params['model'], $type);
                        }
                    }
                }

                $data[$attr['name']] = $value;
            }
        }
        if (!isset ($model->scenario)) 
            $model->setScenario ('X2Flow');
        $model->setX2Fields ($data);

        if ($model instanceof Actions && isset($data['complete'])) {
            switch($data['complete']) {
                case 'Yes':
                    $model->complete();
                    break;
                case 'No':
                    $model->uncomplete();
                    break;
            }
        }

        return true;
    }

// Vulnerability class: CWE-20
$rst[$key] = self::parseAndTrim($st, $unescape);
            }
            return $rst;
        }

        $str = str_replace("<br>"," ",$str);
        $str = str_replace("</br>"," ",$str);
        $str = str_replace("<br/>"," ",$str);
        $str = str_replace("<br />"," ",$str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace('"',"&quot;",$str);
        $str = str_replace("'","&#39;",$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("¼","&#188;",$str);
        $str = str_replace("½","&#189;",$str);
        $str = str_replace("¾","&#190;",$str);
		$str = str_replace("™","&trade;", $str);
		$str = trim($str);
		
        if ($unescape) {
			$str = stripcslashes($str);  
		} else {
	        $str = addslashes($str);
        }

        return $str;
    }

// Vulnerability class: CWE-74
public function update_groupdiscounts() {
	    global $db;
	    
	    if (empty($this->params['id'])) {
	        // look for existing discounts for the same group
	        $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);
	        if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));
	    }

        $gd = new groupdiscounts();
	    $gd->update($this->params);
	    expHistory::back();
	}

// Vulnerability class: CWE-74
protected function doDBUpdates() {
		$title = Title::newFromText( 'Template:Extension DPL' );

		// Make sure template does not already exist
		if ( !$title->exists() ) {
			$wikipage = WikiPage::factory( $title );
			$updater = $wikipage->newPageUpdater( User::newSystemUser( 'DynamicPageList3 extension' ) );
			$content = $wikipage->getContentHandler()->makeContent( '<noinclude>This page was automatically created.  It serves as an anchor page for all \'\'\'[[Special:WhatLinksHere/Template:Extension_DPL|invocations]]\'\'\' of [https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:DynamicPageList3 Extension:DynamicPageList3].</noinclude>', $title );
			$updater->setContent( SlotRecord::MAIN, $content );
			$comment = CommentStoreComment::newUnsavedComment( 'Autogenerated DPL\'s necessary template for content inclusion' );
			$updater->saveRevision(
				$comment,
				EDIT_NEW | EDIT_FORCE_BOT
			);
		}

		return true;
	}

// Vulnerability class: CWE-400
public function saveconfig() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        $conf = serialize($calc->parseConfig($this->params));        
        $calc->update(array('config'=>$conf));
        expHistory::back();
    }

// Vulnerability class: CWE-74
public function testAuthCheckDecryptUser()
    {
        $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';
        $GLOBALS['server'] = 1;
        $_REQUEST['old_usr'] = '';
        $_REQUEST['pma_username'] = '';
        $_COOKIE['pmaServer-1'] = 'pmaServ1';
        $_COOKIE['pmaUser-1'] = 'pmaUser1';
        $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');
        $GLOBALS['cfg']['blowfish_secret'] = 'secret';
        $_SESSION['last_access_time'] = '';
        $_SESSION['last_valid_captcha'] = true;

        // mock for blowfish function
        $this->object = $this->getMockBuilder('AuthenticationCookie')
            ->disableOriginalConstructor()
            ->setMethods(array('cookieDecrypt'))
            ->getMock();

        $this->object->expects($this->once())
            ->method('cookieDecrypt')
            ->will($this->returnValue('testBF'));

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

        $this->assertEquals(
            'testBF',
            $GLOBALS['PHP_AUTH_USER']
        );
    }

// Vulnerability class: CWE-200