/** * Configure after successfull mount. * * @return void * @author Dmitry (dio) Levashov **/ protected function configure() { $this->aroot = realpath($this->root); $root = $this->stat($this->root); if ($this->options['quarantine']) { $this->attributes[] = array('pattern' => '~^' . preg_quote(DIRECTORY_SEPARATOR . $this->options['quarantine']) . '$~', 'read' => false, 'write' => false, 'locked' => true, 'hidden' => true); } // chek thumbnails path if ($this->options['tmbPath']) { $this->options['tmbPath'] = strpos($this->options['tmbPath'], DIRECTORY_SEPARATOR) === false ? $this->root . DIRECTORY_SEPARATOR . $this->options['tmbPath'] : $this->_normpath($this->options['tmbPath']); } parent::configure(); // if no thumbnails url - try detect it if ($root['read'] && !$this->tmbURL && $this->URL) { if (strpos($this->tmbPath, $this->root) === 0) { $this->tmbURL = $this->URL . str_replace(DIRECTORY_SEPARATOR, '/', substr($this->tmbPath, strlen($this->root) + 1)); if (preg_match("|[^/?&=]\$|", $this->tmbURL)) { $this->tmbURL .= '/'; } } } // check quarantine dir if (!empty($this->options['quarantine'])) { $this->quarantine = $this->root . DIRECTORY_SEPARATOR . $this->options['quarantine']; if (!is_dir($this->quarantine) && !$this->_mkdir($this->root, $this->options['quarantine']) || !is_writable($this->quarantine)) { $this->archivers['extract'] = array(); $this->disabled[] = 'extract'; } } else { $this->archivers['extract'] = array(); $this->disabled[] = 'extract'; } }
protected function getGraphsFromFiles(array $files, array $exclude, CFGParser $parser) { $excludeParts = []; foreach ($exclude as $part) { $excludeParts[] = preg_quote($part); } $part = implode('|', $excludeParts); $excludeRegex = "(((\\.({$part})(\$|/))|((^|/)({$part})(\$|/))))"; $graphs = []; foreach ($files as $file) { if (is_file($file)) { $local = [$file]; } elseif (is_dir($file)) { $it = new \CallbackFilterIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file)), function ($file) use($excludeRegex) { if (preg_match($excludeRegex, $file->getPathName())) { return false; } return $file->isFile(); }); $local = []; foreach ($it as $file) { $local[] = $file->getPathName(); // since __toString would be too difficult... } } else { throw new \RuntimeException("Error: {$file} is not a file or directory"); } foreach ($local as $file) { echo "Analyzing {$file}\n"; $graphs[$file] = $parser->parse(file_get_contents($file), $file); } } return $graphs; }
/** * Processes the standard headers that are not subdivided into other structs. */ protected function processStandardHeaders() { $req = $this->request; $req->date = isset($_SERVER['REQUEST_TIME']) ? new DateTime("@{$_SERVER['REQUEST_TIME']}") : new DateTime(); if (isset($_SERVER['REQUEST_METHOD'])) { switch ($_SERVER['REQUEST_METHOD']) { case 'POST': $req->protocol = 'http-post'; break; case 'PUT': $req->protocol = 'http-put'; break; case 'DELETE': $req->protocol = 'http-delete'; break; default: $req->protocol = 'http-get'; } } $req->host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain'); $req->uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; // remove the query string from the URI $req->uri = preg_replace('@\\?.*$@', '', $req->uri); // url decode the uri $req->uri = urldecode($req->uri); // remove the prefix from the URI $req->uri = preg_replace('@^' . preg_quote($this->properties['prefix']) . '@', '', $req->uri); $req->requestId = $req->host . $req->uri; $req->referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; $req->variables =& $_REQUEST; if ($req->protocol == 'http-put') { $req->body = file_get_contents("php://input"); } }
public function __construct(ProcessorInterface $processor = null, $startSep = '---', $endSep = '---') { $this->startSep = $startSep; $this->endSep = $endSep; $this->processor = $processor ?: new YamlProcessor(); $this->regexp = '{^(?:' . preg_quote($startSep) . ")[\r\n|\n]*(.*?)[\r\n|\n]+(?:" . preg_quote($endSep) . ")[\r\n|\n]*(.*)\$}s"; }
/** * Get column name * @param string $name * @return string */ protected function getColumnFromTable($name) { if ($this->table != '%s' && preg_match('(^' . str_replace('%s', '(.*)', preg_quote($this->table)) . '$)', $name, $match)) { return $match[1]; } return $name; }
public function hookActionAdminControllerSetMedia($params) { $admin_webpath = str_ireplace(_PS_ROOT_DIR_, '', _PS_ADMIN_DIR_); $admin_webpath = preg_replace('/^' . preg_quote(DIRECTORY_SEPARATOR, '/') . '/', '', $admin_webpath); $this->context->controller->addJS(array(_PS_JS_DIR_ . 'vendor/d3.v3.min.js', __PS_BASE_URI__ . $admin_webpath . '/themes/' . $this->context->employee->bo_theme . '/js/vendor/nv.d3.min.js')); $this->context->controller->addCSS(__PS_BASE_URI__ . $admin_webpath . '/themes/' . $this->context->employee->bo_theme . '/css/vendor/nv.d3.css'); }
/** * Constructor. * * @param \Iterator $iterator The Iterator to filter * @param array $directories An array of directories to exclude */ public function __construct(\Iterator $iterator, array $directories) { foreach ($directories as $directory) { $this->patterns[] = '#(^|/)' . preg_quote($directory, '#') . '(/|$)#'; } parent::__construct($iterator); }
public static function clean($url, $toLower = true, $spacer = '-') { if ($toLower == true) { $url = strtolower($url); } // International umlauts $url = str_replace(array('á', 'à', 'â', 'Á', 'À', 'Â'), 'a', $url); $url = str_replace(array('ç', 'Ç'), 'c', $url); $url = str_replace(array('é', 'è', 'ë', 'ê', 'É', 'È', 'Ë', 'Ê'), 'e', $url); $url = str_replace(array('í', 'ì', 'î', 'ï', 'Í', 'Ì', 'Î', 'Ï'), 'i', $url); $url = str_replace(array('ó', 'ò', 'ô', 'Ó', 'Ò', 'Ô'), 'o', $url); $url = str_replace(array('ú', 'ù', 'û', 'Ú', 'Ù', 'Û'), 'u', $url); // German umlauts $url = str_replace(array('ä', 'Ä'), 'ae', $url); $url = str_replace(array('ö', 'Ö'), 'oe', $url); $url = str_replace(array('ü', 'Ü'), 'ue', $url); $url = str_replace(array('ß'), 'ss', $url); // Replace some special chars with delimiter $url = preg_replace('/[\\+\\s\\r\\n\\t]+/', $spacer, $url); // Replace multiple delimiter chars with only one char $url = preg_replace('/[' . preg_quote($spacer, '/') . ']+/', $spacer, $url); // Remove html and other special chars $url = preg_replace(array('/<[^>]*>/', '/[^a-z0-9\\-\\._' . preg_quote($spacer, '/') . ']/i'), '', $url); return $url; }
function __construct($connect_options) { $this->url = $connect_options['url']; $this->is_require_auth = $connect_options['require_auth']; if ($this->is_require_auth) { $this->login = $connect_options['login']; $this->password = $connect_options['password']; } $this->connect_timeout = isset($connect_options['connect_timeout']) ? $connect_options['connect_timeout'] : 5; $this->timeout = isset($connect_options['timeout']) ? $connect_options['timeout'] : 5; $this->exclude = explode(';', $connect_options['exclude']); $parse_format = $connect_options['parse_format']; $this->matches = preg_split('/%\\w+/u', $parse_format); $matches_symbol = array(); preg_match_all('/(%\\w+)/', $parse_format, $matches_symbol); $symbol = reset($matches_symbol[0]); $this->regex = '/'; $this->tags = array(); foreach ($this->matches as $key => $value) { if (!empty($value)) { $this->regex .= preg_quote($value); continue; } $this->tags[] = substr($symbol, 1); $symbol = next($matches_symbol[0]); if ($symbol === false) { $this->regex .= '(.+)'; break; } else { $this->regex .= '(.+?)'; } } $this->regex .= '/u'; }
/** * With lots of various rules we created 4 various rulesets for operators. If one * of the tokens or content is found we use the given regex on the joined array. * * @param Testable $testable The testable object * @return void */ public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); foreach ($this->inspector as $inspector) { if (isset($inspector['tokens'])) { $byToken = $testable->findAll($inspector['tokens']); } else { $byToken = array(); } if (isset($inspector['content'])) { $byContent = $testable->findAllContent($inspector['content']); } else { $byContent = array(); } foreach (array_merge($byToken, $byContent) as $id) { $token = $tokens[$id]; $isPHP = $testable->isPHP($token['line']); if ($isPHP && empty($token['isString'])) { $pattern = String::insert($inspector['regex'], array('content' => preg_quote($token['content'], "/"))); $firstId = $id - $inspector['relativeTokens']['before']; $firstId = $firstId < 0 ? 0 : $firstId; $length = $inspector['relativeTokens']['length']; $inspectTokens = array_slice($tokens, $firstId, $length); $html = null; foreach ($inspectTokens as $htmlToken) { $html .= $htmlToken['content']; } if (preg_match($pattern, $html) === 0) { $this->addViolation(array('message' => String::insert($inspector['message'], $token), 'line' => $token['line'])); } } } } }
/** * 生成敏感词缓存 filter:替换关键字,banned:禁止关键字,mod:审核关键字 * @return string 关键词数据 */ public function censorword_cache() { $banned = $mod = array(); $bannednum = $modnum = 0; $data = array('filter' => array(), 'banned' => '', 'mod' => ''); foreach ($this->select() as $censor) { if (preg_match('/^\\/(.+?)\\/$/', $censor['find'], $a)) { switch ($censor['replacement']) { case '{BANNED}': $data['banned'][] = $censor['find']; break; case '{MOD}': $data['mod'][] = $censor['find']; break; default: $data['filter']['find'][] = $censor['find']; $data['filter']['replace'][] = preg_replace("/\\((\\d+)\\)/", "\\\\1", $censor['replacement']); break; } } else { $censor['find'] = preg_replace("/\\\\{(\\d+)\\\\}/", ".{0,\\1}", preg_quote($censor['find'], '/')); switch ($censor['replacement']) { case '{BANNED}': $banned[] = $censor['find']; $bannednum++; if ($bannednum == 1000) { $data['banned'][] = '/(' . implode('|', $banned) . ')/i'; $banned = array(); $bannednum = 0; } break; case '{MOD}': $mod[] = $censor['find']; $modnum++; if ($modnum == 1000) { $data['mod'][] = '/(' . implode('|', $mod) . ')/i'; $mod = array(); $modnum = 0; } break; default: $data['filter']['find'][] = '/' . $censor['find'] . '/i'; $data['filter']['replace'][] = $censor['replacement']; break; } } } if ($banned) { $data['banned'][] = '/(' . implode('|', $banned) . ')/i'; } if ($mod) { $data['mod'][] = '/(' . implode('|', $mod) . ')/i'; } //过滤关键词数据 F("Censor_words", $data); //分类数据 $typedata = M("Terms")->where(array("module" => "censor"))->select(); F("Censor_type", $typedata); return $data; }
* * @package Smarty * @subpackage PluginsShared */ if (!function_exists('smarty_mb_str_replace')) { /** * Multibyte string replace * * @param string $search the string to be searched * @param string $replace the replacement string * @param string $subject the source string * @param int &$count number of matches found * @return string replaced string * @author Rodney Rehm */ function smarty_mb_str_replace($search, $replace, $subject, &$count = 0) { if (!is_array($search) && is_array($replace)) { return false; } if (is_array($subject)) { // call mb_replace for each single string in $subject foreach ($subject as &$string) { $string =& smarty_mb_str_replace($search, $replace, $string, $c); $count += $c; } } elseif (is_array($search)) { if (!is_array($replace)) { foreach ($search as &$string) { $subject = smarty_mb_str_replace($string, $replace, $subject, $c); $count += $c; } } else { $n = max(count($search), count($replace));
/** * Quote regular expression characters. * * @param string $value * @param string $delimiter * * @return string */ public function quote($value, $delimiter = '/') { if (!isset($value)) { return null; } return preg_quote($value, $delimiter); }
/** * Tests the fetchButton method * * @return void * * @since 3.0 */ public function testFetchButton() { $name = 'jdotorg'; $text = 'Joomla.org'; $url = 'http://www.joomla.org'; $this->assertRegExp('#<button onclick="location.href=\'' . preg_quote($url, '#') . '\';" class="btn btn-small">\\s*' . '<span class="icon-' . preg_quote($name, '#') . '"></span>\\s+' . preg_quote($text, '#') . '\\s*' . '</button>\\s*#', $this->object->fetchButton('Link', $name, $text, $url)); }
/** * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the * link is trimmed of leading and trailing slashes before returning to ensure consistency. * * @return string */ public static function get_homepage_link() { if (!self::$cached_homepage_link) { // TODO Move to 'homepagefordomain' module if (class_exists('HomepageForDomainExtension')) { $host = str_replace('www.', null, $_SERVER['HTTP_HOST']); $SQL_host = Convert::raw2sql($host); $candidates = DataObject::get('SiteTree', "\"HomepageForDomain\" LIKE '%{$SQL_host}%'"); if ($candidates) { foreach ($candidates as $candidate) { if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) { self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/'); } } } } if (!self::$cached_homepage_link) { // TODO Move to 'translatable' module if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) { self::$cached_homepage_link = $link; } else { self::$cached_homepage_link = self::get_default_homepage_link(); } } } return self::$cached_homepage_link; }
function fnmatch($pattern, $string, $flags = 0) { $modifiers = null; $transforms = array('\\*' => '.*', '\\?' => '.', '\\[\\!' => '[^', '\\[' => '[', '\\]' => ']', '\\.' => '\\.', '\\' => '\\\\'); // Forward slash in string must be in pattern: if ($flags & FNM_PATHNAME) { $transforms['\\*'] = '[^/]*'; } // Back slash should not be escaped: if ($flags & FNM_NOESCAPE) { unset($transforms['\\']); } // Perform case insensitive match: if ($flags & FNM_CASEFOLD) { $modifiers .= 'i'; } // Period at start must be the same as pattern: if ($flags & FNM_PERIOD) { if (strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) { return false; } } $pattern = '~^' . strtr(preg_quote($pattern, '~'), $transforms) . '$~' . $modifiers; return (bool) preg_match($pattern, $string); }
function dir_tree($dir, $EXT, $subDir = true) { $path = array(); $stack[] = $dir; while ($stack) { $thisdir = array_pop($stack); if ($dircont = scandir($thisdir)) { $i = 0; while (isset($dircont[$i])) { if (!in_array($dircont[$i], array('.', '..', '.svn', '.info'))) { $current_file = $thisdir . $dircont[$i]; if (is_file($current_file)) { foreach ($EXT as $FILEXT) { if (preg_match("/\\." . preg_quote($FILEXT) . "\$/i", $current_file)) { $path[] = str_replace(ROOT_PATH, '', str_replace('\\', '/', $current_file)); break; } } } elseif ($subDir && is_dir($current_file)) { $stack[] = $current_file . "/"; } } $i++; } } } return $path; }
/** * Show sites * * ## OPTIONS * * @subcommand list * @alias show */ public function show($args, $assoc_args) { $sites = SiteFactory::instance(); $data = array(); foreach ($sites as $site) { $report = array('name' => $site->getName()); $fields = Input::optional('fields', $assoc_args, 'name,framework,service_level,id'); $filter = Input::optional('filter', $assoc_args, false); if ($filter) { if (!strpos($filter, ":")) { Terminus::error("Improperly formatted filter"); } $filter = explode(':', $filter); list($filter_field, $filter_value) = $filter; if (!preg_match("#" . preg_quote($filter_value) . "#", $site->info($filter_field))) { // skip rows not matching our filter continue; } } if ($fields) { $fields = explode(',', $fields); foreach ($fields as $field) { $report[$field] = $site->info($field); } } else { $info = $site->info(); foreach ($info as $key => $value) { $report[$key] = $value; } } $data[] = $report; } $this->handleDisplay($data); return $data; }
/** * This routine is used for automatically determining the source for an * event that has to be logged. It can determine the source by using either * a trace back depth level for examining the call stack or by using * the name of a file for which the event happened. * * The depth level is used to find the caller file by looking at a * debug_backtrace() array at the given level. The level might not be the * same for all requests, because some logged events will take multiple * steps before hitting the log writing functions (for example the database * error logging will run through an extra function call). * * The file that generated the event can also be passed as the $file * parameter. In that case, the code will directly use that parameter * and not investigate the call stack at all. * * @param $level - The call stack depth at which the event generating * file can be found. * @param $file - The file name of the file that generated the event or * NULL if this file name is unknown. * * @return $source - A string that can be used as the event source. */ function event_logging_find_source($level = 0, $file = NULL) { $source = NULL; $from_module = FALSE; // Determine the file that generated the event. if ($file === NULL) { if (function_exists('debug_backtrace')) { $bt = debug_backtrace(); if (isset($bt[$level]["file"])) { $file = $bt[$level]["file"]; } } } // See if the file belongs to a module. if ($file !== NULL) { $moddir = preg_quote(dirname(dirname(__FILE__)), '!'); if (preg_match("!^{$moddir}/([^/]+)/!", $file, $m)) { $source = $m[1]; $from_module = TRUE; } } // No module found? Then the logging is probably done by a regular // Phorum page. We can use the phorum_page constant as the source here. if ($source === NULL) { if (defined("phorum_page")) { $source = phorum_page; } elseif (defined('PHORUM_ADMIN')) { $source = "admin"; } else { $source = "unknown"; } } return array($source, $from_module); }
protected function initSmilePatterns() { $this->smilePatterns = array(); $this->smileReplaces = array(); $pre = ""; foreach ($this->smiles as $row) { if (preg_match("/\\w\$/", $row["TYPING"])) { $pre .= "|" . preg_quote($row["TYPING"], "/"); } } foreach ($this->smiles as $row) { if ($row["TYPING"] != '' && $row["IMAGE"] != '') { $code = str_replace(array("'", "<", ">"), array("\\'", "<", ">"), $row["TYPING"]); $patt = preg_quote($code, "/"); $code = preg_quote(str_replace(array("\\"), array("\"), $code)); $image = preg_quote(str_replace("'", "\\'", $row["IMAGE"])); $description = preg_quote(htmlspecialcharsbx(str_replace(array("\\"), array("\"), $row["DESCRIPTION"]), ENT_QUOTES), "/"); $patternName = "pattern" . count($this->smilePatterns); $this->smilePatterns[] = "/(?<=^|\\>|[" . $this->wordSeparator . "\\&]" . $pre . ")(?P<" . $patternName . ">{$patt})(?=\$|\\<|[" . $this->wordSeparator . "\\&])/s" . BX_UTF_PCRE_MODIFIER; $this->smileReplaces[$patternName] = array("code" => $code, "image" => $image, "description" => $description, "width" => intval($row["IMAGE_WIDTH"]), "height" => intval($row["IMAGE_HEIGHT"]), "descriptionDecode" => $row["DESCRIPTION_DECODE"] == 'Y' ? true : false); } } usort($this->smilePatterns, function ($a, $b) { return strlen($a) > strlen($b) ? -1 : 1; }); }
public function clear($prefix = '') { $ns = $this->getPrefix() . $prefix; $ns = preg_quote($ns, '/'); $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY); return apc_delete($iter); }
static function shortnameToImage($string) { $replace = array(); $replaceWith = array(); if (self::$imageType == 'png') { foreach (self::$shortcode_replace as $shortname => $unicode) { $replace[] = $shortname; $replaceWith[] = '<img class="emojione" alt="' . substr($shortname, 1, -1) . '" src="' . self::$imagePathPNG . strtoupper($unicode) . '.png"/>'; } $string = str_replace($replace, $replaceWith, $string); if (self::$ascii) { foreach (self::$ascii_replace as $shortname => $unicode) { $string = preg_replace('/(\\s|^)' . preg_quote($shortname, '/') . '(\\s|$|[!,\\.])/i', '$1<img class="emojione" alt="' . substr($shortname, 1, -1) . '" src="' . self::$imagePathPNG . strtoupper($unicode) . '.png"/>$2', $string); } } } else { foreach (self::$shortcode_replace as $shortname => $unicode) { $filename = strtoupper($unicode); $replace[] = $shortname; $replaceWith[] = '<object class="emojione" data="' . self::$imagePathSVG . $filename . '.svg" type="image/svg+xml" alt="' . substr($shortname, 1, -1) . '"><img class="emojione" alt="' . substr($shortname, 1, -1) . '" src="' . self::$imagePathSVG . strtoupper($unicode) . '.svg"/></object>'; } $string = str_replace($replace, $replaceWith, $string); if (self::$ascii) { foreach (self::$ascii_replace as $shortname => $unicode) { $string = preg_replace('/(\\s|^)' . preg_quote($shortname, '/') . '(\\s|$|[!,\\.])/i', '$1<object class="emojione" data="' . self::$imagePathSVG . strtoupper($unicode) . '.svg" type="image/svg+xml" alt="' . substr($shortname, 1, -1) . '"><img class="emojione" alt="' . substr($shortname, 1, -1) . '" src="' . self::$imagePathSVG . strtoupper($unicode) . '.svg"/></object>$2', $string); } } } return $string; }
/** * execute query - show be regarded as private to insulate the rest of * the application from sql differences * @access private */ function query($sql) { global $CONF; if (is_null($this->dblink)) { $this->_connect(); } //been passed more parameters? do some smart replacement if (func_num_args() > 1) { //query contains ? placeholders, but it's possible the //replacement string have ? in too, so we replace them in //our sql with something more unique $q = md5(uniqid(rand(), true)); $sql = str_replace('?', $q, $sql); $args = func_get_args(); for ($i = 1; $i <= count($args); $i++) { $sql = preg_replace("/{$q}/", "'" . preg_quote(mysql_real_escape_string($args[$i])) . "'", $sql, 1); } //we shouldn't have any $q left, but it will help debugging if we change them back! $sql = str_replace($q, '?', $sql); } $this->dbresult = mysql_query($sql, $this->dblink); if (!$this->dbresult) { die("Query failure: " . mysql_error() . "<br />{$sql}"); } return $this->dbresult; }
/** * Parse of HTML line * * @param string $line * @param array $tags [optional] * @return \axy\min\html\helpers\ParseLineResult */ public static function parseLine($line, array $tags = null) { $result = new ParseLineResult(''); while ($line !== '') { if (!preg_match('~^(?<before>.*?)\\<(?<tag>/?[a-z0-9-]+)(?<attr>.*?)?>(?<after>.*?)$~is', $line, $matches)) { $result->append($line); break; } $tag = $matches['tag']; $after = $matches['after']; $tagL = strtolower($matches['tag']); $result->append($matches['before'] . '<' . $tag . $matches['attr'] . '>'); if (isset($tags[$tagL])) { $pattern = '~^(?<before>.*?)(?<tag></' . preg_quote($tagL) . '>)(?<after>.*?)$~is'; if (!preg_match($pattern, $after, $matches)) { $result->tag = $tagL; $result->after = $after; break; } $content = $matches['before']; $content = self::process($content, $tags[$tagL]); $result->append($content . $matches['tag']); $line = $matches['after']; } else { $line = $after; } } if (!$result->tag) { $result->before = rtrim($result->before); } return $result; }
public function executeRawQuery($raw_query) { // NOTE: "[\s<>K]*" allows any number of (properly escaped) comments to // appear prior to the allowed keyword, since this connection escapes // them as "<K>" (above). $keywords = array('INSERT', 'UPDATE', 'DELETE', 'START', 'SAVEPOINT', 'COMMIT', 'ROLLBACK'); $preg_keywords = array(); foreach ($keywords as $key => $word) { $preg_keywords[] = preg_quote($word, '/'); } $preg_keywords = implode('|', $preg_keywords); if (!preg_match('/^[\\s<>K]*(' . $preg_keywords . ')\\s*/i', $raw_query)) { throw new AphrontQueryNotSupportedException("Database isolation currently only supports some queries. You are " . "trying to issue a query which does not begin with an allowed " . "keyword (" . implode(', ', $keywords) . "): '" . $raw_query . "'"); } $this->transcript[] = $raw_query; // NOTE: This method is intentionally simplified for now, since we're only // using it to stub out inserts/updates. In the future it will probably need // to grow more powerful. $this->allResults = array(); // NOTE: We jitter the insert IDs to keep tests honest; a test should cover // the relationship between objects, not their exact insertion order. This // guarantees that IDs are unique but makes it impossible to hard-code tests // against this specific implementation detail. self::$nextInsertID += mt_rand(1, 10); $this->insertID = self::$nextInsertID; $this->affectedRows = 1; }
public function test_interactive() { // Create a gapselect question. $q = test_question_maker::make_question('calculated'); $q->hints = array(new question_hint(1, 'This is the first hint.', FORMAT_HTML), new question_hint(2, 'This is the second hint.', FORMAT_HTML)); $this->start_attempt_at_question($q, 'interactive', 3, 1); $values = $q->vs->get_values(); $this->assertEquals($values, $q->datasetloader->load_values(1)); // Check the initial state. $this->check_current_state(question_state::$todo); $this->check_current_mark(null); $this->check_current_output($this->get_contains_marked_out_of_summary(), $this->get_contains_submit_button_expectation(true), $this->get_does_not_contain_feedback_expectation(), $this->get_does_not_contain_validation_error_expectation(), $this->get_does_not_contain_try_again_button_expectation(), $this->get_no_hint_visible_expectation()); // Submit blank. $this->process_submission(array('-submit' => 1, 'answer' => '')); // Verify. $this->check_current_state(question_state::$invalid); $this->check_current_mark(null); $this->check_current_output($this->get_contains_marked_out_of_summary(), $this->get_contains_submit_button_expectation(true), $this->get_does_not_contain_feedback_expectation(), $this->get_contains_validation_error_expectation(), $this->get_does_not_contain_try_again_button_expectation(), $this->get_no_hint_visible_expectation()); // Sumit something that does not look like a number. $this->process_submission(array('-submit' => 1, 'answer' => 'newt')); // Verify. $this->check_current_state(question_state::$invalid); $this->check_current_mark(null); $this->check_current_output($this->get_contains_marked_out_of_summary(), $this->get_contains_submit_button_expectation(true), $this->get_does_not_contain_feedback_expectation(), $this->get_contains_validation_error_expectation(), new question_pattern_expectation('/' . preg_quote(get_string('invalidnumber', 'qtype_numerical'), '/') . '/'), $this->get_does_not_contain_try_again_button_expectation(), $this->get_no_hint_visible_expectation()); // Now get it right. $this->process_submission(array('-submit' => 1, 'answer' => $values['a'] + $values['b'])); // Verify. $this->check_current_state(question_state::$gradedright); $this->check_current_mark(3); $this->check_current_output($this->get_contains_mark_summary(3), $this->get_does_not_contain_submit_button_expectation(), $this->get_contains_correct_expectation(), $this->get_does_not_contain_validation_error_expectation(), $this->get_no_hint_visible_expectation()); }
private function parseSingle($key) { if (isset($this->parameters[$key])) { return $this->parameters[$key]; } else { if (preg_match("/@" . preg_quote($key) . $this->endPattern . "/", $this->rawDocBlock, $match)) { return TRUE; } else { preg_match_all("/@" . preg_quote($key) . " (.*)" . $this->endPattern . "/U", $this->rawDocBlock, $matches); $size = sizeof($matches[1]); // not found if ($size === 0) { return NULL; } elseif ($size === 1) { return $this->parseValue($matches[1][0]); } else { $this->parameters[$key] = array(); foreach ($matches[1] as $elem) { $this->parameters[$key][] = $this->parseValue($elem); } return $this->parameters[$key]; } } } }
function __construct($id) { $db = Database::getDatabase(); $this->data = $db->querySingle(sprintf("select * from exception_logging where id = %d", $id)); if (!$this->data) { throw new NotFound(); } $this->data['error_info'] = unserialize(base64_decode($this->data['error_info'])); $pr = preg_quote(c()->getValue('report_format', 'app_root'), '#'); if (!$this->data['error_info']['callstack']) { $this->data['error_info']['callstack'] = array(); } $this->data['error_info']['callstack'] = array_merge(array(array('line' => $this->data['error_info']['line'], 'file' => $this->data['error_info']['file'], 'function' => 'throw', 'args' => array())), $this->data['error_info']['callstack']); foreach ($this->data['error_info']['callstack'] as &$csi) { if ($pr) { $csi['base_file'] = preg_replace("#^{$pr}/?#", '', $csi['file']); $csi['file'] = preg_replace("#^{$pr}/?#", '<R>/', $csi['file']); $csi['scm_link'] = $this->getWebSCMLink($csi['base_file'], $csi['line']); } if ($csi['class']) { $csi['call'] = sprintf('%s%s%s(%s)', $csi['class'], $csi['type'], $csi['function'], implode(', ', array_map(array($this, 'formatArgument'), $csi['args']))); } else { $csi['call'] = sprintf('%s(%s)', $csi['function'], implode(', ', array_map(array($this, 'formatArgument'), $csi['args']))); } } if ($fs = c()->getValue('report_format', 'interesting_custom_fields')) { $fs = explode(',', $fs); foreach ($fs as $f) { $this->data[$f] = $this->data['error_info'][$f]; } } }
public function test_informationitem_feedback_description() { // Create a true-false question with correct answer true. $description = test_question_maker::make_question('description'); $this->start_attempt_at_question($description, 'deferredfeedback'); // Check the initial state. $this->check_current_state(question_state::$todo); $this->check_current_mark(null); $this->check_current_output($this->get_contains_question_text_expectation($description), new question_contains_tag_with_attributes('input', array('type' => 'hidden', 'name' => $this->quba->get_field_prefix($this->slot) . '-seen', 'value' => 1)), $this->get_does_not_contain_feedback_expectation()); // Process a submission indicating this question has been seen. $this->process_submission(array('-seen' => 1)); $this->check_current_state(question_state::$complete); $this->check_current_mark(null); $this->check_current_output($this->get_does_not_contain_correctness_expectation(), new question_no_pattern_expectation('/type=\\"hidden\\"[^>]*name=\\"[^"]*seen\\"|name=\\"[^"]*seen\\"[^>]*type=\\"hidden\\"/'), $this->get_does_not_contain_feedback_expectation()); // Finish the attempt. $this->quba->finish_all_questions(); // Verify. $this->check_current_state(question_state::$finished); $this->check_current_mark(null); $this->check_current_output($this->get_contains_question_text_expectation($description), $this->get_contains_general_feedback_expectation($description)); // Process a manual comment. $this->manual_grade('Not good enough!', null, FORMAT_HTML); $this->check_current_state(question_state::$manfinished); $this->check_current_mark(null); $this->check_current_output(new question_pattern_expectation('/' . preg_quote('Not good enough!', '/') . '/')); // Check that trying to process a manual comment with a grade causes an exception. $this->setExpectedException('moodle_exception'); $this->manual_grade('Not good enough!', 1, FORMAT_HTML); }
protected function __construct($config) { if (count($config["db"]) != 4) { throw new \Exception("Le nombre d'arguments n'est pas valable!"); } spl_autoload_register(array(__CLASS__, 'autoload')); self::$config = $config; self::$database = new Core\Db\ConnectPDO(self::$config["db"]); self::$baseUrl = rtrim(dirname($_SERVER['PHP_SELF']), '/.\\'); $route = isset($_GET["r"]) ? $_GET["r"] : $_SERVER["REQUEST_URI"]; $url = parse_url($route); $path = preg_replace('/^' . preg_quote(self::$baseUrl, '/') . '\\//', "", $url["path"]); $query = @$url["query"]; $method = $_SERVER['REQUEST_METHOD']; $request = new Core\Http\Request($method, $path, $query); $dispatcher = new Core\Http\Dispatcher(); try { $dispatcher->handle($request); } catch (Exception $e) { $code = '404'; header($_SERVER["SERVER_PROTOCOL"] . " " . $code); $request = new Core\Http\Request('GET', 'Site/error', 'code=' . $code . '&message=' . $e->getMessage()); $dispatcher->handle($request); } }