	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();
	}


    public function params()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

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

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

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

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

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

Exposure of Sensitive Information to an Unauthorized Actor

The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.


                    } elseif ($var == 'off' || $var == 'false' || $var == '0') {
                        $var = false;
                    } else {

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


    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');
    }

Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')

The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.


    public function deleteCommentAction(ProjectComment $comment)
    {
        $projectId = $comment->getProject()->getId();

        try {
            $this->repository->deleteComment($comment);
        } catch (\Exception $ex) {
            $this->flashDeleteException($ex);
        }

        return $this->redirectToRoute('project_details', ['id' => $projectId]);
    }

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.


    public function autocomplete() {
        return;
        global $db;

        $model = $this->params['model'];
        $mod = new $model();
        $srchcol = explode(",",$this->params['searchoncol']);
        /*for ($i=0; $i<count($srchcol); $i++) {
            if ($i>=1) $sql .= " OR ";
            $sql .= $srchcol[$i].' LIKE \'%'.$this->params['query'].'%\'';
        }*/
        //    $sql .= ' AND parent_id=0';
        //eDebug($sql);

        //$res = $mod->find('all',$sql,'id',25);
        $sql = "select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from ".$db->prefix."product as p INNER JOIN ".$db->prefix."content_expfiles as cef ON p.id=cef.content_id INNER JOIN ".$db->prefix."expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') desc LIMIT 25";
        //$res = $db->selectObjectsBySql($sql);
        //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');

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

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')

The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.


    public static function hasChildren($i) {
        global $sections;

        if (($i + 1) >= count($sections)) return false;
        return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;
    }


    public static function canImportData() {
        return true;
    }


		public function transferPage()
		{
			//FIXME Put Import code in here.
		}


    public function isBlacklisted($ip, $username)
    {
        // first remove old expired rows
        $this->clean();
        // count
        $params = array('conditions' => array(
                        'Bruteforce.ip' => $ip,
                        'Bruteforce.username' => $username),);
        $count = $this->find('count', $params);
        if ($count >= Configure::read('SecureAuth.amount')) {
            return true;
        } else {
            return false;
        }
    }


            $attvalue = str_replace($quotchar, "", $attvalue);
            switch ($attname) {
                case 'background':
                    $styledef .= "background-image: url('$trans_image_path'); ";
                    break;
                case 'bgcolor':
                    $has_bgc_stl = true;
                    $styledef .= "background-color: $attvalue; ";
                    break;
                case 'text':
                    $has_txt_stl = true;
                    $styledef .= "color: $attvalue; ";
                    break;
            }
        }
        // Outlook defines a white bgcolor and no text color. This can lead to
        // white text on a white bg with certain themes.
        if ($has_bgc_stl && !$has_txt_stl) {
            $styledef .= "color: $text; ";
        }
        if (strlen($styledef) > 0) {
            $divattary{"style"} = "\"$styledef\"";
        }
    }
    return $divattary;
}


    public function testWithBody()
    {
        $b = Psr7\stream_for('0');
        $r = (new Response())->withBody($b);
        $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
        $this->assertSame('0', (string) $r->getBody());
    }


    public function confirm()
    {
        $project = $this->getProject();
        $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));

        $this->response->html($this->helper->layout->project('custom_filter/remove', array(
            'project' => $project,
            'filter' => $filter,
            'title' => t('Remove a custom filter')
        )));
    }

Authorization Bypass Through User-Controlled Key

The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.


public function display_sdm_upload_meta_box($post) {  // File Upload metabox
	$old_upload = get_post_meta($post->ID, 'sdm_upload', true);
	$old_value = isset($old_upload) ? $old_upload : '';

	_e('Manually enter a valid URL of the file in the text box below, or click "Select File" button to upload (or choose) the downloadable file.', 'simple-download-monitor');
	echo '

';

	echo '
';
	echo '<input id="sdm_upload" type="text" size="100" name="sdm_upload" value="' . $old_value . '" placeholder="http://..." />';
	echo '
';

	echo '
';
	echo '<input id="upload_image_button" type="button" class="button-primary" value="' . __('Select File', 'simple-download-monitor') . '" />';

	echo '

';
	_e('Steps to upload a file or choose one from your media library:', 'simple-download-monitor');
	echo '
';
	echo '
Hit the "Select File" button.
';
	echo '
Upload a new file or choose an existing one from your media library.
';
	echo '
Click the "Insert" button, this will populate the uploaded file\'s URL in the above text field.
';
	echo '
';

	wp_nonce_field('sdm_upload_box_nonce', 'sdm_upload_box_nonce_check');
    }


	public function getImageSize($path, $mime = '') {
		$size = false;
		if ($mime === '' || strtolower(substr($mime, 0, 5)) === 'image') {
			if ($work = $this->getWorkFile($path)) {
				if ($size = getimagesize($work)) {
					$size['dimensions'] = $size[0].'x'.$size[1];
				}
			}
			is_file($work) && unlink($work);
		}
		return $size;
	}


function make_fb_cs_vector($size) {
  return str_repeat("\xfe", $size) . str_repeat("\xfc", $size);
}

The product does not properly control the amount of recursion which takes place,  consuming excessive resources, such as allocated memory or the program stack.


function wp_statistics_get_site_title( $url ) {

	//Get ody Page
	$html = wp_statistics_get_html_page( $url );
	if ( $html === false ) {
		return false;
	}

	//Get Page Title
	if ( class_exists( 'DOMDocument' ) ) {
		$dom = new DOMDocument;
		@$dom->loadHTML( $html );
		$title = '';
		if ( isset( $dom ) and $dom->getElementsByTagName( 'title' )->length > 0 ) {
			$title = $dom->getElementsByTagName( 'title' )->item( '0' )->nodeValue;
		}
		return ( wp_strip_all_tags( $title ) == "" ? false : $title );
	}

	return false;
}


    public function registerBag(SessionBagInterface $bag)
    {
        if ($this->started) {
            throw new \LogicException('Cannot register a bag when the session is already started.');
        }

        $this->bags[$bag->getName()] = $bag;
    }


    public function actionGetItems(){
        $sql =
            'SELECT id, name as value
            FROM x2_templates
            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;
    }

The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.


                    $quotedParts[] = $this->quoteIdentifier(trim($part));
                }

                $this->groupBy = implode(", ", $quotedParts);
            }
        }


    public function upload() {

        // upload the file, but don't save the record yet...
        if ($this->params['resize'] != 'false') {
            $maxwidth = $this->params['max_width'];
        } else {
            $maxwidth = null;
        }
        $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);
        // since most likely this function will only get hit via flash in YUI Uploader
        // and since Flash can't pass cookies, we lose the knowledge of our $user
        // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,
        // and then assign $user->id to $file->poster so we have an audit trail for the upload

        if (is_object($file)) {
            $resized = !empty($file->resized) ? true : false;
            $user = new user($this->params['usrid']);
            $file->poster = $user->id;
            $file->posted = $file->last_accessed = time();
            $file->save();
            if (!empty($this->params['cat'])) {
                $expcat = new expCat($this->params['cat']);
                $params['expCat'][0] = $expcat->id;
                $file->update($params);
            }

            // a echo so YUI Uploader is notified of the function's completion
            if ($resized) {
                echo gt('File resized and then saved');
            } else {
                echo gt('File saved');
            }
        } else {
            echo gt('File was NOT uploaded!');
//            flash('error',gt('File was not uploaded!'));
        }
    }


. PMA_Util::getIcon('b_favorite.png')
                        . '';

                    $html .= '`' . $table['db'] . '`.`' . $table['table'] . '`';
                    $html .= '
';
                }
            }
        } else {
            $html .= '
'
                  . ($this->_tableType == 'recent'
                    ?__('There are no recent tables.')
                    :__('There are no favorite tables.'))
                  . '
';
        }


    public function confirm()
    {
        $project = $this->getProject();

        $this->response->html($this->helper->layout->project('column/remove', array(
            'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),
            'project' => $project,
        )));
    }


    public function actionGetItems(){
        // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.
        $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id 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;
    }


function current_user_get_bug_filter( $p_project_id = null ) {
	$f_filter_string = gpc_get_string( 'filter', '' );
	$t_filter = array();

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

	return $t_filter;
}


    public static function initializeNavigation() {
        $sections = section::levelTemplate(0, 0);
        return $sections;
    }


	public function init() {
		global $geo_mashup_options, $pagenow;

		// Enable this interface when the option is set and we're on a destination page
		$enabled = is_admin() &&
			$geo_mashup_options->get( 'overall', 'located_object_name', 'user' ) == 'true' &&
			preg_match( '/(user-edit|profile).php/', $pagenow );
		$enabled = apply_filters( 'geo_mashup_load_user_editor', $enabled );

		// If enabled, register all the interface elements
		if ( $enabled ) {

			// Form generation
			add_action( 'show_user_profile', array( &$this, 'print_form' ) );
			add_action( 'edit_user_profile', array( &$this, 'print_form' ) );
			// MAYBEDO: add location to registration page?

			// Form processing
			add_action( 'personal_options_update', array( &$this, 'save_user'));
			add_action( 'edit_user_profile_update', array( &$this, 'save_user'));

			$this->enqueue_form_client_items();
		}
	}


	function edit_vendor() {
		$vendor = new vendor();

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			assign_to_template(array(
                'vendor'=>$vendor
            ));
		}
	}


	protected function init() {

		if (!($this->options['host'] || $this->options['socket'])
		||  !$this->options['user']
		||  !$this->options['pass']
		||  !$this->options['db']
		||  !$this->options['path']
		||  !$this->options['files_table']) {
			return false;
		}

		$this->db = new mysqli($this->options['host'], $this->options['user'], $this->options['pass'], $this->options['db'], $this->options['port'], $this->options['socket']);
		if ($this->db->connect_error || mysqli_connect_error()) {
			return false;
		}

		$this->db->set_charset('utf8');

		if ($res = $this->db->query('SHOW TABLES')) {
			while ($row = $res->fetch_array()) {
				if ($row[0] == $this->options['files_table']) {
					$this->tbf = $this->options['files_table'];
					break;
				}
			}
		}

		if (!$this->tbf) {
			return false;
		}

		$this->updateCache($this->options['path'], $this->_stat($this->options['path']));

		return true;
	}


	private function LoadData()
	{
		$this->dataLoaded = true;

		$args = array();
		$args[] = '-s';
		$args[] = '-l';
		$args[] = $this->commitHash;
		$args[] = '--';
		$args[] = $this->path;

		$blamelines = explode("\n", $this->exe->Execute($this->project->GetPath(), GIT_BLAME, $args));

		$lastcommit = '';
		foreach ($blamelines as $line) {
			if (preg_match('/^([0-9a-fA-F]{40})(\s+.+)?\s+([0-9]+)\)/', $line, $regs)) {
				if ($regs[1] != $lastcommit) {
					$this->blame[(int)($regs[3])] = $regs[1];
					$lastcommit = $regs[1];
				}
			}
		}
	}

Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')

The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.


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

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

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

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

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

        $listener->onKernelResponse($event);
    }

When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.


    protected function getSwimlane(array $project)
    {
        $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));

        if (empty($swimlane)) {
            throw new PageNotFoundException();
        }

        if ($swimlane['project_id'] != $project['id']) {
            throw new AccessForbiddenException();
        }

        return $swimlane;
    }


    private function doCreation(array $project, array $values)
    {
        $values['project_id'] = $project['id'];
        list($valid, ) = $this->actionValidator->validateCreation($values);

        if ($valid) {
            if ($this->actionModel->create($values) !== false) {
                $this->flash->success(t('Your automatic action have been created successfully.'));
            } else {
                $this->flash->failure(t('Unable to create your automatic action.'));
            }
        }

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


    public function save(){
        $login_user = $this->checkLogin();
        $uid = $login_user['uid'] ;

        $id = I("id/d");
        $member_group_id = I("member_group_id/d");
        $cat_id = I("cat_id/d");

        $teamItemMemberInfo = D("TeamItemMember")->where(" id = '$id'  ")->find();
        $item_id = $teamItemMemberInfo['item_id'] ;
        $team_id = $teamItemMemberInfo['team_id'] ;

        if(!$this->checkItemManage($uid , $item_id)){
            $this->sendError(10303);
            return ;
        }

        $teamInfo = D("Team")->where(" id = '$team_id' and uid = '$login_user[uid]' ")->find();
        if (!$teamInfo) {
            $this->sendError(10209,"无此团队或者你无管理此团队的权限");
            return ;
        }

        if(isset($_POST['member_group_id'])){
            $return = D("TeamItemMember")->where(" id = '$id' ")->save(array("member_group_id"=>$member_group_id));
        }
        if(isset($_POST['cat_id'])){
            $return = D("TeamItemMember")->where(" id = '$id' ")->save(array("cat_id"=>$cat_id));
        }
        $this->sendResult($return);

    }


            } elseif (!empty($this->params['src'])) {
                if ($this->params['src'] == $loc->src) {
                    $this->config = $config->config;
                    break;
                }
            }
        }


    public function destroy(Appointment $appointment)
    {
        if (!auth()->user()->can("appointment-create")) {
            return response("Access denied", 403);
        }

        $deleted = $appointment->delete();
        if ($deleted) {
            return response("Success");
        }
        return response("Error", 503);
    }

The software does not perform an authorization check when an actor attempts to access a resource or perform an action.


    protected function getSubtask()
    {
        $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));

        if (empty($subtask)) {
            throw new PageNotFoundException();
        }

        return $subtask;
    }


    public function getDisplayName ($plural=true, $ofModule=true) {
        return Yii::t('users', '{user}', array(
            '{user}' => Modules::displayName($plural, 'Users'),
        ));
    }


        function RandomCompat_substr($binary_string, $start, $length = null)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_substr(): First argument should be a string'
                );
            }

            if (!is_int($start)) {
                throw new TypeError(
                    'RandomCompat_substr(): Second argument should be an integer'
                );
            }

            if ($length !== null) {
                if (!is_int($length)) {
                    throw new TypeError(
                        'RandomCompat_substr(): Third argument should be an integer, or omitted'
                    );
                }

                return substr($binary_string, $start, $length);
            }

            return substr($binary_string, $start);
        }

Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG)

The software uses a Pseudo-Random Number Generator (PRNG) but does not correctly manage seeds.


public function StartTLS() {
    $this->error = null; # to avoid confusion

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

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

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

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

    if($code != 220) {
      $this->error =
         array("error"     => "STARTTLS not accepted from server",
               "smtp_code" => $code,
               "smtp_msg"  => substr($rply,4));
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
');
      }
      return false;
    }

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

    return true;
  }


    function showallSubcategories() {
//        global $db;

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


    function search_by_model() {
        global $db, $user;

        $sql = "select DISTINCT(p.id) as id, p.title, model from " . $db->prefix . "product as p WHERE ";
        if (!($user->isAdmin())) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';

        //if first character of search is a -, then we do a wild card, else from beginning
        $this->params['query'] = expString::escape($this->params['query']);
        if ($this->params['query'][0] == '-') {
            $sql .= " p.model LIKE '%" . $this->params['query'];
        } else {
            $sql .= " p.model LIKE '" . $this->params['query'];
        }

        $sql .= "%' AND p.parent_id=0 GROUP BY p.id ";
        $sql .= "order by p.model ASC LIMIT 30";
        $res = $db->selectObjectsBySql($sql);
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


	public static function startup()
	{
		//Override the default expire time of token
		\CsrfMagic\Csrf::$expires = 259200;
		\CsrfMagic\Csrf::$callback = function ($tokens) {
			throw new \App\Exceptions\AppException('Invalid request - Response For Illegal Access', 403);
		};
		$js = 'vendor/yetiforce/csrf-magic/src/Csrf.min.js';
		if (!IS_PUBLIC_DIR) {
			$js = 'public_html/' . $js;
		}
		\CsrfMagic\Csrf::$dirSecret = __DIR__;
		\CsrfMagic\Csrf::$rewriteJs = $js;
		\CsrfMagic\Csrf::$cspToken = \App\Session::get('CSP_TOKEN');
		\CsrfMagic\Csrf::$frameBreaker = \Config\Security::$csrfFrameBreaker;
		\CsrfMagic\Csrf::$windowVerification = \Config\Security::$csrfFrameBreakerWindow;

		/*
		 * if an ajax request initiated, then if php serves content with <html> tags
		 * as a response, then unnecessarily we are injecting csrf magic javascipt
		 * in the response html at <head> and <body> using csrf_ob_handler().
		 * So, to overwride above rewriting we need following config.
		 */
		if (static::isAjax()) {
			\CsrfMagic\Csrf::$frameBreaker = false;
			\CsrfMagic\Csrf::$rewriteJs = null;
		}
	}


	function insertServiceCategorieInDB(){
		global $pearDB, $centreon;

		if (testServiceCategorieExistence($_POST["sc_name"])){
                $DBRESULT = $pearDB->query("INSERT INTO `service_categories` (`sc_name`, `sc_description`, `level`, `icon_id`, `sc_activate` )
                    VALUES ('".$_POST["sc_name"]."', '".$_POST["sc_description"]."', ".
                        (isset($_POST['sc_severity_level']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_level']):"NULL").", ".
                        (isset($_POST['sc_severity_icon']) && $_POST['sc_type'] ? $pearDB->escape($_POST['sc_severity_icon']) : "NULL").", ".
                        "'".$_POST["sc_activate"]["sc_activate"]."')");

Improper Control of Generation of Code ('Code Injection')

The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.


    function manage() {
        global $db, $router, $user;

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


    public function deleteItem(){
        $login_user = $this->checkLogin();
        $this->checkAdmin();
        $item_id = I("item_id/d");
        $return = D("Item")->soft_delete_item($item_id);
        if (!$return) {
            $this->sendError(10101);
        }else{
            $this->sendResult($return);
        }
    }


    static function displayname() {
        return "Events";
    }


            $otherPublisherName = MAX_buildName($aOtherPublisher['publisher_id'], $aOtherPublisher['name']);
            if ($aOtherPublisher['publisher_id'] != $affiliateid) {
                $form .= "<option value='" . $aOtherPublisher['publisher_id'] . "'>" . htmlspecialchars($otherPublisherName) . "</option>";
            }
        }
        $form .= "</select><input type='image' class='submit' src='" . OX::assetPath() . "/images/".$phpAds_TextDirection."/go_blue.gif'></form>";

        addPageFormTool($GLOBALS['strMoveTo'], 'iconZoneMove', $form);
    }

    //delete
    if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)
       || OA_Permission::isAccount(OA_ACCOUNT_MANAGER)
       || OA_Permission::hasPermission(OA_PERM_ZONE_DELETE)) {
        $deleteConfirm = phpAds_DelConfirm($GLOBALS['strConfirmDeleteZone']);
        addPageLinkTool($GLOBALS["strDelete"], MAX::constructUrl(MAX_URL_ADMIN, "zone-delete.php?token=" . urlencode(phpAds_SessionGetToken()) . "&affiliateid=$affiliateid&zoneid=$zoneid&returnurl=affiliate-zones.php"), "iconDelete", null, $deleteConfirm);
    }

    //shortcut
    addPageShortcut($GLOBALS['strBackToZones'], MAX::constructUrl(MAX_URL_ADMIN, "affiliate-zones.php?affiliateid=$affiliateid"), "iconBack");
    $entityString = _getEntityString($aEntities);
    addPageShortcut($GLOBALS['strZoneHistory'], MAX::constructUrl(MAX_URL_ADMIN, "stats.php?entity=zone&breakdown=history&$entityString"), 'iconStatistics');
}


    protected function assetExtensions()
    {
        return [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'ico',
            'css',
            'js',
            'woff',
            'woff2',
            'svg',
            'ttf',
            'eot',
            'json',
            'md',
            'less',
            'sass',
            'scss',
            'xml'
        ];
    }

Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.


    public function getDoctypeFromConfig($config) {
        // recommended test
        $doctype = $config->get('HTML.Doctype');
        if (!empty($doctype)) return $doctype;
        $doctype = $config->get('HTML.CustomDoctype');
        if (!empty($doctype)) return $doctype;
        // backwards-compatibility
        if ($config->get('HTML.XHTML')) {
            $doctype = 'XHTML 1.0';
        } else {
            $doctype = 'HTML 4.01';
        }
        if ($config->get('HTML.Strict')) {
            $doctype .= ' Strict';
        } else {
            $doctype .= ' Transitional';
        }
        return $doctype;
    }


    public function store(CurrencyFormRequest $request)
    {
        /** @var User $user */
        $user = auth()->user();
        $data = $request->getCurrencyData();
        if (!$this->userRepository->hasRole($user, 'owner')) {

            Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.');
            Log::channel('audit')->info('Tried to create (POST) currency without admin rights.', $data);

            return redirect($this->getPreviousUri('currencies.create.uri'));

        }

        $data['enabled'] = true;
        try {
            $currency = $this->repository->store($data);
        } catch (FireflyException $e) {
            Log::error($e->getMessage());
            Log::channel('audit')->info('Could not store (POST) currency without admin rights.', $data);
            $request->session()->flash('error', (string) trans('firefly.could_not_store_currency'));
            $currency = null;
        }
        $redirect = redirect($this->getPreviousUri('currencies.create.uri'));

        if (null !== $currency) {
            $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name]));
            Log::channel('audit')->info('Created (POST) currency.', $data);
            if (1 === (int) $request->get('create_another')) {

                $request->session()->put('currencies.create.fromStore', true);

                $redirect = redirect(route('currencies.create'))->withInput();

            }
        }

        return $redirect;
    }


    public function actionView($id){
        $model = $this->loadModel($id);
        if (!$this->checkPermissions ($model, 'view')) $this->denied ();

        // add media object to user's recent item list
        User::addRecentItem('m', $id, Yii::app()->user->getId());

        $this->render('view', array(
            'model' => $model,
        ));
    }


    public static function hasChildren($i) {
        global $sections;

        if (($i + 1) >= count($sections)) return false;
        return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;
    }


    public static function error ($vars="") {
        if( isset($vars) && $vars != "" ) {
            include(GX_PATH.'/inc/lib/Control/Error/'.$vars.'.control.php');
        }else{
            include(GX_PATH.'/inc/lib/Control/Error/404.control.php');
        }
    }


    public static function showModal($params) {

        if (!isset($params['argument']) || empty($params['argument'])) {
            return array(
                'processed' => true,
                'process_status' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/chatcommand', 'Please provide modal URL!')
            );
        }

        $paramsURL = explode(' ',$params['argument']);
        $URL = array_shift($paramsURL);

        if (is_numeric($URL)) {
            $URL =  (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . erLhcoreClassDesign::baseurldirect('form/formwidget') . '/' . $URL;
        }

The software prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.


    public static function addViews($id)
    {
        $botlist = self::botlist();
        $nom = 0;
        foreach ($botlist as $bot) {
            if (preg_match("/{$bot}/", $_SERVER['HTTP_USER_AGENT'])) {
                $nom = 1 + $nom;
            } else {
                $nom = 0;
            }
        }
        if ($nom == 0) {
            # code...
            $sql = "UPDATE `posts` SET `views` = `views`+1 WHERE `id` = '{$id}' LIMIT 1";
            $q = Db::query($sql);
        }
    }


	function manage_vendors () {
	    expHistory::set('viewable', $this->params);
		$vendor = new vendor();

		$vendors = $vendor->find('all');
		assign_to_template(array(
            'vendors'=>$vendors
        ));
	}


    public function read($sessionId)
    {
        $dbData = $this->getCollection()->findOne(array(
            $this->options['id_field'] => $sessionId,
            $this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
        ));

        if (null === $dbData) {
            return '';
        }

        if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
            return $dbData[$this->options['data_field']]->getData();
        }

        return $dbData[$this->options['data_field']]->bin;
    }


    public function delete() {
        global $db, $history;

        /* The global constants can be overriden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        if (empty($this->params['id'])) {
            flash('error', gt('Missing id for the comment you would like to delete'));
            $lastUrl = expHistory::getLast('editable');
        }

        // delete the note
        $simplenote = new expSimpleNote($this->params['id']);
        $rows = $simplenote->delete();

        // delete the assocication too
        $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);

        // send the user back where they came from.
        $lastUrl = expHistory::getLast('editable');
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    public function testGetEventsPublicProfile(){
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('testuser');

        Yii::app()->settings->historyPrivacy = null;
        $lastEventId=0;
        $lastTimestamp=0;
        $myProfile = Profile::model()->findByAttributes(array('username' => 'testuser2'));
        $events=Events::getEvents(
            $lastEventId,$lastTimestamp,null,$myProfile, false);
        $this->assertEquals (
            array_map (
                function ($event) { return $event->id; },
                Events::model ()->findAllByAttributes (array (
                    'user' => 'testuser2',
                    'visibility' => 1
                ))
            ),
            array_map (function ($event) { return $event->id; }, $events['events']));

        TestingAuxLib::restoreX2WebUser ();
    }


    function process_subsections($parent_section, $subtpl) {
        global $db, $router;

        $section              = new stdClass();
        $section->parent      = $parent_section->id;
        $section->name        = $subtpl->name;
        $section->sef_name    = $router->encode($section->name);
        $section->subtheme    = $subtpl->subtheme;
        $section->active      = $subtpl->active;
        $section->public      = $subtpl->public;
        $section->rank        = $subtpl->rank;
        $section->page_title  = $subtpl->page_title;
        $section->keywords    = $subtpl->keywords;
        $section->description = $subtpl->description;
        $section->id          = $db->insertObject($section, 'section');
        self::process_section($section, $subtpl);
    }


            $list[] = "$name = <i>" . $this->getClass($obj, 'AttrDef_') . '</i>';
        }
        return $this->listify($list);
    }


    public function __invoke(Request $request)
    {
        $this->authorize('manage modules');

        $response = ModuleInstaller::upload($request);

        return response()->json($response);
    }

The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.


    public static function makeConfig ($file) {
        $config = "<?php if(!defined('GX_LIB')) die(\"Direct Access Not Allowed!\");
/**
* GeniXCMS - Content Management System
*
* PHP Based Content Management System and Framework
*
* @package GeniXCMS
* @since 0.0.1 build date 20140925
* @version 0.0.1
* @link https://github.com/semplon/GeniXCMS
* @author Puguh Wijayanto (www.metalgenix.com)
* @copyright 2014-2015 Puguh Wijayanto
* @license http://www.opensource.org/licenses/mit-license.php MIT
*
*/error_reporting(0);

// DB CONFIG
define('DB_HOST', '".Session::val('dbhost')."');
define('DB_NAME', '".Session::val('dbname')."');
define('DB_PASS', '".Session::val('dbpass')."');
define('DB_USER', '".Session::val('dbuser')."');
define('DB_DRIVER', 'mysqli');

define('THEME', 'default');
define('GX_LANG', 'english');
define('SMART_URL', false); //set 'true' if you want use SMART URL (SEO Friendly URL)
define('GX_URL_PREFIX', '.html');

// DON't REMOVE or EDIT THIS.
define('SECURITY', '".Typo::getToken(200)."'); // for security purpose, will be used for creating password

        ";
        try{
            $f = fopen($file, "w");
            $c = fwrite($f, $config);
            fclose($f);
        }catch (Exception $e) {
            echo $e->getMessage();
        }

        return $config;
    }


    private function runCallback() {
        foreach ($this->records as &$record) {
            if (isset($record->ref_type)) {
                $refType = $record->ref_type;
                if (class_exists($record->ref_type)) {
                    $type = new $refType();
                    $classinfo = new ReflectionClass($type);
                    if ($classinfo->hasMethod('paginationCallback')) {
                        $item = new $type($record->original_id);
                        $item->paginationCallback($record);
                    }
                }
            }
        }
    }


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

        assign_to_template(array(
            'modules' => $modules,
        ));
    }


    public function getAllowedElements($config) {
        $this->init($config);
        return $this->fake_elements;
    }


	function RemoveXSSchars(&$val)
	{
		static $patterns = NULL;
		static $replacements = NULL;
		$val_before = $val;
		$found = true;

		if ( $patterns == NULL ) {
			$patterns = array();
			$replacements = array();

			// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are
			// allowed this prevents some character re-spacing such as <java\0script>
			// note that you have to handle splits with \n, \r, and \t later since they
			// *are* allowed in some inputs
			$patterns[] = '/([\x00-\x08\x0b-\x0c\x0e-\x19])/';
			$replacements[] = '';

			// straight replacements, the user should never need these since they're
			// normal characters this prevents like
			// <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
			// Calculate the search and replace patterns only once
			$search = 'abcdefghijklmnopqrstuvwxyz';
			$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$search .= '1234567890!@#$%^&*()';
			$search .= '~`";:?+/={}[]-_|\'\\';
			for ($i = 0, $istrlen_search = strlen($search); $i < $istrlen_search; $i++) {
				// ;? matches the ;, which is optional
				// 0{0,8} matches any padded zeros,
				// which are optional and go up to 8 chars
				// &#x0040 @ search for the hex values
				$patterns[] = '/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i';
				$replacements[] = $search[$i];
				// &#00064 @ 0{0,8} matches '0' zero to eight times
				// with a ;
				$patterns[] = '/(&#0{0,8}'.ord($search[$i]).';?)/';
				$replacements[] = $search[$i];
			}
		}
		$val = preg_replace($patterns, $replacements, $val);
		if ($val_before == $val) {
			// no replacements were made, so exit the loop
			$found = false;
		}
		return $found;
	}


	public function remove_placeholder_escape( $query ) {
		return str_replace( $this->placeholder_escape(), '%', $query );
	}


    static function author() {
        return "Dave Leffler";
    }


    public function checkHTTP($link, $get_body = false)
    {
        if (! function_exists('curl_init')) {
            return null;
        }
        $handle = curl_init($link);
        if ($handle === false) {
            return null;
        }
        PMA_Util::configureCurl($handle);
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 5);
        curl_setopt($handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        if (! defined('TESTSUITE')) {
            session_write_close();
        }
        $data = @curl_exec($handle);
        if (! defined('TESTSUITE')) {
            ini_set('session.use_only_cookies', '0');
            ini_set('session.use_cookies', '0');
            ini_set('session.use_trans_sid', '0');
            ini_set('session.cache_limiter', 'nocache');
            session_start();
        }
        if ($data === false) {
            return null;
        }
        $http_status = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        if ($http_status == 200) {
            return $get_body ? $data : true;
        }

        if ($http_status == 404) {
            return false;
        }
        return null;
    }


function singleQuoteReplace($param1 = false, $param2 = false, $param3)
{
    return str_replace("'", "''", str_replace("\'", "'", $param3));
}


    public function nonOkErrorStatus()
    {
        return [
            'UPLOAD_ERR_INI_SIZE'   => [ UPLOAD_ERR_INI_SIZE ],
            'UPLOAD_ERR_FORM_SIZE'  => [ UPLOAD_ERR_FORM_SIZE ],
            'UPLOAD_ERR_PARTIAL'    => [ UPLOAD_ERR_PARTIAL ],
            'UPLOAD_ERR_NO_FILE'    => [ UPLOAD_ERR_NO_FILE ],
            'UPLOAD_ERR_NO_TMP_DIR' => [ UPLOAD_ERR_NO_TMP_DIR ],
            'UPLOAD_ERR_CANT_WRITE' => [ UPLOAD_ERR_CANT_WRITE ],
            'UPLOAD_ERR_EXTENSION'  => [ UPLOAD_ERR_EXTENSION ],
        ];
    }


    protected function fixupImportedAttributes($modelName, X2Model &$model) {
        if ($modelName === 'Contacts' || $modelName === 'X2Leads')
            $this->fixupImportedContactName ($model);

        if ($modelName === 'Actions' && isset($model->associationType))
            $this->reconstructImportedActionAssoc($model);

        // Set visibility to Public by default if unset by import
        if ($model->hasAttribute('visibility') && is_null($model->visibility))
            $model->visibility = 1;
        // If date fields were provided, do not create new values for them
        if (!empty($model->createDate) || !empty($model->lastUpdated) ||
                !empty($model->lastActivity)) {
            $now = time();
            if (empty($model->createDate))
                $model->createDate = $now;
            if (empty($model->lastUpdated))
                $model->lastUpdated = $now;
            if ($model->hasAttribute('lastActivity') && empty($model->lastActivity))
                $model->lastActivity = $now;
        }
        if($_SESSION['leadRouting'] == 1){
            $assignee = $this->getNextAssignee();
            if($assignee == "Anyone")
                $assignee = "";
            $model->assignedTo = $assignee;
        }
        // Loop through our override and set the manual data
        foreach($_SESSION['override'] as $attr => $val){
            $model->$attr = $val;
        }
    }


    public function close()
    {
        $this->setError('');
        $this->server_caps = null;
        $this->helo_rply = null;
        if (is_resource($this->smtp_conn)) {
            // close the connection and cleanup
            fclose($this->smtp_conn);
            $this->smtp_conn = null; //Makes for cleaner serialization
            $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
        }
    }


            } elseif (!empty($this->params['src'])) {
                if ($this->params['src'] == $loc->src) {
                    $this->config = $config->config;
                    break;
                }
            }
        }


    public function onRefresh()
    {
        $value = post($this->getFieldName());
        $previewHtml = $this->safe
            ? Markdown::parseSafe($value)
            : Markdown::parse($value);

        if ($this->shouldCleanHtml()) {
            $previewHtml = Html::clean($previewHtml);
        }

        return [
            'preview' => $previewHtml
        ];
    }


    public static function delete($id)
    {
        return Categories::delete($id);
    }


    public function setup($config) {
        $a = $this->addElement(
            'a', 'Inline', 'Inline', 'Common',
            array(
                // 'accesskey' => 'Character',
                // 'charset' => 'Charset',
                'href' => 'URI',
                // 'hreflang' => 'LanguageCode',
                'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'),
                'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'),
                // 'tabindex' => 'Number',
                // 'type' => 'ContentType',
            )
        );
        $a->formatting = true;
        $a->excludes = array('a' => true);
    }


    public function testHostIsNormalizedToLowercase()
    {
        $uri = new Uri('//eXaMpLe.CoM');

        $this->assertSame('example.com', $uri->getHost());
        $this->assertSame('//example.com', (string) $uri);

        $uri = (new Uri())->withHost('eXaMpLe.CoM');

        $this->assertSame('example.com', $uri->getHost());
        $this->assertSame('//example.com', (string) $uri);
    }


function draw_cdef_preview($cdef_id) {
	?>

cdef=<?php print html_escape(get_cdef($cdef_id, true));?>

	<?php
}


    public function setContainer($container)
    {
        $this->container = $container;
        $container->setType('ctBanner');
    }


    public function update() {

        //populate the alt tag field if the user didn't
        if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];

        // call expController update to save the image
        parent::update();
    }


    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'])));
    }


    public function resetRemoteAuthKey($id)
    {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException(__('This endpoint expects POST requests.'));
        }
        $result = $this->Server->resetRemoteAuthkey($id);
        if ($result !== true) {
            if (!$this->_isRest()) {
                $this->Flash->error($result);
                $this->redirect(array('action' => 'index'));
            } else {
                return $this->RestResponse->saveFailResponse('Servers', 'resetRemoteAuthKey', $id, $message, $this->response->type());
            }
        } else {
            $message = __('API key updated.');
            if (!$this->_isRest()) {
                $this->Flash->success($message);
                $this->redirect(array('action' => 'index'));
            } else {
                return $this->RestResponse->saveSuccessResponse('Servers', 'resetRemoteAuthKey', $message, $this->response->type());
            }
        }
    }

The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.


    public function testRaisesExceptionOnInvalidStreamOrFile($streamOrFile)
    {
        $this->setExpectedException('InvalidArgumentException');

        new UploadedFile($streamOrFile, 0, UPLOAD_ERR_OK);
    }


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


$logo = '";
        } else {
            $logo = '';
        }

        return $logo;
    }


function XMLRPCtest($string) {
	$string = processInputData($string, ARG_STRING);
	return array('status' => 'success',
	             'message' => 'RPC call worked successfully',
	             'string' => $string);
}


    public function session() {
        // Test if logged in, log in if not, log in.
        try {
            $this->assertElementPresent('css=ul#user-menu');
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            /* If this isn't the first time we've logged in, we have a problem;
             * the user should have been logged in throughout the life of the
             * test case class. Append t
             */
            if (!$this->firstLogin)
                array_push($this->verificationErrors, $e->toString());
            $this->firstLogin = false;
            $this->login();
            return 0;
        }
        try {
            $this->assertCorrectUser();
        } catch (PHPUnit_Framework_AssertionFailedError $e) {
            // The browser is logged in but not as the correct user.
            $this->logout();
            $this->login();
            $this->firstLogin = false;
            return 0;
        }
        // Indicator of whether the session was already initialized properly
        return 1;
    }


        foreach ($nodes as $node) {
            if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
                if ($node->active == 1) {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
                } else {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
                }
                $ar[$node->id] = $text;
                foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
                    $ar[$id] = $text;
                }
            }
        }


	function show_vendor () {
		$vendor = new vendor();

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			$vendor_title = $vendor->title;
			$state = new geoRegion($vendor->state);
			$vendor->state = $state->name;
			//Removed unnecessary fields
			unset(
                $vendor->title,
                $vendor->table,
                $vendor->tablename,
                $vendor->classname,
                $vendor->identifier
            );

			assign_to_template(array(
                'vendor_title' => $vendor_title,
                'vendor'=>$vendor
            ));
		}
	}


    public static function autoload($class) {
        $file = HTMLPurifier_Bootstrap::getPath($class);
        if (!$file) return false;
        // Technically speaking, it should be ok and more efficient to
        // just do 'require', but Antonio Parraga reports that with
        // Zend extensions such as Zend debugger and APC, this invariant
        // may be broken.  Since we have efficient alternatives, pay
        // the cost here and avoid the bug.
        require_once HTMLPURIFIER_PREFIX . '/' . $file;
        return true;
    }


            $count += $db->dropTable($basename);
        }

        flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
        expHistory::back();
    }


    public static function getParent($parent='', $menuid = ''){
        if(isset($menuid)){
            $where = " AND `menuid` = '{$menuid}'";
        }else{
            $where = '';
        }
        $sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
        $menu = Db::result($sql);
        return $menu;
    }


function updateBasicSettings(PDFStructure &$structure) {
	// set headline
	if (isset($_POST['headline'])) {
		$structure->setTitle(str_replace('<', '', str_replace('>', '', $_POST['headline'])));
	}
	// set logo
	if (isset($_POST['logoFile'])) {
		$structure->setLogo($_POST['logoFile']);
	}
	// set folding marks
	if (isset($_POST['foldingmarks'])) {
		$structure->setFoldingMarks($_POST['foldingmarks']);
	}
}


    public static function isPublic($s) {
        if ($s == null) {
            return false;
        }
        while ($s->public && $s->parent > 0) {
            $s = new section($s->parent);
        }
        $lineage = (($s->public) ? 1 : 0);
        return $lineage;
    }


            $regx = str_replace('/', '\/', $k);
            // echo $regx."\n";
            if (preg_match('/^'.$regx.'$/Usi', $uri, $m)) {
                $result = [$v, $m];

                return $result;
            }
        }
    }


DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return"draw.io"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader("Content-Language","da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(c)};


  this.complete = function (result) {
    if (resultsBuffer.length) {
      socket.emit('result', resultsBuffer)
      resultsBuffer = []
    }

    socket.emit('complete', result || {})
    if (this.config.clearContext) {
      navigateContextTo('about:blank')
    } else {
      self.updater.updateTestStatus('complete')
    }
    if (returnUrl) {
      if (!/^https?:\/\//.test(returnUrl)) {
        throw new Error(
          'Security: Navigation to '.concat(
            returnUrl,
            ' was blocked to prevent malicious exploits.'
          )
        )
      }
      location.href = returnUrl
    }
  }

URL Redirection to Untrusted Site ('Open Redirect')

A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + _.escape(foreignSource) + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


OAuthServer.prototype.stop = function(callback) {
    this.server.close(callback);
};

Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')

The software constructs a string for a command to executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string.


  _mdBlockQuote(str) {
    return str.replace(/^>\s(.*)/, (all, quote) => '<blockquote>' + quote + '</blockquote>');
  }


  Modal.prototype.enforceFocus = function () {
    $(document)
      .off('focusin.bs.modal') // guard against infinite focus loop
      .on('focusin.bs.modal', $.proxy(function (e) {
        if (document !== e.target &&
            this.$element[0] !== e.target &&
            !this.$element.has(e.target).length) {
          this.$element.trigger('focus')
        }
      }, this))
  }


function _c(a,b,c) {var d={mm:"munutenn",MM:"miz",dd:"devezh"};return a+" "+cd(d[c],a)}function ad(a) {switch(bd(a)) {case 1:case 3:case 4:case 5:case 9:return a+" bloaz";default:return a+" vloaz"}}function bd(a) {return a>9?bd(a%10):a}function cd(a,b) {return 2===b?dd(a):a}function dd(a) {var b={m:"v",b:"v",d:"z"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)}


function addToolTipToTableCell(value) {
  if (value) {
    return `<span class="js-tooltip" data-bs-toggle="tooltip" data-bs-placement="left" title="${value}">${value}</span>`
  }
  return ''
}

Improper Neutralization of Formula Elements in a CSV File

The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.


Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state.


                        PMA_ajaxShowMessage($('<div />',{'class':'error','html':PMA_messages.strRequestFailed+' ( '+escapeHtml(AJAX.xhr.statusText)+' )'}));
                        AJAX.active = false;
                        AJAX.xhr = null;
                    }
                }
            });


The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.


  return function self(name, val) {
    if (!name) return new RegExp(regex, opt);
    val = val.source || val;
    val = val.replace(/(^|[^\[])\^/g, '$1');
    regex = regex.replace(name, val);
    return self;
  };


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),
m;for(m in urlParams)0>mxUtils.indexOf(g,m)&&(d=0==f?d+"?":d+"&",null!=urlParams[m]&&(d+=m+"="+urlParams[m],f++))}return d};EditorUi.prototype.showLinkDialog=function(d,f,g,m,q){d=new LinkDialog(this,d,f,g,!0,m,q);this.showDialog(d.container,560,130,!0,!0);d.init()};EditorUi.prototype.getServiceCount=function(d){var f=1;null==this.drive&&"function"!==typeof window.DriveClient||f++;null==this.dropbox&&"function"!==typeof window.DropboxClient||f++;null==this.oneDrive&&"function"!==typeof window.OneDriveClient||


    $scope.removeAllNodes = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(
            function() { // success
              growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');
              var req = $scope.requisitionsData.getRequisition(foreignSource);
              req.reset();
            },
            $scope.errorHandler
          );
        }
      });
    };


    main.subscribeObjects = function (patterns) {
        if (!patterns) return;
        if (typeof patterns === 'object') {
            for (let s = 0; s < patterns.length; s++) {
                main.subscribesObjects[patterns[s]] = main.subscribesObjects[patterns[s]] || 0;
                main.subscribesObjects[patterns[s]]++;
                if (main.subscribesObjects[patterns[s]] === 1) {
                    main.socket.emit('subscribeObjects', patterns[s]);
                }
            }
        } else {
            main.subscribesObjects[patterns] = main.subscribesObjects[patterns] || 0;
            main.subscribesObjects[patterns]++;
            if (main.subscribesObjects[patterns] === 1) {
                main.socket.emit('subscribeObjects', patterns);
            }
        }
    };


Toolbar.prototype.setFontSize = function(value)
{
	if (this.sizeMenu != null)
	{
		this.sizeMenu.innerHTML = '';
		var div = document.createElement('div');
		div.style.display = 'inline-block';
		div.style.overflow = 'hidden';
		div.style.textOverflow = 'ellipsis';
		div.style.maxWidth = '24px';
		mxUtils.write(div, value);
		this.sizeMenu.appendChild(div);

		this.appendDropDownImageHtml(this.sizeMenu);
	}
};


function formcheck_Timetable_course_F3(this_DET) {
  var this_button_id = this_DET.id;

  var frmvalidator = new Validator("F3", this_button_id);

  var course_id = document.getElementById("course_id_div").value;
  if (course_id == "new") {
    frmvalidator.addValidation(
      "tables[courses][new][TITLE]",
      "req",
      "Please enter the course title "
    );
    frmvalidator.addValidation(
      "tables[courses][new][TITLE]",
      "maxlen=50",
      "Max length for course title is 50 characters "
    );

    frmvalidator.addValidation(
      "tables[courses][new][SHORT_NAME]",
      "maxlen=25",
      "Max length for short name is 25 characters "
    );
  } else {
    frmvalidator.addValidation(
      "inputtables[courses][" + course_id + "][TITLE]",
      "req",
      "Please enter the course title "
    );
    frmvalidator.addValidation(
      "inputtables[courses][" + course_id + "][TITLE]",
      "maxlen=50",
      "Max length for course title is 50 characters"
    );

    frmvalidator.addValidation(
      "inputtables[courses][" + course_id + "][SHORT_NAME]",
      "maxlen=25",
      "Max length for short name is 25 characters"
    );
  }
}


  key.verify = function(digest, signature, scheme) {
    if(typeof scheme === 'string') {
      scheme = scheme.toUpperCase();
    } else if(scheme === undefined) {
      scheme = 'RSASSA-PKCS1-V1_5';
    }

    if(scheme === 'RSASSA-PKCS1-V1_5') {
      scheme = {
        verify: function(digest, d) {
          // remove padding
          d = _decodePkcs1_v1_5(d, key, true);
          // d is ASN.1 BER-encoded DigestInfo
          var obj = asn1.fromDer(d);
          // compare the given digest to the decrypted one
          return digest === obj.value[1].value;
        }
      };
    } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
      scheme = {
        verify: function(digest, d) {
          // remove padding
          d = _decodePkcs1_v1_5(d, key, true);
          return digest === d;
        }
      };
    }

    // do rsa decryption w/o any decoding, then verify -- which does decoding
    var d = pki.rsa.decrypt(signature, key, true, false);
    return scheme.verify(digest, d, key.n.bitLength());
  };

Improper Verification of Cryptographic Signature

The software does not verify, or incorrectly verifies, the cryptographic signature for data.


Runner.prototype.hooks = function(name, suites, fn) {
  var self = this
    , orig = this.suite;

  function next(suite) {
    self.suite = suite;

    if (!suite) {
      self.suite = orig;
      return fn();
    }

    self.hook(name, function(err) {
      if (err) {
        var errSuite = self.suite;
        self.suite = orig;
        return fn(err, errSuite);
      }

      next(suites.pop());
    });
  }

  next(suites.pop());
};


    $scope.refresh = function(requisition) {
      RequisitionsService.startTiming();
      RequisitionsService.updateDeployedStatsForRequisition(requisition).then(
        function() { // success
          growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');
        },
        $scope.errorHandler
      );
    };


html: function (token, attrs, content) {
			var size = $.inArray(attrs.defaultattr, mybbCmd.fsStr) + 1;
			if (!isNaN(attrs.defaultattr)) {
				size = attrs.defaultattr;
				if (size > 7)
					size = 7;
				if (size < 1)
					size = 1;
			}
			if (size < 0) {
				size = 0;
			}
			return '' + content + '';
		}


function isPrototypePolluted(key) {
  return ['__proto__', 'constructor', 'prototype'].includes(key)
}

Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')

The software receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.


function startingTag(element) {
	element = jqLite(element).clone();
	try {
		// turns out IE does not let you set .html() on elements which
		// are not allowed to have children. So we just ignore it.
		element.empty();
	} catch (e) {
		/* empty */
	}
	var elemHtml = jqLite("<div>")
		.append(element)
		.html();
	try {
		return element[0].nodeType === NODE_TYPE_TEXT
			? lowercase(elemHtml)
			: elemHtml
					.match(/^(<[^>]+>)/)[1]
					.replace(/^<([\w\-]+)/, function(match, nodeName) {
						return "<" + lowercase(nodeName);
					});
	} catch (e) {
		return lowercase(elemHtml);
	}
}

The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.


			unselectAll = function() {
				if (selectedFiles.length) {
					selectLock = false;
					selectedFiles = [];
					cwd.find('[id].'+clSelected).trigger(evtUnselect);
					trigger();
				}
			},


function remove_cluster(ids) {
  var data = {};
  $.each(ids, function(_, cluster) {
    data[ "clusterid-" + cluster] = true;
  });
  $.ajax({
    type: 'POST',
    url: '/manage/removecluster',
    data: data,
    timeout: pcs_timeout,
    success: function () {
      $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")});
      Pcs.update();
    },
    error: function (xhr, status, error) {
      alert("Unable to remove cluster: " + res + " ("+error+")");
      $("#dialog_verify_remove_clusters.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")});
    }
  });
}

Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions.


refreshTabs : function(){
        "use strict";
        window.console.log('refreshTabs');
        var self = this;
        var pltabs = '';
        for(var i=0; i<this.managedPlaylists.length; i++){
            var pl = this.managedPlaylists[i];

            var isactive = ''
            if(pl.id == this.editingPlaylist){
                isactive = ' class="active" ';
            } else {
                isactive = ' class="playlist-tab-inactive" ';
            }
            pltabs += '
';

            var isplaying = '';
            if(pl.id == this.playingPlaylist){
                isplaying += '▶';
            }

            var isunsaved = '';
            if(!pl.saved && pl.reason_open !== 'queue'){
                isunsaved += ' (unsaved)';
            }

            // fix for CVE-2015-8310
            var escaped_playlist_name = $("
").text(pl.name).html();
            pltabs += ''+isplaying+' '+escaped_playlist_name + isunsaved;
            if(pl.closable){
                pltabs += '×';
            }
            pltabs += '
';
        }
        pltabs += '
+
';
        $(self.cssSelectorPlaylistChooser+' ul').empty()
        $(self.cssSelectorPlaylistChooser+' ul').append(pltabs);
    },


(function(a){var e={};CKEDITOR.on("reset",function(){e={}});a.equals=function(a){try{return a&&a.$===this.$}catch(c){return false}};a.setCustomData=function(a,c){var d=this.getUniqueId();(e[d]||(e[d]={}))[a]=c;return this};a.getCustomData=function(a){var c=this.$["data-cke-expando"];return(c=c&&e[c])&&a in c?c[a]:null};a.removeCustomData=function(a){var c=this.$["data-cke-expando"],c=c&&e[c],d,g;if(c){d=c[a];g=a in c;delete c[a]}return g?d:null};a.clearCustomData=function(){this.removeAllListeners();


(function($,e,t) {"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function() {if (!n[f]&&this[s]) {return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if (i.length===1) {a=t;h()}},teardown:function() {if (!n[f]&&this[s]) {return false}var e=$(this);for(var t=i.length-1;t>=0;t--) {if (i[t]==this) {i.splice(t,1);break}}e.removeData(m);if (!i.length) {if (r) {cancelAnimationFrame(a)} else {clearTimeout(a)}a=null}},add:function(e) {if (!n[f]&&this[s]) {return false}var i;function a(e,n,a) {var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if ($.isFunction(e)) {i=e;return a} else {i=e.handler;e.handler=a}}};function h(t) {if (r===true) {r=t||1}for(var s=i.length-1;s>=0;s--) {var l=$(i[s]);if (l[0]==e||l.is(":visible")) {var f=l.width(),c=l.height(),d=l.data(m);if (d&&(f!==d.w||c!==d.h)) {l.trigger(u,[d.w=f,d.h=c]);r=t||true}} else {d=l.data(m);d.w=0;d.h=0}}if (a!==null) {if (r&&(t==null||t-r<1e3)) {a=e.requestAnimationFrame(h)} else {a=setTimeout(h,n[o]);r=false}}}if (!e.requestAnimationFrame) {e.requestAnimationFrame=function() {return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i) {return e.setTimeout(function() {t((new Date).getTime())},n[l])}}()}if (!e.cancelAnimationFrame) {e.cancelAnimationFrame=function() {return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);


	onPaste: function (event) {
		const self = this,
			allowedTypes = 'image/jpeg|image/png|image/gif',
			dataTransfer = event.data.dataTransfer,
			editor = event.editor,
			count = dataTransfer.getFilesCount();
		for (let index = 0; index < count; index++) {
			let file = dataTransfer.getFile(index);
			if (file.type.match(allowedTypes)) {
				self
					.validateFile(file, editor)
					.done(function (base) {
						let image,
							selectedImg = editor.getSelection();
						if (selectedImg) selectedImg = selectedImg.getSelectedElement();
						if (!selectedImg || selectedImg.getName() !== 'img') selectedImg = null;
						if (selectedImg) {
							image = selectedImg;
						} else {
							image = editor.document.createElement('img');
						}
						image.setAttribute('src', base);
						if (!selectedImg) editor.insertElement(image);
					})
					.fail(function (error) {
						editor.showNotification(error, 'warning');
					});
			} else {
				editor.showNotification(
					app.vtranslate('JS_INVALID_FILE_TYPE') +
						'<br>' +
						app.vtranslate('JS_AVAILABLE_FILE_TYPES') +
						': ' +
						allowedTypes.replace(/\|/g, ', '),
					'warning'
				);
			}
		}
	},

Unrestricted Upload of File with Dangerous Type

The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.


        function sendMessage(callback) {
            pool.send(
                {
                    data: {},
                    message: new MockBuilder(
                        {
                            from: 'test@valid.sender',
                            to: 'test@valid.recipient'
                        },
                        message
                    )
                },
                function (err) {
                    expect(err).to.not.exist;
                    callback();
                }
            );
        }

        let total = 100;
        let returned = 0;
        let cb = function () {
            let sent = 0;

            if (++returned === total) {
                expect(pool._connections.length).to.be.above(1);
                pool._connections.forEach(function (conn) {
                    expect(conn.messages).to.be.above(1);
                    sent += conn.messages;
                });

                expect(sent).to.be.equal(total);

                pool.close();
                return done();
            }
        };
        for (let i = 0; i < total; i++) {
            sendMessage(cb);
        }
    });


Runner.prototype.grep = function(re, invert){
  debug('grep %s', re);
  this._grep = re;
  this._invert = invert;
  this.total = this.grepTotal(this.suite);
  return this;
};


The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.


getCreateHtml: function (address) {
            address = this.getHelper().escapeString(address);

            var html = '' +
                '<button class="dropdown-toggle btn btn-link btn-sm" data-toggle="dropdown">' +
                    '' +
                '</button>' +
                '
' +
            '';

            if (this.getAcl().check('Contact', 'create')) {
                html += '
'+this.translate('Create Contact', 'labels', 'Email')+'
';
            }
            if (this.getAcl().check('Lead', 'create')) {
                html += '
'+this.translate('Create Lead', 'labels', 'Email')+'
';
            }
            if (this.getAcl().check('Contact', 'edit')) {
                html += '
'+this.translate('Add to Contact', 'labels', 'Email')+'
';
            }
            if (this.getAcl().check('Lead', 'edit')) {
                html += '
'+this.translate('Add to Lead', 'labels', 'Email')+'
';
            }

            html += '
' +
            '';

            return html;
        },


    $scope.provision = function() {
      $scope.isSaving = true;
      growl.info('The node ' + _.escape($scope.node.nodeLabel) + ' is being added to requisition ' + _.escape($scope.node.foreignSource) + '. Please wait...');
      var successMessage = 'The node ' + _.escape($scope.node.nodeLabel) + ' has been added to requisition ' + _.escape($scope.node.foreignSource);
      RequisitionsService.quickAddNode($scope.node).then(
        function() { // success
          $scope.reset();
          bootbox.dialog({
            message: successMessage,
            title: 'Success',
            buttons: {
              main: {
                label: 'Ok',
                className: 'btn-secondary'
              }
            }
          });
        },
        $scope.errorHandler
      );
    };


    __add_options_to_select(select, options) {
        for(var value of options) {
            var option = document.createElement('option');
            if (Array.isArray(value)) { // array of type [value, text]
                option.value = value[1];
                option.textContent = value[1];
            } else { // only value, text=value
                option.value = value;
                option.textContent = value;
            }
            select.appendChild(option);
        }
    }


                        text : Ext.util.Format.htmlEncode(this.app.i18n._hidden(attr.name)),
                        qtip : Ext.util.Format.htmlEncode(attr.description ? this.app.i18n._hidden(attr.description) + ' ' + addText : addText),
                        selected : attr.id === this.selectedFilterId,
                        id : attr.id,

                        sorting : attr.sorting,
                        draggable : true,
                        allowDrop : false,

                        leaf : attr.leaf === false ? attr.leaf : true,
                        cls : 'tinebase-westpanel-node-favorite' + addClass
                    });
                }


The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.


      left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
    }
    return left;
  },


DotObject.prototype.set = function (path, val, obj, merge) {
  var i
  var k
  var keys
  var key

  // Do not operate if the value is undefined.
  if (typeof val === 'undefined') {
    return obj
  }
  keys = parsePath(path, this.separator)

  for (i = 0; i < keys.length; i++) {
    key = keys[i]
    if (i === keys.length - 1) {
      if (merge && isObject(val) && isObject(obj[key])) {
        for (k in val) {
          if (hasOwnProperty.call(val, k)) {
            obj[key][k] = val[k]
          }
        }
      } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {
        for (var j = 0; j < val.length; j++) {
          obj[keys[i]].push(val[j])
        }
      } else {
        obj[key] = val
      }
    } else if (
      // force the value to be an object
      !hasOwnProperty.call(obj, key) ||
      (!isObject(obj[key]) && !Array.isArray(obj[key]))
    ) {
      // initialize as array if next key is numeric
      if (/^\d+$/.test(keys[i + 1])) {
        obj[key] = []
      } else {
        obj[key] = {}
      }
    }
    obj = obj[key]
  }
  return obj
}


transaction: randomString(12),
				room: myroom,
				to: username,
				text: result
			};
			textroom.data({
				text: JSON.stringify(message),
				error: function(reason) { bootbox.alert(reason); },
				success: function() {
					$('#chatroom').append('
[' + getDateString() + '] [whisper to ' + display + '] ' + escapeXmlTags(result));
					$('#chatroom').get(0).scrollTop = $('#chatroom').get(0).scrollHeight;
				}
			});
		}
	});
	return;
}


        function isCollapsedOneLiner(node) {
            const before = sourceCode.getTokenBefore(node);
            const last = sourceCode.getLastToken(node);
            const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last;

            return before.loc.start.line === lastExcludingSemicolon.loc.end.line;
        }

The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.


		rtrim = function(str){
			return str.replace(/\s+$/, '');
		},


		function unpackConfig()
		{
			if (typeof _config !== 'object')
				return;

			if (typeof _config.delimiter === 'string'
                && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)
			{
				_delimiter = _config.delimiter;
			}

			if (typeof _config.quotes === 'boolean'
				|| typeof _config.quotes === 'function'
				|| Array.isArray(_config.quotes))
				_quotes = _config.quotes;

			if (typeof _config.skipEmptyLines === 'boolean'
				|| typeof _config.skipEmptyLines === 'string')
				_skipEmptyLines = _config.skipEmptyLines;

			if (typeof _config.newline === 'string')
				_newline = _config.newline;

			if (typeof _config.quoteChar === 'string')
				_quoteChar = _config.quoteChar;

			if (typeof _config.header === 'boolean')
				_writeHeader = _config.header;

			if (Array.isArray(_config.columns)) {

				if (_config.columns.length === 0) throw new Error('Option columns is empty');

				_columns = _config.columns;
			}

			if (_config.escapeChar !== undefined) {
				_escapedQuote = _config.escapeChar + _quoteChar;
			}

			if (typeof _config.escapeFormulae === 'boolean')
				_escapeFormulae = _config.escapeFormulae;
		}


		var getExtTemplates = function(isSearch)
		{
			list.style.display = 'none';
			searchBox.style.display = 'none';
			div.style.left = '30px';

			setActiveTab(isSearch? -1 : 1); //deselect all of them if isSearch

			if (oldTemplates == null)
			{
				oldTemplates = templates;
			}

			div.scrollTop = 0;
			div.innerHTML = '';
			spinner.spin(div);

			var callback2 = function(docList, errorMsg, searchImportCats)
			{
				i0 = 0;
				spinner.stop();
				templates = docList;
				searchImportCats = searchImportCats || {};
				var importListsCount = 0;

				for (var cat in searchImportCats)
				{
					importListsCount += searchImportCats[cat].length;
				}

				if (errorMsg)
				{
					div.innerHTML = errorMsg;
				}
				else if (docList.length == 0 && importListsCount == 0)
				{
					div.innerHTML = mxUtils.htmlEntities(mxResources.get('noDiagrams', null, 'No Diagrams Found'));
				}
				else
				{
					div.innerHTML = '';

					if (importListsCount > 0)
					{
						list.style.display = '';
						div.style.left = '160px';
						list.innerHTML = '';

						customCatCount = 0;
						categories = {'draw.io': docList};

						for (var cat in searchImportCats)
						{
							categories[cat] = searchImportCats[cat];
						}

						initUi();
					}
					else
					{
						addTemplates(true);
					}
				}
			}

			if (isSearch)
			{
				searchDocsCallback(searchInput.value, callback2);
			}
			else
			{
				recentDocsCallback(callback2);
			}
		}


_currentRules:function _currentRules() {
        if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
            return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
        } else {
            return this.conditions["INITIAL"].rules;
        }
    },


        text: antSword.noxss(conf[_]['type'].toUpperCase()),
        im0: this.manager.list.imgs[0],
        im1: this.manager.list.imgs[0],
        im2: this.manager.list.imgs[0]
      });
    }


                    scope.returnThis = function () {
                        return this;
                    };


function isFormData(obj) {
  return toString.call(obj) === '[object FormData]';
}


page.onResourceRequested = function (request, networkRequest) {
    console.log('Request ' + request.url);
    if (request.url.lastIndexOf(body.url, 0) === 0) {
        return;
    }

    //potentially dangerous request
    if (request.url.lastIndexOf("file:///", 0) === 0 && !body.allowLocalFilesAccess) {
        networkRequest.abort();
        return;
    }

    //to support cdn like format //cdn.jquery...
    if (request.url.lastIndexOf("file://", 0) === 0 && request.url.lastIndexOf("file:///", 0) !== 0) {
        networkRequest.changeUrl(request.url.replace("file://", "http://"));
    }

    if (body.waitForJS && request.url.lastIndexOf("http://intruct-javascript-ending", 0) === 0) {
        pageJSisDone = true;
    }
};

The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.


    function getVersionClass(version) {
        if (version) {
            var tmp = version.split ('.');
            if (tmp[0] === '0' && tmp[1] === '0' && tmp[2] === '0') {
                version = 'planned';
            } else if (tmp[0] === '0' && tmp[1] === '0') {
                version = 'alpha';
            } else if (tmp[0] === '0') {
                version = 'beta'
            } else if (version === 'npm error') {
                version = 'error';
            } else {
                version = 'stable';
            }
        }
        return version;
    }


function create_group() {
  var num_nodes = 0;
  var node_names = "";
  $("#resource_list :checked").parent().parent().each(function (index,element) {
    if (element.getAttribute("nodeID")) {
      num_nodes++;
      node_names += element.getAttribute("nodeID") + " "
    }
  });

  if (num_nodes == 0) {
    alert("You must select at least one resource to add to a group");
    return;
  }

  $("#resources_to_add_to_group").val(node_names);
  $("#add_group").dialog({
    title: 'Create Group',
    modal: true,
    resizable: false,
    buttons: {
      Cancel: function() {
        $(this).dialog("close");
      },
      "Create Group": function() {
        var data = $('#add_group > form').serialize();
        var url = get_cluster_remote_url() + "add_group";
        ajax_wrapper({
          type: "POST",
          url: url,
          data: data,
          success: function() {
            Pcs.update();
            $("#add_group").dialog("close");
          },
          error: function (xhr, status, error) {
            alert(
              "Error creating group "
              + ajax_simple_error(xhr, status, error)
            );
            $("#add_group").dialog("close");
          }
        });
      }
    }
  });
}


          value: value.slice(start + 2, idx),
          start: start,
          end: idx + 1,
          replaceInValue: function (value, context) {
            return interpreter.replace(value, context, parseContext);
          },
        };

        return parseContext;
      }
    }

    return null;
  },

Improperly Controlled Modification of Dynamically-Determined Object Attributes

The software receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.


return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent("SHOULD NOT BE CALLED: createImageUrlConverter");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImages");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImageToDataUri");


Manager.prototype.generateId = function () {
  return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
    + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
};

The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.


  function onEnd() {
    self.readable = false;
  }


self.setContent = function($node) {
      $node.html('
' + self.icon + ' ' + lang.databasic.name + ': ' +
        $node.attr('data-test') + '
');
    };


    context.suite = function(title) {
      if (suites.length > 1) suites.shift();
      var suite = Suite.create(suites[0], title);
      suites.unshift(suite);
      return suite;
    };


function selectedFilesRail(inputFileID) {

    var fileobj = [];
    if(inputFileID && inputFileID != '') {
        setFilesRail(document.getElementById(inputFileID).files);
    }
}


Context.prototype.inspect = function(){
  return JSON.stringify(this, function(key, val){
    if ('_runnable' == key) return;
    if ('test' == key) return;
    return val;
  }, 2);
};


  copy: function (from, dist, callback) {
    var that = this,
      cmd = '';
    dist = path.resolve(dist);
    fs.lstat(from, function (err, stats) {
      if (err) {
        callback(err);
      } else {
        if (stats.isDirectory()) {
          that.mkdir(dist, function (err) {
            if (err) {
              callback(err);
            } else {
              if (that._win32) {
                cmd = 'echo d|xcopy /s /e /y "' + path.join(from, '*') + '" "' + dist + '"';
              } else {
                cmd = 'cp -f -R -p ' + path.join(from, '*').replace(/ /g, '\\ ') + ' ' + dist.replace(/ /g, '\\ ');
              }
              child_process.exec(cmd, function (error, stdout, stderr) {
                callback && callback(error);
              });
            }
          });
        } else if (stats.isFile()) {
          if (that._win32) {
            cmd = 'echo f|xcopy /y "' + from + '" "' + dist + '"';
          } else {
            cmd = 'cp -f -p ' + from.replace(/ /g, '\\ ') + ' ' + dist.replace(/ /g, '\\ ');
          }
          child_process.exec(cmd, function (error, stdout, stderr) {
            callback && callback(error);
          });
        } else {
          callback && callback(null);
        }
      }
    });
  },

Improper Neutralization of Special Elements used in a Command ('Command Injection')

The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.


	expression: function() {
		return this.assignment();
	},


Client.prototype.openssh_forwardInStreamLocal = function(socketPath, cb) {
  if (!this._sock
      || !this._sock.writable
      || !this._sshstream
      || !this._sshstream.writable)
    throw new Error('Not connected');

  var wantReply = (typeof cb === 'function');
  var self = this;

  if (!this.config.strictVendor
      || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
    if (wantReply) {
      this._callbacks.push(function(had_err) {
        if (had_err) {
          return cb(had_err !== true
                    ? had_err
                    : new Error('Unable to bind to ' + socketPath));
        }
        self._forwardingUnix[socketPath] = true;
        cb();
      });
    }

    return this._sshstream.openssh_streamLocalForward(socketPath, wantReply);
  } else if (wantReply) {
    process.nextTick(function() {
      cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version'));
    });
  }

  return true;
};


	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "dialogClass" ) {
			uiDialog
				.removeClass( this.options.dialogClass )
				.addClass( value );
		}

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button({
				// ensure that we always pass a string
				label: "" + value
			});
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {
			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


    context.teardown = function(fn) {
      suites[0].afterEach(fn);
    };