			$_q = trim($_q);
			if ($_q !== '') {
				if ($_q[0] === '-') {
					if (isset($_q[1])) {
						$excludes[] = substr($_q, 1);
					}
				} else {
					$query[] = $_q;
				}
			}
		}
		if (! $query) {
			$q = '';
		} else {
			$q = join(' ', $query);
			$this->doSearchCurrentQuery = array(
				'q' => $q,
				'excludes' => $excludes
			);
		}

		// valided regex $this->options['searchExDirReg']
		if ($this->options['searchExDirReg']) {
			if (false === preg_match($this->options['searchExDirReg'], '')) {
				$this->options['searchExDirReg'] = '';
			}
		}

		return ($q === '' || $this->commandDisabled('search'))
			? array()
			: $this->doSearch(is_null($dir)? $this->root : $dir, $q, $mimes);
	}


	protected function _dimensions($path, $mime) {
		if (strpos($mime, 'image') !== 0) return '';
		$cache = $this->getDBdat($path);
		if (isset($cache['width']) && isset($cache['height'])) {
			return $cache['width'].'x'.$cache['height'];
		}
		$ret = '';
		if ($work = $this->getWorkFile($path)) {
			if ($size = getimagesize($work)) {
				$cache['width'] = $size[0];
				$cache['height'] = $size[1];
				$this->updateDBdat($path, $cache);
				$ret = $size[0].'x'.$size[1];
			}
		}
		is_file($work) && unlink($work);
		return $ret;
	}

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.


	protected function _fclose($fp, $path='') {
		fclose($fp);
		if ($path) {
			unlink($this->getTempFile($path));
		}
	}


	protected function _copy($source, $targetDir, $name) {
		$res = false;

		if ($this->tmp) {
			$local  = $this->getTempFile();
			$target = $this->_joinPath($targetDir, $name);

			if (ftp_get($this->connect, $local, $source, FTP_BINARY)
			&& ftp_put($this->connect, $target, $local, $this->ftpMode($target))) {
				$res = $target;
			}
			unlink($local);
		}

		return $res;
	}


	public function localFileSystemSearchIteratorFilter($file, $key, $iterator) {
		$name = $file->getFilename();
		if ($this->doSearchCurrentQuery['excludes']) {
			foreach($this->doSearchCurrentQuery['excludes'] as $exclude) {
				if ($this->stripos($name, $exclude) !== false) {
					return false;
				}
			}
		}
		if ($iterator->hasChildren()) {
			if ($this->options['searchExDirReg'] && preg_match($this->options['searchExDirReg'], $key)) {
				return false;
			}
			return (bool)$this->attr($key, 'read', null, true);
		}
		return ($this->stripos($name, $this->doSearchCurrentQuery['q']) === false)? false : true;
	}


	protected function _stat($path) {

		static $statOwner;
		if (is_null($statOwner)) {
			$statOwner = (!empty($this->options['statOwner']));
		}

		$stat = array();

		if (!file_exists($path) && !is_link($path)) {
			return $stat;
		}

		//Verifies the given path is the root or is inside the root. Prevents directory traveral.
		if (!$this->_inpath($path, $this->root)) {
			return $stat;
		}

		$gid = $uid = 0;
		$stat['isowner'] = false;
		$linkreadable = false;
		if ($path != $this->root && is_link($path)) {
			if (! $this->options['followSymLinks']) {
				return array();
			}
			if (!($target = $this->readlink($path))
			|| $target == $path) {
				if (is_null($target)) {
					$stat = array();
					return $stat;
				} else {
					$stat['mime']  = 'symlink-broken';
					$target = readlink($path);
					$lstat = lstat($path);
					$ostat = $this->getOwnerStat($lstat['uid'], $lstat['gid']);
					$linkreadable = !empty($ostat['isowner']);
				}
			}
			$stat['alias'] = $this->_path($target);
			$stat['target'] = $target;
		}
		$size = sprintf('%u', filesize($path));
		$stat['ts'] = filemtime($path);
		if ($statOwner) {
			$fstat = stat($path);
			$uid = $fstat['uid'];
			$gid = $fstat['gid'];
			$stat['perm'] = substr((string)decoct($fstat['mode']), -4);
			$stat = array_merge($stat, $this->getOwnerStat($uid, $gid));
		}

		if (($dir = is_dir($path)) && $this->options['detectDirIcon']) {
			$favicon = $path . DIRECTORY_SEPARATOR . $this->options['detectDirIcon'];
			if ($this->URL && file_exists($favicon)) {
				$stat['icon'] = $this->URL . str_replace(DIRECTORY_SEPARATOR, '/', substr($favicon, strlen($this->root) + 1));
			}
		}

		if (!isset($stat['mime'])) {
			$stat['mime'] = $dir ? 'directory' : $this->mimetype($path);
		}
		//logical rights first
		$stat['read'] = ($linkreadable || is_readable($path))? null : false;
		$stat['write'] = is_writable($path)? null : false;

		if (is_null($stat['read'])) {
			$stat['size'] = $dir ? 0 : $size;
		}

		return $stat;
	}


	protected function _chmod($path, $mode) {
		$modeOct = is_string($mode) ? octdec($mode) : octdec(sprintf("%04o",$mode));
		$ret = chmod($path, $modeOct);
		$ret && clearstatcache();
		return  $ret;
	}


	protected function _copy($source, $targetDir, $name) {
		$mtime = filemtime($source);
		$target = $this->_joinPath($targetDir, $name);
		if ($ret = copy($source, $target)) {
			isset($this->options['keepTimestamp']['copy']) && $mtime && touch($target, $mtime);
			clearstatcache();
		}
		return $ret;
	}


	protected function _copy($source, $targetDir, $name) {
		$this->clearcache();
		$id = $this->_joinPath($targetDir, $name);

		$sql = $id > 0
			? sprintf('REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden`) (SELECT %d, %d, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden` FROM %s WHERE id=%d)', $this->tbf, $id, $this->_dirname($id), $this->tbf, $source)
			: sprintf('INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden`) SELECT %d, \'%s\', content, size, %d, mime, width, height, `read`, `write`, `locked`, `hidden` FROM %s WHERE id=%d', $this->tbf, $targetDir, $this->db->real_escape_string($name), time(), $this->tbf, $source);

		return $this->query($sql);
	}


	public function cmdPostprocess($cmd, &$result, $args, $elfinder) {
		if ($cmd === 'ls') {
			if (! empty($result['list']) && ! empty($this->replaced['ls'])) {
				foreach($result['list'] as $hash => $name) {
					if ($keys = array_keys($this->replaced['ls'], $name)) {
						if (count($keys) === 1) {
							$result['list'][$hash] = $keys[0];
						} else {
							$result['list'][$hash] = $keys;
						}
					}
				}
			}
		}
	}


    public function setJson($json)
    {
        $this->data = $json;

        return $this->update();
    }


    private function normalizeAndFilterClientIps(array $clientIps, $ip)
    {
        $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
        $firstTrustedIp = null;

        foreach ($clientIps as $key => $clientIp) {
            // Remove port (unfortunately, it does happen)
            if (preg_match('{((?:\d+\.) {3}\d+)\:\d+}', $clientIp, $match)) {
                $clientIps[$key] = $clientIp = $match[1];
            }

            if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
                unset($clientIps[$key]);

                continue;
            }

            if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
                unset($clientIps[$key]);

                // Fallback to this when the client IP falls into the range of trusted proxies
                if (null === $firstTrustedIp) {
                    $firstTrustedIp = $clientIp;
                }
            }
        }

        // Now the IP chain contains only untrusted proxies and the client IP
        return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);
    }


    public function start()
    {
        if ($this->started) {
            return true;
        }

        if (\PHP_SESSION_ACTIVE === session_status()) {
            throw new \RuntimeException('Failed to start the session: already started by PHP.');
        }

        if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
            throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
        }

        // ok to try and start the session
        if (!session_start()) {
            throw new \RuntimeException('Failed to start the session');
        }

        $this->loadSession();

        return true;
    }


    public function isActive()
    {
        return \PHP_SESSION_ACTIVE === session_status();
    }


    public function testDestroy()
    {
        $collection = $this->createMongoCollectionMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $methodName = phpversion('mongodb') ? 'deleteOne' : 'remove';

        $collection->expects($this->once())
            ->method($methodName)
            ->with(array($this->options['id_field'] => 'foo'));

        $this->assertTrue($this->storage->destroy('foo'));
    }


    public function testNameException()
    {
        session_start();
        $this->proxy->setName('foo');
    }


    public static function mb_http_output($encoding = null)
    {
        return null !== $encoding ? 'pass' === $encoding : 'pass';
    }


    public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
    {
        $encoding = self::getEncoding($encoding);

        if ('' === $needle .= '') {
            trigger_error(__METHOD__.': Empty delimiter', E_USER_WARNING);

            return false;
        }

        return iconv_strpos($haystack, $needle, $offset, $encoding);
    }


function mb_strrpos($s, $needle, $offset = 0, $enc = null) { return p\Mbstring::mb_strrpos($s, $needle, $offset, $enc); }


function mb_substitute_character($char = null) { return p\Mbstring::mb_substitute_character($char); }


function mb_strrichr($s, $needle, $part = false, $enc = null) { return p\Mbstring::mb_strrichr($s, $needle, $part, $enc); }


    public static function exist($cat)
    {
        $cat = Typo::int($cat);
        $sql = "SELECT `id` FROM `cat` WHERE `id` = '{$cat}'";
        $q = Db::result($sql);
        // echo Db::$num_rows;
        if (Db::$num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }


    public static function title($mod)
    {
        $data = self::data($mod);

        return $data['name'];
    }


                'text' => htmlspecialchars($item->getName(), ENT_QUOTES),
                'expandable' => false,
                'leaf' => true,
                'expanded' => true,
                'description' => htmlspecialchars($item->getDescription(), ENT_QUOTES),
                'iconCls' => 'pimcore_icon_classificationstore',
            ];

            $resultItem['qtitle'] = 'ID: ' . $item->getId();

            if ($item->getDescription()) {
            }
            $resultItem['qtip'] = $item->getDescription() ? htmlspecialchars($item->getDescription(), ENT_QUOTES) : ' ';
            $result[] = $resultItem;
        }

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 __construct(
        protected RequestHelper $requestHelper,
        protected ContentSecurityPolicyHandler $contentSecurityPolicyHandler,
        protected Config $config
    )
    {
    }


    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }


    public function build(ContainerBuilder $container)
    {
        // auto-tag GDPR data providers
        $container
            ->registerForAutoconfiguration(DataProviderInterface::class)
            ->addTag('pimcore.gdpr.data-provider');

        $container->addCompilerPass(new SerializerPass());
        $container->addCompilerPass(new GDPRDataProviderPass());
        $container->addCompilerPass(new ImportExportLocatorsPass());
        $container->addCompilerPass(new TranslationServicesPass());
        $container->addCompilerPass(new ContentSecurityPolicyUrlsPass());

        /** @var SecurityExtension $extension */
        $extension = $container->getExtension('security');
        $extension->addSecurityListenerFactory(new PreAuthenticatedAdminSessionFactory());
    }


    public function __construct(protected Config $config, protected array $cspHeaderOptions = [])
    {
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);

        $this->cspHeaderOptions = $resolver->resolve($cspHeaderOptions);
    }


        $cspHeaderOptions = array_map(function ($k, $v) {
            return "$k $v " . $this->getAllowedUrls($k);
        }, array_keys($this->cspHeaderOptions), array_values($this->cspHeaderOptions));


                    $this->orderKey[] = $this->quoteIdentifier($o);
                }
            }
        }


            } elseif ($type == 'customlayout') {
                $layoutData = json_decode($data['name'], true);
                $className = $layoutData['className'];
                $layoutName = $layoutData['name'];

                if ($item['name'] == $layoutName && $item['className'] == $className) {
                    $class = DataObject\ClassDefinition::getByName($className);
                    if (!$class) {
                        throw new \Exception('Class does not exist');
                    }

                    $classId = $class->getId();

                    $layoutList = new DataObject\ClassDefinition\CustomLayout\Listing();
                    $db = \Pimcore\Db::get();
                    $layoutList->setCondition('name = ' . $db->quote($layoutName) . ' AND classId = ' . $classId);
                    $layoutList = $layoutList->load();

                    $layoutDefinition = null;
                    if ($layoutList) {
                        $layoutDefinition = $layoutList[0];
                    }

                    if (!$layoutDefinition) {
                        $layoutDefinition = new DataObject\ClassDefinition\CustomLayout();
                        $layoutDefinition->setName($layoutName);
                        $layoutDefinition->setClassId($classId);
                    }

                    try {
                        $layoutDefinition->setDescription($item['description']);
                        $layoutDef = DataObject\ClassDefinition\Service::generateLayoutTreeFromArray($item['layoutDefinitions'], true);
                        $layoutDefinition->setLayoutDefinitions($layoutDef);
                        $layoutDefinition->save();
                    } catch (\Exception $e) {
                        Logger::error($e->getMessage());

                        return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);
                    }
                }
            }
        }

        return $this->adminJson(['success' => true]);
    }

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


    public function testUserCredentials($email, $password, $server, $port, $security) {
        require_once(
            realpath(Yii::app()->basePath.'/components/phpMailer/PHPMailerAutoload.php'));
        $phpMail = new PHPMailer(true);

        $phpMail->isSMTP();
        $phpMail->SMTPAuth = true;
        $phpMail->Username = $email;
        $phpMail->Password = $password;
        $phpMail->Host = $server;
        $phpMail->Port = $port;
        $phpMail->SMTPSecure = $security;

        try {
            $validCredentials = $phpMail->SmtpConnect();
        } catch(phpmailerException $error) {
            $validCredentials = false;
        }
        return $validCredentials;
    }

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.


            $tags = array_merge($matches, $tags);
        }
        $tags = array_unique($tags);
        return $tags;
    }


            $text = preg_replace($exp, '', $text);
        }

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

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

        return $matches[1];
    }


    private function registerTestingScripts () {
        if (YII_UNIT_TESTING) {
//            $this->registerScriptFile (
//                $baseUrl.'/js/qunit/qunit-1.15.0.js', CClientScript::POS_HEAD);
//            $this->registerCssFile ($baseUrl.'/js/qunit/qunit-1.15.0.css');
            Yii::app()->clientScript->registerScript('unitTestingErrorHandler',"
            ;(function () {
                if (typeof x2 === 'undefined') return;
                if (x2.UNIT_TESTING) {
                    var oldErrorHandler = window.onerror;
                    window.onerror = function (errorMessage, url, lineNumber) {
                        $('body').attr (
                            'x2-js-error', 'Javascript Error: ' + url + ': ' + lineNumber + ': ' +
                                errorMessage);

                        if (oldErrorHandler) return oldErrorHandler (errorMessage, url, lineNumber);
                        return false;
                    };
                }
            }) ();
            ", self::POS_HEAD);
        }
    }


    public function isQmail()
    {
        $ini_sendmail_path = ini_get('sendmail_path');

        if (!stristr($ini_sendmail_path, 'qmail')) {
            $this->Sendmail = '/var/qmail/bin/qmail-inject';
        } else {
            $this->Sendmail = $ini_sendmail_path;
        }
        $this->Mailer = 'qmail';
    }


    protected function edebug($str)
    {
        if ($this->SMTPDebug <= 0) {
            return;
        }
        //Avoid clash with built-in function names
        if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
            return;
        }
        switch ($this->Debugoutput) {
            case 'error_log':
                //Don't output, just log
                error_log($str);
                break;
            case 'html':
                //Cleans up output a bit for a better looking, HTML-safe output
                echo htmlentities(
                    preg_replace('/[\r\n]+/', '', $str),
                    ENT_QUOTES,
                    'UTF-8'
                )
                . "<br>\n";
                break;
            case 'echo':
            default:
                //Normalize line breaks
                $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
                echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
                    "\n",
                    "\n                   \t                  ",
                    trim($str)
                ) . "\n";
        }
    }


    public function isSMTP()
    {
        $this->Mailer = 'smtp';
    }


    public function __destruct()
    {
        //Close any open SMTP connection nicely
        if ($this->Mailer == 'smtp') {
            $this->smtpClose();
        }
    }


    public function isSendmail()
    {
        $ini_sendmail_path = ini_get('sendmail_path');

        if (!stristr($ini_sendmail_path, 'sendmail')) {
            $this->Sendmail = '/usr/sbin/sendmail';
        } else {
            $this->Sendmail = $ini_sendmail_path;
        }
        $this->Mailer = 'sendmail';
    }


    public function isMail()
    {
        $this->Mailer = 'mail';
    }


    public function login($username = '', $password = '')
    {
        if (!$this->connected) {
            $this->setError('Not connected to POP3 server');
        }
        if (empty($username)) {
            $username = $this->username;
        }
        if (empty($password)) {
            $password = $this->password;
        }

        // Send the Username
        $this->sendString("USER $username" . self::CRLF);
        $pop3_response = $this->getResponse();
        if ($this->checkResponse($pop3_response)) {
            // Send the Password
            $this->sendString("PASS $password" . self::CRLF);
            $pop3_response = $this->getResponse();
            if ($this->checkResponse($pop3_response)) {
                return true;
            }
        }
        return false;
    }


    protected function hmac($data, $key)
    {
        if (function_exists('hash_hmac')) {
            return hash_hmac('md5', $data, $key);
        }

        // The following borrowed from
        // http://php.net/manual/en/function.mhash.php#27225

        // RFC 2104 HMAC implementation for php.
        // Creates an md5 HMAC.
        // Eliminates the need to install mhash to compute a HMAC
        // by Lance Rushing

        $bytelen = 64; // byte length for md5
        if (strlen($key) > $bytelen) {
            $key = pack('H*', md5($key));
        }
        $key = str_pad($key, $bytelen, chr(0x00));
        $ipad = str_pad('', $bytelen, chr(0x36));
        $opad = str_pad('', $bytelen, chr(0x5c));
        $k_ipad = $key ^ $ipad;
        $k_opad = $key ^ $opad;

        return md5($k_opad . pack('H*', md5($k_ipad . $data)));
    }


    public function setDebugLevel($level = 0)
    {
        $this->do_debug = $level;
    }


    protected function edebug($str, $level = 0)
    {
        if ($level > $this->do_debug) {
            return;
        }
        //Avoid clash with built-in function names
        if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
            call_user_func($this->Debugoutput, $str, $this->do_debug);
            return;
        }
        switch ($this->Debugoutput) {
            case 'error_log':
                //Don't output, just log
                error_log($str);
                break;
            case 'html':
                //Cleans up output a bit for a better looking, HTML-safe output
                echo htmlentities(
                    preg_replace('/[\r\n]+/', '', $str),
                    ENT_QUOTES,
                    'UTF-8'
                )
                . "<br>\n";
                break;
            case 'echo':
            default:
                //Normalize line breaks
                $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
                echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
                    "\n",
                    "\n                   \t                  ",
                    trim($str)
                )."\n";
        }
    }


            foreach ($lines_out as $line_out) {
                //RFC2821 section 4.5.2
                if (!empty($line_out) and $line_out[0] == '.') {
                    $line_out = '.' . $line_out;
                }
                $this->client_send($line_out . self::CRLF);
            }


    public function quit($close_on_error = true)
    {
        $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
        $err = $this->error; //Save any error
        if ($noerror or $close_on_error) {
            $this->close();
            $this->error = $err; //Restore any error from the quit command
        }
        return $noerror;
    }


    public function noop()
    {
        return $this->sendCommand('NOOP', 'NOOP', 250);
    }


                    $modelName = ucfirst ($module->name);
                    if ($module->name !== 'document' && class_exists ($modelName)) {
                        // prefix widget class name with custom module model name and a delimiter
                        $cache[$widgetType][$modelName.'::TemplatesGridViewProfileWidget'] =
                            Yii::t(
                                'app', '{modelName} Summary', array ('{modelName}' => $modelName));
                    }
                }
            }
        }
        return $cache[$widgetType];
    }


	public function execute(&$params) {
        $listIdentifier=$this->parseOption('listId',$params);
        if(is_numeric($listIdentifier)){
            $list = CActiveRecord::model('X2List')->findByPk($listIdentifier);
        }else{
            $list = CActiveRecord::model('X2List')->findByAttributes(
                array('name'=>$listIdentifier));
        }

		if($list !== null && $list->modelName === get_class($params['model'])) {
			if ($list->addIds($params['model']->id)) {
                return array (true, "");
            }
		}
        return array (false, "");
	}


    public function isVisibleTo ($user) {
        if (Yii::app()->params->isAdmin) return true;
        if (!$user) return false;

        $assignedUser = null;
        if ($this->associationType === 'User') {
            $assignedUser = User::model ()->findByPk ($this->associationId);
        }
        switch (Yii::app()->settings->historyPrivacy) {
            case 'group':
                if (in_array ($this->user, Groups::getGroupmates ($user->id)) ||
                    ($this->associationType === 'User' &&
                     $assignedUser &&
                     in_array ($assignedUser->username, Groups::getGroupmates ($user->id)))) {

                    return true;
                }
                // fall through
            case 'user':
                if ($this->user === $user->username ||
                    ($this->associationType === 'User' &&
                     ($this->associationId === $user->id))) {

                    return true;
                }
                break;
            default: // default history privacy (public or assigned)
                return ($this->user === $user->username || $this->visibility ||
                    $this->associationType === 'User' && $this->associationId === $user->id);
        }
        return false;
    }


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


    public static function displayName($plural = true, $module = null) {
        $moduleTitle = null;
        if (is_null($module))
            $module = Yii::app()->controller->module->name;

        // return a cached value
        if (isset(self::$_displayNames[$module][$plural]))
            return self::$_displayNames[$module][$plural];

        $moduleTitle = Yii::app()->db->createCommand()
            ->select('title')
            ->from('x2_modules')
            ->where("name = :name")
            ->bindValue(':name', $module)
            ->limit(1)
            ->queryScalar();

        if (!$moduleTitle) return false;

        if (Yii::app()->locale->id === 'en') {
            // Handle silly English pluralization
            if (!$plural) {
                if (preg_match('/ies$/', $moduleTitle)) {
                    $moduleTitle = preg_replace('/ies$/', 'y', $moduleTitle);
                } else if (preg_match('/ses$/', $moduleTitle)) {
                    $moduleTitle = preg_replace('/es$/', '', $moduleTitle);
                } else if ($moduleTitle !== 'Process') {
                    // Otherwise chop the trailing s
                    $moduleTitle = trim($moduleTitle, 's');
                }
            } else {
                if (preg_match('/y$/', $moduleTitle)) {
                    $moduleTitle = preg_replace('/y$/', 'ies', $moduleTitle);
                } else if (preg_match('/ss$/', $moduleTitle)) {
                    $moduleTitle .= 'es';
                } else if (in_array ($moduleTitle, array ('Service'))) {
                    $moduleTitle .= 's';
                }
            }
        }
        self::$_displayNames[$module][$plural] = $moduleTitle;
        return $moduleTitle;
    }


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


    public function getDisplayName ($plural=true, $ofModule=true) {
        if (!$ofModule) {
            return Yii::t('app', 'Campaign'.($plural ? 's' : ''));
        } else {


    public function getDisplayName ($plural=true, $ofModule=true) {
        return Yii::t('marketing', 'Web Form');
    }


    public function actionDelete($id){
        if(Yii::app()->request->isPostRequest){
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            if (!$this->checkPermissions ($model, 'delete')) $this->denied ();
            $model->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
    }


	public function actionUpdate($id,$quick=0){
		$model = $this->getModel($id);

		if(isset($_POST['Quote'])){
			$model->setX2Fields($_POST['Quote']);
			if(isset($_POST['lineitem']))
				$model->lineItems = $_POST['lineitem'];

			if(!$model->hasLineItemErrors) {
				if($model->save()) {
					$model->saveLineItems();
					$this->redirect(array('view','id' => $model->id));
				}
			}
		}
		$users=User::getNames();
		$products = $model->activeProducts();
		$quoteProducts = $model->lineItems;
		$viewData = array(
			'model' => $model,
			'users' => $users,
			'products' => $products,
			'orders' => $quoteProducts,
			'quick'=>$quick,
		);

		if(!$quick)
			$this->render('update', $viewData);
		else {
			if($model->hasErrors() || $model->hasLineItemErrors) {
				// Sneak into the response that validation failed via setting
				// the response code manually:
				header('HTTP/1.1 400 Validation Error');
			}
			$this->renderPartial('update', $viewData,false,true);
		}
	}


            foreach($item->attributes as $name => $value)
                if ($name !== 'id' && $name !== 'listId') {
                    $copy->$name = $value;
                }
            $lineItems[] = $copy;
        }
        return $lineItems;
    }


    public function getDisplayName ($plural=true, $ofModule=true) {
        return Yii::t('workflow', '{process}', array(
            '{process}' => Modules::displayName($plural, 'Process'),
        ));
    }


    public function testImportLineEndings() {
        $csvFile = 'lineendings-contacts.csv';
        // Skip verification of uploaded CSV since it will be modified
        $this->prepareImport ('Contacts', $csvFile, false);
        $expected = $this->stashModels ('Contacts');
        $this->assertGreaterThan (0, count($expected),
            'Failed to load fixture! Models were expected');
        $this->beginImport();
        $this->assertNoValidationErrorsPresent();
        $this->assertModelsWereImported ($expected, 'Contacts');
    }


            $this->assertCsvExported ($modelName);
        }
    }


    public function testContactsPages () {
        $this->visitPages ($this->getPages ('^contacts'));
    }


    public function testDocsPages () {
        $this->visitPages ($this->getPages ('^docs'));
    }


    public function testBugReportsPages () {
        $this->visitPages ($this->getPages ('^bugReports'));
    }


    public function testClearTags () {
        $contact = $this->contacts ('testAnyone');
        Yii::app()->db->createCommand ("
            delete from x2_tags where type='Contacts' and itemId=:id
        ")->execute (array (':id' => $contact->id));
        $tags = array ('test', 'test2', 'test3');
        $contact->addTags ($tags);
        $contact->clearTags ();
        $this->assertEquals (array (), $contact->getTags (true));
    }


    public function testPregReplace () {
        $str = self::$dummyString;

        $pattern = '/\d+/';
        $replacement = '';
        $this->assertEquals (
            preg_replace ($pattern, $replacement, $str),
            StringUtil::pregReplace ($pattern, $replacement, $str)
        );

        $this->assertEquals (
            preg_replace ($pattern, $replacement, $str, 1),
            StringUtil::pregReplace ($pattern, $replacement, $str, 1)
        );

        $countA = null;
        $countB = null;
        $this->assertEquals (
            preg_replace ($pattern, $replacement, $str, 1, $countA),
            StringUtil::pregReplace ($pattern, $replacement, $str, 1, $countB)
        );
    }


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

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

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


    public function tearDown () {
        self::restoreIniSettings ();
        return parent::tearDown ();
    }


    public function testRedirectLinkGenerationException () {
        $this->setExpectedException (
            'StringUtilException', '',
            StringUtilException::PREG_REPLACE_CALLBACK_ERROR);

        // set this high enough to cause a redirect link replacement error, but not a CUrlRule error
        ini_set('pcre.backtrack_limit', '10');
        ini_set('pcre.recursion_limit', '10');

        Yii::app()->controller = new MarketingController (
            'campaign', new MarketingModule ('campaign', null));
        $_SERVER['SERVER_NAME'] = 'localhost';
        $cmb = $this->instantiate();
        $contact = $this->contacts('testUser_unsent');
        list($subject,$message,$uniqueId) = $cmb->prepareEmail(
            $this->campaign('redirectLinkGeneration'), $contact, false);
    }


    protected function registerTwigParser()
    {
        /*
         * Register system Twig environment
         */
        App::singleton('twig.environment', function ($app) {
            $twig = new TwigEnvironment(new TwigLoader, ['auto_reload' => true]);
            $twig->addExtension(new TwigExtension);
            $twig->addExtension(new SandboxExtension(new TwigSecurityPolicy, true));
            return $twig;
        });

        /*
         * Register .htm extension for Twig views
         */
        App::make('view')->addExtension('htm', 'twig', function () {
            return new TwigEngine(App::make('twig.environment'));
        });
    }

NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.


    protected function registerBackendPermissions()
    {
        BackendAuth::registerCallback(function ($manager) {
            $manager->registerPermissions('October.System', [
                'system.manage_updates' => [
                    'label' => 'system::lang.permissions.manage_software_updates',
                    'tab' => 'system::lang.permissions.name',
                    'roles' => UserRole::CODE_DEVELOPER,
                ],
                'system.access_logs' => [
                    'label' => 'system::lang.permissions.access_logs',
                    'tab' => 'system::lang.permissions.name',
                    'roles' => UserRole::CODE_DEVELOPER,
                ],
                'system.manage_mail_settings' => [
                    'label' => 'system::lang.permissions.manage_mail_settings',
                    'tab' => 'system::lang.permissions.name',
                    'roles' => UserRole::CODE_DEVELOPER,
                ],
                'system.manage_mail_templates' => [
                    'label' => 'system::lang.permissions.manage_mail_templates',
                    'tab' => 'system::lang.permissions.name',
                    'roles' => UserRole::CODE_DEVELOPER,
                ]
            ]);
        });
    }

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


	function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
		if ( -1 === $action ) {
			_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );
		}

		$adminurl = strtolower( admin_url() );
		$referer  = strtolower( wp_get_referer() );
		$result   = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false;

		/**
		 * Fires once the admin request has been validated or not.
		 *
		 * @since 1.5.1
		 *
		 * @param string    $action The nonce action.
		 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
		 *                          0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
		 */
		do_action( 'check_admin_referer', $action, $result );

		if ( ! $result && ! ( -1 === $action && strpos( $referer, $adminurl ) === 0 ) ) {
			wp_nonce_ays( $action );
			die();
		}

		return $result;
	}

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.


$activate_url = add_query_arg( array(
								'_wpnonce'    => wp_create_nonce( 'activate-plugin_' . $status['file'] ),
								'action'      => 'activate',
								'plugin'      => $status['file'],
							), network_admin_url( 'plugins.php' ) );

							if ( is_network_admin() ) {
								$button_text  = __( 'Network Activate' );
								$activate_url = add_query_arg( array( 'networkwide' => 1 ), $activate_url );
							}

							$action_links[] = sprintf(
								'%3$s',
								esc_url( $activate_url ),
								/* translators: %s: Plugin name */
								esc_attr( sprintf( __( 'Activate %s' ), $plugin['name'] ) ),
								$button_text
							);
						} else {
							$action_links[] = '<button type="button" class="button button-disabled" disabled="disabled">' . _x( 'Installed', 'plugin' ) . '</button>';
						}
						break;
				}
			}


$link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $attr );
	} else {
		$link_text = '';
	}

	if ( trim( $link_text ) == '' )
		$link_text = $_post->post_title;

	/**
	 * Filters a retrieved attachment page link.
	 *
	 * @since 2.7.0
	 *
	 * @param string       $link_html The page link HTML output.
	 * @param int          $id        Post ID.
	 * @param string|array $size      Size of the image. Image size or array of width and height values (in that order).
	 *                                Default 'thumbnail'.
	 * @param bool         $permalink Whether to add permalink to image. Default false.
	 * @param bool         $icon      Whether to include an icon. Default false.
	 * @param string|bool  $text      If string, will be link text. Default false.
	 */
	return apply_filters( 'wp_get_attachment_link', "$link_text", $id, $size, $permalink, $icon, $text );
}


	public function update_item_permissions_check( $request ) {
		$comment = $this->get_comment( $request['id'] );
		if ( is_wp_error( $comment ) ) {
			return $comment;
		}

		if ( ! $this->check_edit_permission( $comment ) ) {
			return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		return true;
	}


	protected function get_comment( $id ) {
		$error = new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
		if ( (int) $id <= 0 ) {
			return $error;
		}

		$id = (int) $id;
		$comment = get_comment( $id );
		if ( empty( $comment ) ) {
			return $error;
		}

		if ( ! empty( $comment->comment_post_ID ) ) {
			$post = get_post( (int) $comment->comment_post_ID );
			if ( empty( $post ) ) {
				return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
			}
		}

		return $comment;
	}


	public function register_routes() {

		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_items' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => $this->get_collection_params(),
			),
			'schema' => array( $this, 'get_public_item_schema' ),
		) );

		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<status>[\w-]+)', array(
			'args' => array(
				'status' => array(
					'description' => __( 'An alphanumeric identifier for the status.' ),
					'type'        => 'string',
				),
			),
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_item' ),
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
				'args'                => array(
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
				),
			),
			'schema' => array( $this, 'get_public_item_schema' ),
		) );
	}


	public function create_item_permissions_check( $request ) {
		if ( ! empty( $request['id'] ) ) {
			return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
		}

		$post_type = get_post_type_object( $this->post_type );

		if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
			return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
			return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		if ( ! current_user_can( $post_type->cap->create_posts ) ) {
			return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		if ( ! $this->check_assign_terms_permission( $request ) ) {
			return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
		}

		return true;
	}


function wp_read_audio_metadata( $file ) {
	if ( ! file_exists( $file ) ) {
		return false;
	}
	$metadata = array();

	if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
		define( 'GETID3_TEMP_DIR', get_temp_dir() );
	}

	if ( ! class_exists( 'getID3', false ) ) {
		require( ABSPATH . WPINC . '/ID3/getid3.php' );
	}
	$id3 = new getID3();
	$data = $id3->analyze( $file );

	if ( ! empty( $data['audio'] ) ) {
		unset( $data['audio']['streams'] );
		$metadata = $data['audio'];
	}

	if ( ! empty( $data['fileformat'] ) )
		$metadata['fileformat'] = $data['fileformat'];
	if ( ! empty( $data['filesize'] ) )
		$metadata['filesize'] = (int) $data['filesize'];
	if ( ! empty( $data['mime_type'] ) )
		$metadata['mime_type'] = $data['mime_type'];
	if ( ! empty( $data['playtime_seconds'] ) )
		$metadata['length'] = (int) round( $data['playtime_seconds'] );
	if ( ! empty( $data['playtime_string'] ) )
		$metadata['length_formatted'] = $data['playtime_string'];

	wp_add_id3_tag_data( $metadata, $data );

	$metadata = wp_kses_post_deep( $metadata );

	return $metadata;
}


	function _real_escape( $string ) {
		if ( $this->dbh ) {
			if ( $this->use_mysqli ) {
				$escaped = mysqli_real_escape_string( $this->dbh, $string );
			} else {
				$escaped = mysql_real_escape_string( $string, $this->dbh );
			}
		} else {
			$class = get_class( $this );
			if ( function_exists( '__' ) ) {
				/* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
				_doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
			} else {
				_doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
			}
			$escaped = addslashes( $string );
		}

		return $this->add_placeholder_escape( $escaped );
	}


	public function add_placeholder_escape( $query ) {
		/*
		 * To prevent returning anything that even vaguely resembles a placeholder,
		 * we clobber every % we can find.
		 */
		return str_replace( '%', $this->placeholder_escape(), $query );
	}


    public function logout()
    {
        if ($this->Session->check('Auth.User')) {
            $this->User->extralog($this->Auth->user(), "logout");
        }
        $this->Flash->info(__('Good-Bye'));
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $this->Auth->user('id')
            ),
            'recursive' => -1
        ));
        unset($user['User']['password']);
        $user['User']['action'] = 'logout';
        $this->User->save($user['User'], true, array('id'));
        $this->redirect($this->Auth->logout());
    }


    private function __findObjectByUuid($object_uuid, &$type, $scope = 'modify')
    {
        $this->loadModel('Event');
        if (!$this->userRole['perm_tagger']) {
            throw new MethodNotAllowedException(__('This functionality requires tagging permission.'));
        }
        $object = $this->Event->fetchEvent($this->Auth->user(), array(
            'event_uuid' => $object_uuid,
            'metadata' => 1
        ));
        $type = 'Event';
        if (!empty($object)) {
            $object = $object[0];
            if (
                $scope !== 'view' &&
                !$this->_isSiteAdmin() &&
                !$object['Event']['orgc_id'] != $this->Auth->user('org_id')
            ) {
                throw new MethodNotAllowedException(__('Invalid Target.'));
            }
        } else {
            $type = 'Attribute';
            $object = $this->Event->Attribute->fetchAttributes(
                $this->Auth->user(),
                array(
                    'conditions' => array(
                        'Attribute.uuid' => $object_uuid
                    ),
                    'flatten' => 1
                )
            );
            if (!empty($object)) {
                $object = $object[0];
                if (
                    $scope !== 'view' &&
                    !$this->_isSiteAdmin() &&
                    !$object['Event']['orgc_id'] != $this->Auth->user('org_id')
                ) {
                    throw new MethodNotAllowedException(__('Invalid Target.'));
                }
            } else {
                throw new MethodNotAllowedException(__('Invalid Target.'));
            }
        }
        return $object;
    }


    public function clean()
    {
        $dataSourceConfig = ConnectionManager::getDataSource('default')->config;
        $dataSource = $dataSourceConfig['datasource'];
        $expire = date('Y-m-d H:i:s', time());
        if ($dataSource == 'Database/Mysql') {
            $sql = 'DELETE FROM bruteforces WHERE `expire` <= "' . $expire . '";';
        } elseif ($dataSource == 'Database/Postgres') {
            $sql = 'DELETE FROM bruteforces WHERE expire <= "' . $expire . '";';
        }
        $this->query($sql);
    }


    public function __construct($id = false, $table = null, $ds = null)
    {
        parent::__construct($id, $table, $ds);
        $this->findMethods['column'] = true;
        if (in_array('phar', stream_get_wrappers())) {
            stream_wrapper_unregister('phar');
        }
    }


    public function escapeField($cell)
    {
        if (!is_string($cell)) {
            return $cell;
        }

        if (in_array($cell[0], $this->startingChars, true)) {
            return $this->escapeChar . $cell;
        }

        return $cell;
    }

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.


    public function testGetEscapeChar()
    {
        $this->assertEquals("'", $this->cleanCSV->getEscapeChar());
    }


        return openssl_random_pseudo_bytes($length);
    } else {
        $pr_bits = '';
        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, $length);
            @fclose($fp);
        } else {
            $pr_bits = substr(rand(time()).rand(time()), 0, $length);
        }
        return $pr_bits;
    }
}

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


    public function create_file() {
        if (!AuthUser::hasPermission('file_manager_mkfile')) {
            Flash::set('error', __('You do not have sufficient permissions to create a file.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $data = $_POST['file'];

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

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


function htmlContextCleaner($input) {
    $bad_chars = array("<", ">");
    $safe_chars = array("<", ">");
    $output = str_replace($bad_chars, $safe_chars, $input);

    return stripslashes($output);
}


        function RandomCompat_strlen($binary_string)
        {
            if (!is_string($binary_string)) {
                throw new TypeError(
                    'RandomCompat_strlen() expects a string'
                );
            }

            return mb_strlen($binary_string, '8bit');
        }

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.


function url_check_format($url)
{
  if (strpos($url, '"') !== false)
  {
    return false;
  }

  if (strncmp($url, 'http://', 7) !== 0 and strncmp($url, 'https://', 8) !== 0)
  {
    return false;
  }

  return filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED)!==false;
}

The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.


$user = db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($check['user']), 'username');
			form_alternate_row('line' . $check['id']);
			$name = get_data_source_title($check['datasource']);
			$title = $name;
			if (strlen($name) > 50) {
				$name = substr($name, 0, 50);
			}
			form_selectable_cell('' . html_escape($name) . '', $check['id']);
			form_selectable_ecell($user, $check['id']);
			form_selectable_cell(date('F j, Y, G:i', $check['started']), $check['id']);
			form_selectable_ecell($check['datasource'], $check['id']);
			form_selectable_cell(debug_icon(($check['done'] ? (strlen($issue_line) ? 'off' : 'on' ) : '')), $check['id'], '', 'center');
			form_selectable_cell(debug_icon($info['rrd_writable']), $check['id'], '', 'center');
			form_selectable_cell(debug_icon($info['rrd_exists']), $check['id'], '', 'center');
			form_selectable_cell(debug_icon($info['active']), $check['id'], '', 'center');
			form_selectable_cell(debug_icon($info['rrd_match']), $check['id'], '', 'center');
			form_selectable_cell(debug_icon($info['valid_data']), $check['id'], '', 'center');
			form_selectable_cell(debug_icon(($info['rra_timestamp2'] != '' ? 1 : '')), $check['id'], '', 'center');
			form_selectable_cell('' . html_escape(strlen(trim($issue_line)) ? $issue_line : __('<none>')) . '', $check['id']);
			form_checkbox_cell($check['id'], $check['id']);
			form_end_row();
		}
	}else{


function form_confirm_buttons($action_url, $cancel_url) {
	global $config;
	?>

			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $cancel_url, ENT_QUOTES);?>")' value='<?php print __esc('Cancel');?>'>
			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $action_url . '&confirm=true', ENT_QUOTES);?>")' value='<?php print __esc('Delete');?>'>

<?php }


		} elseif (strtolower($icon) == 'desc') {
			$icon = 'fa fa-sort-desc';
		} else {
			$icon = 'fa fa-unsorted';
		}

		if (($db_column == '') || (substr_count($db_column, 'nosort'))) {
			print '<th ' . ($tip != '' ? "title='" . html_escape($tip) . "'":'') . " class='$nohide $align' " . ((($i+1) == count($header_items)) ? "colspan='$last_item_colspan' " : '') . '>' . $display_text . "</th>\n";


    public function onRouteStartup(Enlight_Controller_EventArgs $args)
    {
        $request = $args->getRequest();

        if (str_starts_with($request->getPathInfo(), '/backend')
            || str_starts_with($request->getPathInfo(), '/api/')
        ) {
            return;
        }

        $shop = $this->getShopByRequest($request);

        if (!$shop->getHost()) {
            $shop->setHost($request->getHttpHost());
        }
        if (!$shop->getBaseUrl()) {
            $preferBasePath = $this->get(Shopware_Components_Config::class)->get('preferBasePath');
            $shop->setBaseUrl($preferBasePath ? $request->getBasePath() : $request->getBaseUrl());
        }
        if (!$shop->getBasePath()) {
            $shop->setBasePath($request->getBasePath());
        }

        // Read original base path for resources
        $request->getBasePath();
        $request->setBaseUrl($shop->getBaseUrl());

        // Update path info
        $request->setPathInfo($this->createPathInfo($request, $shop));

        $host = $request->getHeader('X_FORWARDED_HOST');
        if ($host !== null && $host === $shop->getHost()) {
            // If the base path is null, set it to empty string. Otherwise the request will try to assemble the base path. On a reverse proxy setup with varnish this will fail on virtual URLs like /en
            // The X-Forwarded-Host header is only set in such environments
            if ($shop->getBasePath() === null) {
                $shop->setBasePath('');
            }

            $request->setSecure();
            $request->setBasePath($shop->getBasePath());
            $request->setBaseUrl($shop->getBaseUrl());
            $request->setHttpHost($shop->getHost());
        }

        $this->validateShop($shop);
        $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);
    }

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.


    protected function getShopByRequest(Request $request)
    {
        $repository = $this->get(ModelManager::class)->getRepository(Shop::class);

        $shop = null;
        if ($request->getPost('__shop') !== null) {
            $shop = $repository->getActiveById($request->getPost('__shop'));
        }

        if ($shop === null && $request->getCookie('shop') !== null) {
            $shop = $repository->getActiveById($request->getCookie('shop'));
        }

        if ($shop && $request->getCookie('shop') !== null && $request->getPost('__shop') === null) {
            $requestShop = $repository->getActiveByRequest($request);
            if ($requestShop !== null && $shop->getId() !== $requestShop->getId() && $shop->getBaseUrl() !== $requestShop->getBaseUrl()) {
                $shop = $requestShop;
            }
        }

        if ($shop === null) {
            $shop = $repository->getActiveByRequest($request);
        }

        if ($shop === null) {
            $shop = $repository->getActiveDefault();
        }

        return $shop;
    }


    public function setLinks($links)
    {
        $return = $this->setOneToMany($links, Link::class, 'links', 'container');
        $this->setType(self::TYPE_LINKS);

        return $return;
    }


    public function setContainer($container)
    {
        $this->container = $container;
        $container->setType(Container::TYPE_PRODUCTS);
    }


    private function checkAuthenticationTag() {
        if (hash_equals($this->authentication_tag, $this->calculateAuthenticationTag())) {
            return true;
        } else {
            throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');
        }
    }

Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.


    function selectObjects($table, $where = null, $orderby = null) {
        if ($where == null)
            $where = "1";
        else
            $where = $this->injectProof($where);
        if ($orderby == null)
            $orderby = '';
        else
            $orderby = "ORDER BY " . $orderby;

        $res = @mysqli_query($this->connection, "SELECT * FROM `" . $this->prefix . "$table` WHERE $where $orderby");
        if ($res == null)
            return array();
        $objects = array();
        for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)
            $objects[] = mysqli_fetch_object($res);
        return $objects;
    }


    public function permissions_all() {
        //set the permissions array
        $perms = array();
        foreach ($this->permissions as $perm => $name) {
            if (!in_array($perm, $this->remove_permissions)) $perms[$perm] = $name;
        }
        $perms = array_merge($perms, $this->m_permissions, $this->add_permissions, $this->manage_permissions);
        return $perms;
    }


    function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {

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


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


$rst[$key] = self::parseAndTrim($st, $unescape);
            }
            return $rst;
        }

        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace('"',""",$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","’",$str);
        $str = str_replace("‘","‘",$str);
        $str = str_replace("®","®",$str);
        $str = str_replace("–","-", $str);
        $str = str_replace("—","—", $str);
        $str = str_replace("”","”", $str);
        $str = str_replace("“","“", $str);
        $str = str_replace("¼","¼",$str);
        $str = str_replace("½","½",$str);
        $str = str_replace("¾","¾",$str);
		$str = str_replace("™","™", $str);
		$str = trim($str);

        if ($unescape) {
			$str = stripcslashes($str);
		} else {
	        $str = addslashes($str);
        }

        return $str;
    }

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.


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


static function convertXMLFeedSafeChar($str) {
		$str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace("
","",$str);
        $str = str_replace(""",'"',$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","'",$str);
        $str = str_replace("‘","'",$str);
        $str = str_replace("®","",$str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("”",'"', $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("“",'"', $str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


	public function update() {
        global $user;

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


    public function activate_address()
    {
        global $db, $user;

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


	public function delete() {
	    global $user;

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


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

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


    public function toolbar() {
//        global $user;

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

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

        // sort the top level menus alphabetically by filename
		ksort($menu);
		$sorted = array();
		foreach($menu as $m) $sorted[] = $m;

        // slingbar position
        if (isset($_COOKIE['slingbar-top'])){
            $top = $_COOKIE['slingbar-top'];
        } else {
            $top = SLINGBAR_TOP;
        }

		assign_to_template(array(
            'menu'=>(bs3()) ? $sorted : json_encode($sorted),
            "top"=>$top
        ));
    }


    function reset_stats() {
//        global $db;

        // reset the counters
//        $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');
        banner::resetImpressions();
//        $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');
        banner::resetClicks();

        // let the user know we did stuff.
        flash('message', gt("Banner statistics reset."));
        expHistory::back();
    }


                $banner->increaseImpressions();
            }
        }

        // assign banner to the template and show it!
        assign_to_template(array(
            'banners'=>$banners
        ));
    }


	public function approve_toggle() {
	    if (empty($this->params['id'])) return;

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

	    $comment = new expComment($this->params['id']);
	    $comment->approved = $comment->approved == 1 ? 0 : 1;
	    if ($comment->approved) {
		    $this->sendApprovalNotification($comment,$this->params);
	    }
	    $comment->save();
	    expHistory::back();
	}


            $comments->records[$key]->avatar = $db->selectObject('user_avatar',"user_id='".$record->poster."'");
        }

        if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);
        // eDebug($sql, true);

        // count the unapproved comments
        if ($require_approval == 1 && $user->isAdmin()) {
            $sql  = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';
            $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';
            $sql .= 'WHERE cnt.content_id='.$this->params['content_id']." AND cnt.content_type='".expString::escape($this->params['content_type'])."' ";
            $sql .= 'AND com.approved=0';
            $unapproved = $db->countObjectsBySql($sql);
        } else {
            $unapproved = 0;
        }

        $this->config = $this->params['config'];
        $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');
        $ratings = !empty($this->params['ratings']) ? true : false;

        assign_to_template(array(
            'comments'=>$comments,
            'config'=>$this->params['config'],
            'unapproved'=>$unapproved,
			'content_id'=>$this->params['content_id'],
			'content_type'=>$this->params['content_type'],
			'user'=>$user,
			'hideform'=>$this->params['hideform'],
			'hidecomments'=>$this->params['hidecomments'],
			'title'=>$this->params['title'],
			'formtitle'=>$this->params['formtitle'],
            'type'=>$type,
            'ratings'=>$ratings,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
		));
	}


	public function approve() {
	    expHistory::set('editable', $this->params);

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

	    if (empty($this->params['id'])) {
	        flash('error', gt('No ID supplied for comment to approve'));
	        expHistory::back();
	    }

	    $comment = new expComment($this->params['id']);
	    assign_to_template(array(
            'comment'=>$comment
        ));
	}


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


   	function show() {
//        assign_to_template(array('record'=>$record,'tag'=>$tag));  //FIXME $record & $tag are undefined
    }


    public function approve() {
        expHistory::set('editable', $this->params);

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

        if (empty($this->params['id'])) {
            flash('error', gt('No ID supplied for note to approve'));
            $lastUrl = expHistory::getLast('editable');
        }

        $simplenote = new expSimpleNote($this->params['id']);
        assign_to_template(array(
            'simplenote'=>$simplenote,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'tab'=>$this->params['tab']
        ));
    }


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


    function delete_option_master() {
        global $db;

        $masteroption = new option_master($this->params['id']);

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


    public function update_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);
        // find required shipping method if needed
        if ($this->params['required_shipping_calculator_id'] > 0) {
            $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];
        } else {
            $this->params['required_shipping_calculator_id'] = 0;
        }

        $discount->update($this->params);
        expHistory::back();
    }


    function configure() {
        expHistory::set('editable', $this->params);
        // little bit of trickery so that that categories can have their own configs

        $this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
        $this->config = $config->config;
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);
        $views = expTemplate::get_config_templates($this, $this->loc);

        $gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all');

        assign_to_template(array(
            'config'=>$this->config,
            'pullable_modules'=>$pullable_modules,
            'views'=>$views,
            'countries'=>$countries,
            'regions'=>$regions,
            'title'=>static::displayname()
        ));
    }


    function update_option_master() {
        global $db;

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $opt = new option_master($id);
        $oldtitle = $opt->title;

        $opt->update($this->params);

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $opt->title) {

        }$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);

        expHistory::back();
    }


	 function manage_upcharge() {
		$this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
		$this->config = $config->config;

		$gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all',null,'rank asc,name asc');
        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions,
            'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
        ));
	 }


	 function update_upcharge() {
        $this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
		$this->config = $config->config;

		//This will make sure that only the country or region that given a rate value will be saved in the db
		$upcharge = array();
		foreach($this->params['upcharge'] as $key => $item) {
			if(!empty($item)) {
				$upcharge[$key] = $item;
			}
		}
		$this->config['upcharge'] = $upcharge;

        $config->update(array('config'=>$this->config));
        flash('message', gt('Configuration updated'));
        expHistory::back();
    }


      public function edit_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);

        //grab all user groups
        $group = new group();

        //create two 'default' groups:
        $groups = array(
                -1 => 'ALL LOGGED IN USERS',
                -2 => 'ALL NON-LOGGED IN USERS'
                );
        //loop our groups and append them to the array
       // foreach ($group->find() as $g){
       //this is a workaround for older code. Use the previous line if possible:
       $allGroups = group::getAllGroups();
       if (count($allGroups))
       {
           foreach ($allGroups as $g)
           {
                $groups[$g->id] = $g->name;
           };
       }
       //find our selected groups for this discount already
       // eDebug($discount);
       $selected_groups = array();
       if (!empty($discount->group_ids))
       {
            $selected_groups = expUnserialize($discount->group_ids);
       }

       if ($discount->minimum_order_amount == "") $discount->minimum_order_amount = 0;
       if ($discount->discount_amount == "") $discount->discount_amount = 0;
       if ($discount->discount_percent == "") $discount->discount_percent = 0;

        // get the shipping options and their methods
        $shipping_services = array();
        $shipping_methods = array();
//        $shipping = new shipping();
        foreach (shipping::listAvailableCalculators() as $calcid=>$name) {
            if (class_exists($name)) {
                $calc = new $name($calcid);
                $shipping_services[$calcid] = $calc->title;
                $shipping_methods[$calcid] = $calc->availableMethods();
            }
        }

       assign_to_template(array(
           'discount'=>$discount,
           'groups'=>$groups,
           'selected_groups'=>$selected_groups,
           'shipping_services'=>$shipping_services,
           'shipping_methods'=>$shipping_methods
       ));
    }


    public function search() {
//        global $db, $user;
        global $db;

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


    function edit_order_item() {
        $oi = new orderitem($this->params['id'], true, true);
        if (empty($oi->id)) {
            flash('error', gt('Order item doesn\'t exist.'));
            expHistory::back();
        }
        $oi->user_input_fields = expUnserialize($oi->user_input_fields);
        $params['options'] = $oi->opts;
        $params['user_input_fields'] = $oi->user_input_fields;
        $oi->product           = new product($oi->product->id, true, true);
        if ($oi->product->parent_id != 0) {
            $parProd = new product($oi->product->parent_id);
            //$oi->product->optiongroup = $parProd->optiongroup;
            $oi->product = $parProd;
        }
        //FIXME we don't use selectedOpts?
//        $oi->selectedOpts = array();
//        if (!empty($oi->opts)) {
//            foreach ($oi->opts as $opt) {
//                $option = new option($opt[0]);
//                $og     = new optiongroup($option->optiongroup_id);
//                if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))
//                    $oi->selectedOpts[$og->id] = array($option->id);
//                else
//                    array_push($oi->selectedOpts[$og->id], $option->id);
//            }
//        }
        //eDebug($oi->selectedOpts);

        assign_to_template(array(
            'oi' => $oi,
            'params' => $params
        ));
    }


function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params);
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);
            expHistory::back();
        }
    }


    public function search_external() {
//        global $db, $user;
        global $db;

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


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


	function manage () {
	    expHistory::set('viewable', $this->params);

		$vendor = new vendor();
		$vendors = $vendor->find('all');
		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		assign_to_template(array(
            'purchase_orders'=>$purchase_orders,
            'vendors' => $vendors,
            'vendor_id' => @$this->params['vendor']
        ));
	}


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

		$vendor->update($this->params['vendor']);
        expHistory::back();
    }


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


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


    public function saveconfig() {
        global $db;

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


	public function editspeed() {
        global $db;

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

    }


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


    static function displayname() {
        return gt("e-Commerce Category Manager");
    }


    function delete() {
        global $db;

        if (empty($this->params['id'])) return false;
        $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);
        $product = new $product_type($this->params['id'], true, false);
        //eDebug($product_type);
        //eDebug($product, true);
        //if (!empty($product->product_type_id)) {
        //$db->delete($product_type, 'id='.$product->product_id);
        //}

        $db->delete('option', 'product_id=' . $product->id . " AND optiongroup_id IN (SELECT id from " . $db->prefix . "optiongroup WHERE product_id=" . $product->id . ")");
        $db->delete('optiongroup', 'product_id=' . $product->id);
        //die();
        $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type="' . $product_type . '"');

        if ($product->product_type == "product") {
            if ($product->hasChildren()) {
                $this->deleteChildren();
            }
        }

        $product->delete();

        flash('message', gt('Product deleted successfully.'));
        expHistory::back();
    }


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

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


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


    function edit() {
        global $template;

        parent::edit();
        $allforms = array();
        $allforms[""] = gt('Disallow Feedback');
        // calculate which event date is the one being edited
        $event_key = 0;
        foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {
       	    if ($d->id == $this->params['date_id']) $event_key = $key;
       	}

        assign_to_template(array(
            'allforms'     => array_merge($allforms, expTemplate::buildNameList("forms", "event/email", "tpl", "[!_]*")),
            'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,
            'event_key'    => $event_key,
        ));
    }


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


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


    function searchName() {
        return gt("Calendar Event");
    }


                $emails[$u->email] = trim(user::getUserAttribution($u->id));
            }


            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }


                        $body = str_replace(array("\n"), "<br />", $body);
                    } else {
                        // It's going elsewhere (doesn't like quoted-printable)
                        $body = str_replace(array("\n"), " -- ", $body);
                    }
                    $title = $items[$i]->title;

                    $msg .= "BEGIN:VEVENT\n";
                    $msg .= $dtstart . $dtend;
                    $msg .= "UID:" . $items[$i]->date_id . "\n";
                    $msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
                    if ($title) {
                        $msg .= "SUMMARY:$title\n";
                    }
                    if ($body) {
                        $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
                    }
                    //	if($link_url) { $msg .= "URL: $link_url\n";}
                    if (!empty($this->config['usecategories'])) {
                        if (!empty($items[$i]->expCat[0]->title)) {
                            $msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
                        } else {
                            $msg .= "CATEGORIES:".$this->config['uncat']."\n";
                        }
                    }
                    $msg .= "END:VEVENT\n";
                }


    public static function canImportData() {
        return true;
    }