/** * @desc Called by the autoload engine to load a specific class must return true on success, * or false if class is not found * @param string $class_name - a class to load * @param bool $test_only - if true, do not actually load class, only check if it is present * @return bool */ public function load_class($class_name, $test_only = false) { if (strcspn($class_name, "#=\"\\?*:/@|<>.\$") != strlen($class_name)) { die("Invalid class name: [{$class_name}]"); } $prefix = $this->prefix; // check if the class belongs to our namespace: if (substr($class_name, 0, strlen($prefix)) == $prefix) { $class_name2 = substr($class_name, strlen($prefix)); } else { return false; } $file = "{$this->path}/{$class_name}.class.php"; if (!file_exists($file)) { $file = "{$this->path}/{$class_name2}.class.php"; } if (file_exists($file)) { if (!$test_only) { include $file; } return true; } // Maybe this is an interface? $file = "{$this->path}/{$class_name}.interface.php"; if (!file_exists($file)) { $file = "{$this->path}/{$class_name2}.interface.php"; } if (file_exists($file)) { if (!$test_only) { include $file; } return true; } return false; }
/** * Returns the next token from this tokenizer's string * * @param bool delimiters default NULL * @return string next token */ public function nextToken($delimiters = null) { if (empty($this->_stack)) { // Read until we have either find a delimiter or until we have // consumed the entire content. do { $offset = strcspn($this->_buf, $delimiters ? $delimiters : $this->delimiters); if ($offset < strlen($this->_buf) - 1) { break; } if (null === ($buf = $this->source->read())) { break; } $this->_buf .= $buf; } while (true); if (!$this->returnDelims || $offset > 0) { $this->_stack[] = substr($this->_buf, 0, $offset); } $l = strlen($this->_buf); if ($this->returnDelims && $offset < $l) { $this->_stack[] = $this->_buf[$offset]; } $offset++; $this->_buf = $offset < $l ? substr($this->_buf, $offset) : false; } return array_shift($this->_stack); }
public function getPositionFirstVowel($word) { if (empty($word) || !is_string($word)) { throw new \InvalidArgumentException(__FILE__ . ':' . __LINE__ . ': Invalid word, it must be a string, got :' . var_export($word, true)); } return strcspn(strtolower($word), self::VOWEL); }
function getUserBytes($user) { global $ipfw_offset; global $ipfw; global $UserBytes; $ipfw_rule = $ipfw_offset + $user; $RuleNum1 = 0; if (!count($UserBytes)) { $ftext = array(); exec($ipfw . ' show', $ftext); for ($i = 0; $i < count($ftext); $i++) { $strTmp = trim($ftext[$i]); $len = strcspn($strTmp, " "); $RuleNum = substr($strTmp, 0, $len); $strTmp = trim(substr_replace($strTmp, " ", 0, $len)); $len = strcspn($strTmp, " "); $CountPakets = substr($strTmp, 0, $len); $strTmp = trim(substr_replace($strTmp, " ", 0, $len)); $len = strcspn($strTmp, " "); $CountBytes = substr($strTmp, 0, $len); if ($RuleNum1 != $RuleNum) { $RuleNum1 = $RuleNum; $UserBytes[$RuleNum] = $CountBytes; } } } return isset($UserBytes[$ipfw_rule]) ? $UserBytes[$ipfw_rule] : false; }
public function getHostInfo($schema = '') { if ($this->_hostInfo === null) { if ($secure = $this->getIsSecureConnection()) { $http = 'https'; } else { $http = 'http'; } if (isset($_SERVER['HTTP_HOST'])) { $this->_hostInfo = $http . '://' . $_SERVER['HTTP_HOST']; } else { $this->_hostInfo = $http . '://' . $_SERVER['SERVER_NAME']; $port = $secure ? $this->getSecurePort() : $this->getPort(); if ($port !== 80 && !$secure || $port !== 443 && $secure) { $this->_hostInfo .= ':' . $port; } } } if ($schema !== '') { $secure = $this->getIsSecureConnection(); if ($secure && $schema === 'https' || !$secure && $schema === 'http') { return $this->_hostInfo; } $port = $schema === 'https' ? $this->getSecurePort() : $this->getPort(); if ($port !== 80 && $schema === 'http' || $port !== 443 && $schema === 'https') { $port = ':' . $port; } else { $port = ''; } $pos = strpos($this->_hostInfo, ':'); return $schema . substr($this->_hostInfo, $pos, strcspn($this->_hostInfo, ':', $pos + 1) + 1) . $port; } else { return $this->_hostInfo; } }
public function match($source, &$pos) { $sourceLength = strlen($source); for (; $pos < $sourceLength; $pos++) { $pos += strcspn($source, $this->firstChars, $pos); if ($pos == $sourceLength) { return false; } foreach ($this->stdTags as $tagIndex => $tag) { $this->tagLength = strlen($tag); if ($pos + $this->tagLength <= $sourceLength && substr_compare($source, $tag, $pos, $this->tagLength) === 0) { $pos += $this->tagLength; $this->tagIndex = $tagIndex; $this->isStdTag = true; return true; } } foreach ($this->userTags as $tagIndex => $tag) { $this->tagLength = strlen($tag); if ($pos + $this->tagLength <= $sourceLength && substr_compare($source, $tag, $pos, $this->tagLength) === 0) { $pos += $this->tagLength; $this->tagIndex = $tagIndex; $this->isStdTag = false; return true; } } } return false; }
/** * Export a literal as an XPath expression * * @param string $str Literal, e.g. "foo" * @return string XPath expression, e.g. "'foo'" */ public static function export($str) { // foo becomes 'foo' if (strpos($str, "'") === false) { return "'" . $str . "'"; } // d'oh becomes "d'oh" if (strpos($str, '"') === false) { return '"' . $str . '"'; } // This string contains both ' and ". XPath 1.0 doesn't have a mechanism to escape quotes, // so we have to get creative and use concat() to join chunks in single quotes and chunks // in double quotes $toks = []; $c = '"'; $pos = 0; while ($pos < strlen($str)) { $spn = strcspn($str, $c, $pos); if ($spn) { $toks[] = $c . substr($str, $pos, $spn) . $c; $pos += $spn; } $c = $c === '"' ? "'" : '"'; } return 'concat(' . implode(',', $toks) . ')'; }
function parse_query($submitted_query) { $query = explode(' ', $submitted_query); if (strcspn($query[0], '0123456789') == strlen($query[0])) { # One word book title (ie. Jacob, James, Matthew) $book = $query[0]; $chapter = $query[1]; if ($query[1] && strcspn($query[1], '0123456789') == strlen($query[1])) { # Two word book title (ie. Solomon's Song) $book .= ' ' . $query[1]; $chapter = $query[2]; if ($query[2] && strcspn($query[2], '0123456789') == strlen($query[2])) { # Three word book title (ie. Doctrine and Covenants, Words of Mormon) $book .= ' ' . $query[2]; $chapter = $query[3]; } } } if (strcspn($query[0], '0123456789') != strlen($query[0])) { # Book that starts with a number (ie. 1 Nephi, 2 Corinthians, 3 John) $book = $query[0] . ' ' . $query[1]; $chapter = $query[2]; } $get_verse = explode(':', $chapter); $result['book'] = $book; $result['chapter'] = $get_verse[0]; $result['verse'] = $get_verse[1]; return $result; }
/** * Tries to match the prefered language out of the http_accept_language string * with one of the available languages. * * @private * @param httpAcceptLanguage the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] * @return Returns returns prefered language or false if no language matched. */ function _matchHttpAcceptLanguages(&$httpAcceptLanguage) { $acceptedLanguages = explode(',', $httpAcceptLanguage); $availableLanguages =& Locales::getAvailableLocales(); $primaryLanguageMatch = ''; // we iterate through the array of languages sent by the UA and test every single // one against the array of available languages foreach ($acceptedLanguages as $acceptedLang) { // clean the string and strip it down to the language value (remove stuff like ";q=0.3") $acceptedLang = substr($acceptedLang, 0, strcspn($acceptedLang, ';')); if (strlen($acceptedLang) > 2) { // cut to primary language $primaryAcceptedLang = substr($acceptedLang, 0, 2); } else { $primaryAcceptedLang = $acceptedLang; } // this is where we start to iterate through available languages foreach ($availableLanguages as $availableLang) { if (stristr($availableLang, $acceptedLang) !== false) { // we have a exact language match return $availableLang; } elseif (stristr($availableLang, $primaryAcceptedLang) !== false && $primaryLanguageMatch == '') { // we found the first primary language match! $primaryLanguageMatch = $availableLang; } } } // foreach if ($primaryLanguageMatch != '') { return $primaryLanguageMatch; } else { return false; } }
protected function parseInput($native, &$pos) { $hasDelimiters = $angleDelimiter = $singleOpen = false; if ('<' === ($char = $this->nextChar($native, $pos)) || '(' === $char) { $hasDelimiters = true; if ('<' === $char) { $angleDelimiter = true; } else { $singleOpen = $pos === call_user_func(self::$strrpos, $native, '('); } $pos++; } $center = $this->point->parseInput($native, $pos); if (')' === $this->nextChar($native, $pos) && $singleOpen) { $hasDelimiters = false; $pos++; } $this->expectChar($native, $pos, ','); $len = strcspn($native, ',)>', $pos); $radius = call_user_func(self::$substr, $native, $pos, $len); $pos += $len; if ($hasDelimiters) { $this->expectChar($native, $pos, $angleDelimiter ? '>' : ')'); } return new Circle($center, $this->_float->input($radius)); }
/** * Create a new Page Template * @param string Name * @param string Description * @param string Filename of the template * @param string Template * @param integer GUID of Cluster Template * @param integer Id of Type (1=singlepage, 2=multipage) * @param integer OPtional key to use. */ function createSitepageMaster($name, $description, $templatePath, $template, $clt, $type, $id = null) { global $db, $c, $errors; if ($id == null) { $id = nextGUID(); } $name = makeCopyName("sitepage_master", "NAME", parseSQL($name), "VERSION=0 AND DELETED=0"); $description = parseSQL($description); $filename = substr($templatePath, 0, strcspn($templatePath, ".")); $filesuffix = $templatePath = substr($templatePath, strcspn($templatePath, ".") + 1); $templatePath = makeUniqueFilename($c["devpath"], parseSQL($filename), $filesuffix); $fp = @fopen($c["devpath"] . $templatePath, "w+"); if ($fp != "") { @fwrite($fp, $template); @fclose($fp); } else { $errors .= "--Could not write spm: " . $templatePath; } $sql = "INSERT INTO sitepage_master (SPM_ID, NAME, DESCRIPTION, TEMPLATE_PATH, CLT_ID, SPMTYPE_ID) VALUES "; $sql .= "({$id}, '{$name}', '{$description}', '{$templatePath}', {$clt}, {$type})"; $query = new query($db, $sql); $query->free(); $variations = createDBCArray("variations", "VARIATION_ID", "1"); for ($i = 0; $i < count($variations); $i++) { $sql = "INSERT INTO sitepage_variations (SPM_ID, VARIATION_ID) VALUES ( {$id}, " . $variations[$i] . ")"; $query = new query($db, $sql); $query->free(); } return $id; }
public function stringToBin($str) { $alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-"; $nbits = 6; $length = strlen($str); $out = ''; $at = 0; $rshift = 0; $char_in = 0; $char_out = chr(0); while (1) { $char_in = strcspn($alpha, $str[$at++]); if ($rshift > 0) { $char_out |= chr($char_in << 8 - $rshift); $out .= $char_out; $char_out = chr(0); if ($at >= $length) { break; } } $char_out |= chr($char_in >> $rshift); $rshift += 2; if ($rshift === 8) { $rshift = 0; } } return $out; }
/** * Format a string containing `<styles>`...`</>` sequences * * @param string $in * @param string[] $stack * @return string */ public static function format($in, &$stack) { $offset = 0; $length = strlen($in); $formatted = ''; do { $p = strcspn($in, '<', $offset); $formatted .= substr($in, $offset, $p); $offset += $p + 1; if ($offset >= $length) { break; } $e = strcspn($in, '>', $offset); $token = substr($in, $offset, $e); if ('' === $token) { $e = strpos($in, '</>', $offset) - $offset; $formatted .= substr($in, $offset + 1, $e - 1); $e += 2; } else { if ('/' === $token[0]) { $formatted .= array_pop($stack); } else { if (strlen($token) !== strspn($token, 'abcdefghijklmnopqrstuvwxyz0123456789-,@')) { $formatted .= substr($in, $offset - 1, $e + 1 + 1); } else { list($set, $unset) = Terminal::transition($token); $formatted .= $set; $stack[] = $unset; } } } $offset += $e + 1; } while ($offset < $length); return $formatted; }
function sql_compile_placeholder($tmpl) { $compiled = array(); $p = 0; $i = 0; $has_named = false; while (false !== ($start = $p = strpos($tmpl, "?", $p))) { switch ($c = substr($tmpl, ++$p, 1)) { case "%": case "@": case "#": $type = $c; ++$p; break; default: $type = ""; } $len = strcspn(substr($tmpl, $p), " \t\r\n,;()[]/"); if ($len) { $key = substr($tmpl, $p, $len); $has_named = true; $p += $len; } else { $key = $i++; } $compiled[] = array($key, $type, $start, $p - $start); } return array($compiled, $tmpl, $has_named); }
/** * Writes a pair * * @param string $name * @param [:string] $attributes * @param var $value * @return void */ public function pair($name, $attributes, $value) { if (is_array($value)) { foreach ($value as $element) { $this->pair($name, $attributes, $element); } } else { if ($value instanceof Object) { $value->write($this, $name); } else { if (null !== $value) { $key = strtoupper($name); foreach ($attributes as $name => $attribute) { if (null === $attribute) { continue; } else { if (strcspn($attribute, '=;:') < strlen($attribute)) { $pair = strtoupper($name) . '="' . $attribute . '"'; } else { $pair = strtoupper($name) . '=' . $attribute; } } if (strlen($key) + strlen($pair) > self::WRAP) { $this->writer->writeLine($key . ';'); $key = ' ' . $pair; } else { $key .= ';' . $pair; } } $this->writer->writeLine(wordwrap($key . ':' . strtr($value, ["\n" => '\\n']), self::WRAP, "\r\n ", true)); } } } }
/** * Delete files in the deleted directory if they are not referenced in the * filearchive table. This needs to be done in the repo because it needs to * interleave database locks with file operations, which is potentially a * remote operation. * @return FileRepoStatus */ function cleanupDeletedBatch($storageKeys) { $root = $this->getZonePath('deleted'); $dbw = $this->getMasterDB(); $status = $this->newGood(); $storageKeys = array_unique($storageKeys); foreach ($storageKeys as $key) { $hashPath = $this->getDeletedHashPath($key); $path = "{$root}/{$hashPath}{$key}"; $dbw->begin(); $inuse = $dbw->selectField('filearchive', '1', array('fa_storage_group' => 'deleted', 'fa_storage_key' => $key), __METHOD__, array('FOR UPDATE')); if (!$inuse) { $sha1 = substr($key, 0, strcspn($key, '.')); $ext = substr($key, strcspn($key, '.') + 1); $ext = File::normalizeExtension($ext); $inuse = $dbw->selectField('oldimage', '1', array('oi_sha1' => $sha1, 'oi_archive_name ' . $dbw->buildLike($dbw->anyString(), ".{$ext}"), $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE), __METHOD__, array('FOR UPDATE')); } if (!$inuse) { wfDebug(__METHOD__ . ": deleting {$key}\n"); if (!@unlink($path)) { $status->error('undelete-cleanup-error', $path); $status->failCount++; } } else { wfDebug(__METHOD__ . ": {$key} still in use\n"); $status->successCount++; } $dbw->commit(); } return $status; }
/** * Parse an attribute value template * * @link http://www.w3.org/TR/xslt#dt-attribute-value-template * * @param string $attrValue Attribute value * @return array Array of tokens */ public static function parse($attrValue) { $tokens = []; $attrLen = strlen($attrValue); $pos = 0; while ($pos < $attrLen) { // Look for opening brackets if ($attrValue[$pos] === '{') { // Two brackets = one literal bracket if (substr($attrValue, $pos, 2) === '{{') { $tokens[] = ['literal', '{']; $pos += 2; continue; } // Move the cursor past the left bracket ++$pos; // We're inside an inline XPath expression. We need to parse it in order to find // where it ends $expr = ''; while ($pos < $attrLen) { // Capture everything up to the next "interesting" char: ', " or } $spn = strcspn($attrValue, '\'"}', $pos); if ($spn) { $expr .= substr($attrValue, $pos, $spn); $pos += $spn; } if ($pos >= $attrLen) { throw new RuntimeException('Unterminated XPath expression'); } // Capture the character then move the cursor $c = $attrValue[$pos]; ++$pos; if ($c === '}') { // Done with this expression break; } // Look for the matching quote $quotePos = strpos($attrValue, $c, $pos); if ($quotePos === false) { throw new RuntimeException('Unterminated XPath expression'); } // Capture the content of that string then move the cursor past it $expr .= $c . substr($attrValue, $pos, $quotePos + 1 - $pos); $pos = 1 + $quotePos; } $tokens[] = ['expression', $expr]; } $spn = strcspn($attrValue, '{', $pos); if ($spn) { // Capture this chunk of attribute value $str = substr($attrValue, $pos, $spn); // Unescape right brackets $str = str_replace('}}', '}', $str); // Add the value and move the cursor $tokens[] = ['literal', $str]; $pos += $spn; } } return $tokens; }
/** * Will return https://sp.example.org[:PORT] */ public static function selfURLhost() { $url = self::getBaseURL(); $start = strpos($url, '://') + 3; $length = strcspn($url, '/', $start) + $start; return substr($url, 0, $length); }
public function getBrowserLangCode($system_langs) { $lang = null; if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { return $lang; } $browser_langs = explode(',', $this->request->server['HTTP_ACCEPT_LANGUAGE']); foreach ($browser_langs as $browser_lang) { // Slice out the part before ; on first step, the part before - on second, place into array $browser_lang = substr($browser_lang, 0, strcspn($browser_lang, ';')); $primary_browser_lang = substr($browser_lang, 0, 2); foreach ($system_langs as $system_lang) { if (!$system_lang['status']) { continue; } $system_code = $system_lang['code']; $system_dir = $system_lang['directory']; // Take off 3 letters (zh-yue) iso code languages as they can't match browsers' languages and default them to en // http://www.w3.org/International/articles/language-tags/#extlang if (strlen($system_dir) > 5) { continue; } if (strtolower($browser_lang) == strtolower(substr($system_dir, 0, strlen($browser_lang)))) { return $system_code; } elseif ($primary_browser_lang == substr($system_dir, 0, 2)) { $primary_detected_code = $system_code; } } if (isset($primary_detected_code)) { return $primary_detected_code; } } return $lang; }
/** * Parses a DNUMBER token like PHP would. * * @param string $str A string number * * @return float The parsed number */ public static function parse($str) { // if string contains any of .eE just cast it to float if (false !== strpbrk($str, '.eE')) { return (double) $str; } // otherwise it's an integer notation that overflowed into a float // if it starts with 0 it's one of the special integer notations if ('0' === $str[0]) { // hex if ('x' === $str[1] || 'X' === $str[1]) { return hexdec($str); } // bin if ('b' === $str[1] || 'B' === $str[1]) { return bindec($str); } // oct // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit (8 or 9) // so that only the digits before that are used return octdec(substr($str, 0, strcspn($str, '89'))); } // dec return (double) $str; }
function passTest($pass, $pass_confirm) { if (!empty($pass)) { //checkt of de string empty is if (7 < strlen($pass)) { //checkt of het wachtwoord wel 8 of meer karakters is if (strcspn($pass, '0123456789') != strlen($pass)) { //checkt of het wachtwoord nummers bevat if (strcspn($pass, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') != strlen($pass)) { //checkt of het wachtwoord een hoofdletter heeft if ($pass_confirm == $pass) { return TRUE; } else { $_SESSION['message'] = "Wachtwoorden komen niet overeen"; } } else { $_SESSION['message'] = "Wachtwoord moet een hoofdletter bevatten"; } } else { $_SESSION['message'] = "Wachtwoorden moet een cijfer bevatten"; } } else { $_SESSION['message'] = "Wachtwoord moet minimaal 8 of meer karakters bevatten"; } } else { $_SESSION['message'] = "Wachtwoord veld is leeg"; } }
/** * Tries to detect the language. * * @return string locale or null if not found * * @since 11.1 */ public static function detectLanguage() { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $browserLangs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $systemLangs = self::getLanguages(); foreach ($browserLangs as $browserLang) { // Slice out the part before ; on first step, the part before - on second, place into array $browserLang = substr($browserLang, 0, strcspn($browserLang, ';')); $primary_browserLang = substr($browserLang, 0, 2); foreach ($systemLangs as $systemLang) { // Take off 3 letters iso code languages as they can't match browsers' languages and default them to en $Jinstall_lang = $systemLang->lang_code; if (strlen($Jinstall_lang) < 6) { if (strtolower($browserLang) == strtolower(substr($systemLang->lang_code, 0, strlen($browserLang)))) { return $systemLang->lang_code; } elseif ($primary_browserLang == substr($systemLang->lang_code, 0, 2)) { $primaryDetectedLang = $systemLang->lang_code; } } } if (isset($primaryDetectedLang)) { return $primaryDetectedLang; } } } return; }
function escape($str) { if (strcspn($str, ",\"\r\n") != strlen($str)) { $str = '"' . str_replace('"', '""', $str) . '"'; } return $str; }
function revert(&$url_array, $pos) { global $_SEF_SPACE; $QUERY_STRING = ''; $url_array = array_filter($url_array); // V x : traling slash can cause empty array element $url_array = array_values($url_array); if (!empty($url_array[1]) && strcspn($url_array[1], ',') == strlen($url_array[1])) { // This is a nocache url $x = 0; $c = count($url_array); while ($x < $c) { if (isset($url_array[$x]) && $url_array[$x] != '' && isset($url_array[$x + 1]) && $url_array[$x + 1] != '') { $QUERY_STRING .= '&' . $url_array[$x] . '=' . $url_array[$x + 1]; } $x += 2; } } else { //This is a default mambo SEF url for a component foreach ($url_array as $value) { $temp = explode(",", $value); if (isset($temp[0]) && $temp[0] != '' && isset($temp[1]) && $temp[1] != "") { $QUERY_STRING .= "&{$temp['0']}={$temp['1']}"; } } } //return str_replace("&option","option",$QUERY_STRING); return JString::ltrim($QUERY_STRING, '&'); }
protected function __construct() { $idFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid'; $nodeId = is_file( $idFile ) ? file_get_contents( $idFile ) : ''; // Try to get some ID that uniquely identifies this machine (RFC 4122)... if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) { wfSuppressWarnings(); if ( wfIsWindows() ) { // http://technet.microsoft.com/en-us/library/bb490913.aspx $csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) ); $line = substr( $csv, 0, strcspn( $csv, "\n" ) ); $info = str_getcsv( $line ); $nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : ''; } elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X // See http://linux.die.net/man/8/ifconfig $m = array(); preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/', wfShellExec( '/sbin/ifconfig -a' ), $m ); $nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : ''; } wfRestoreWarnings(); if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) { $nodeId = MWCryptRand::generateHex( 12, true ); $nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit } file_put_contents( $idFile, $nodeId ); // cache } $this->nodeId32 = wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 ); $this->nodeId48 = wfBaseConvert( $nodeId, 16, 2, 48 ); // If different processes run as different users, they may have different temp dirs. // This is dealt with by initializing the clock sequence number and counters randomly. $this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88'; $this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128'; }
/** * Read a string * * @param int limit default 8192 * @return string */ public function read($limit = 8192) { while ($this->in->available() > 0 && strlen($this->buffer) < $limit) { $read = $this->in->read($limit); $o = 0; $s = strlen($read); while ($o < $s) { $p = strcspn($read, '=', $o); $this->buffer .= substr($read, $o, $p); if (($o += $p + 1) <= $s) { while ($this->in->available() > 0 && $o > $s - 2) { $read .= $this->in->read(2); $s = strlen($read); } if ("\n" === $read[$o]) { $o += 1; } else { if (1 !== sscanf($h = substr($read, $o, 2), '%x', $c)) { throw new \io\IOException('Invalid byte sequence "=' . $h . '"'); } $this->buffer .= chr($c); $o += 2; } } } } $chunk = substr($this->buffer, 0, $limit); $this->buffer = substr($this->buffer, $limit); return $chunk; }
/** * Map route to all public controller method * * with * Route::get('/prefix', 'ClassController') * * this will map * GET domain.com/prefix -> ClassController::getIndex * POST domain.com/prefix -> ClassCOntroller::postIndex * PUT domain.com/prefix -> ClassCOntroller::putIndex */ public static function controller() { $arguments = func_get_args(); $path = $arguments[0]; $controller = end($arguments); $class = new \ReflectionClass($controller); $controllerMethods = $class->getMethods(\ReflectionMethod::IS_PUBLIC); $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; foreach ($controllerMethods as $method) { if (substr($method->name, 0, 2) != '__') { $methodName = $method->name; $callable = $arguments; $pos = strcspn($methodName, $uppercase); $httpMethod = substr($methodName, 0, $pos); $ctrlMethod = lcfirst(strpbrk($methodName, $uppercase)); if ($ctrlMethod == 'index') { $pathMethod = $path; } else { if ($httpMethod == 'get') { $pathMethod = "{$path}/{$ctrlMethod}(/:params+)"; } else { $pathMethod = "{$path}/{$ctrlMethod}"; } } //put edited pattern to the top stack array_shift($callable); array_unshift($callable, $pathMethod); //put edited controller to the bottom stack array_pop($callable); array_push($callable, "{$controller}:{$methodName}"); call_user_func_array(array(self::$slim, $httpMethod), $callable); } } }
public function parse_basic_syntax($args) { $version_parser = new VersionParser(); $requires = array(); foreach ($args as $requirement) { $name_length = strcspn($requirement, '>=|~'); if (strlen($requirement) === $name_length) { // No version constraint specified, use wildcard $dependency_name = $requirement; $constraint_text = '*'; } else { $dependency_name = substr($requirement, 0, $name_length); $constraint_text = substr($requirement, $name_length); // If the constraint is exactly '=', trim it for // Composer syntax compatibility if (strlen($constraint_text) >= 2 && $constraint_text[0] === '=' && is_numeric($constraint_text[1])) { $constraint_text = substr($constraint_text, 1); } } if (strpos($dependency_name, '/') === false) { $dependency_name = 'wpackagist-plugin/' . $dependency_name; } $constraint = $version_parser->parseConstraints($constraint_text); $requires[] = new Link($this->plugin_name, $dependency_name, $constraint, 'requires', $constraint_text); } $this->setRequires($requires); }
public function parse() { // first remove the XML declaration // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages $header = preg_replace('/<\\?xml.*?\\?' . '>/s', '', substr($this->message, 0, 100), 1); $this->message = trim(substr_replace($this->message, $header, 0, 100)); if ('' == $this->message) { return false; } // Then remove the DOCTYPE $header = preg_replace('/^<!DOCTYPE[^>]*+>/i', '', substr($this->message, 0, 200), 1); $this->message = trim(substr_replace($this->message, $header, 0, 200)); if ('' == $this->message) { return false; } // Check that the root tag is valid $root_tag = substr($this->message, 0, strcspn(substr($this->message, 0, 20), "> \t\r\n")); if ('<!DOCTYPE' === strtoupper($root_tag)) { return false; } if (!in_array($root_tag, ['<methodCall', '<methodResponse', '<fault'])) { return false; } // Bail if there are too many elements to parse $element_limit = 30000; if ($element_limit && 2 * $element_limit < substr_count($this->message, '<')) { return false; } $this->_parser = xml_parser_create(); // Set XML parser to take the case of tags in to account xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false); // Set XML parser callback functions xml_set_object($this->_parser, $this); xml_set_element_handler($this->_parser, 'tagOpen', 'tagClose'); xml_set_character_data_handler($this->_parser, 'cdata'); $chunk_size = 262144; // 256Kb, parse in chunks to avoid the RAM usage on very large messages $final = false; do { if (strlen($this->message) <= $chunk_size) { $final = true; } $part = substr($this->message, 0, $chunk_size); $this->message = substr($this->message, $chunk_size); if (!xml_parse($this->_parser, $part, $final)) { return false; } if ($final) { break; } } while (true); xml_parser_free($this->_parser); // Grab the error messages, if any if ($this->messageType === 'fault') { $this->faultCode = $this->params[0]['faultCode']; $this->faultString = $this->params[0]['faultString']; } return true; }
function Analyze() { $info =& $this->getid3->info; fseek($this->getid3->fp, $info['avdataoffset'], SEEK_SET); $SZIPHeader = fread($this->getid3->fp, 6); if (substr($SZIPHeader, 0, 4) != "SZ\n") { $info['error'][] = 'Expecting "53 5A 0A 04" at offset ' . $info['avdataoffset'] . ', found "' . getid3_lib::PrintHexBytes(substr($SZIPHeader, 0, 4)) . '"'; return false; } $info['fileformat'] = 'szip'; $info['szip']['major_version'] = getid3_lib::BigEndian2Int(substr($SZIPHeader, 4, 1)); $info['szip']['minor_version'] = getid3_lib::BigEndian2Int(substr($SZIPHeader, 5, 1)); while (!feof($this->getid3->fp)) { $NextBlockID = fread($this->getid3->fp, 2); switch ($NextBlockID) { case 'SZ': // Note that szip files can be concatenated, this has the same effect as // concatenating the files. this also means that global header blocks // might be present between directory/data blocks. fseek($this->getid3->fp, 4, SEEK_CUR); break; case 'BH': $BHheaderbytes = getid3_lib::BigEndian2Int(fread($this->getid3->fp, 3)); $BHheaderdata = fread($this->getid3->fp, $BHheaderbytes); $BHheaderoffset = 0; while (strpos($BHheaderdata, "", $BHheaderoffset) > 0) { //filename as \0 terminated string (empty string indicates end) //owner as \0 terminated string (empty is same as last file) //group as \0 terminated string (empty is same as last file) //3 byte filelength in this block //2 byte access flags //4 byte creation time (like in unix) //4 byte modification time (like in unix) //4 byte access time (like in unix) $BHdataArray['filename'] = substr($BHheaderdata, $BHheaderoffset, strcspn($BHheaderdata, "")); $BHheaderoffset += strlen($BHdataArray['filename']) + 1; $BHdataArray['owner'] = substr($BHheaderdata, $BHheaderoffset, strcspn($BHheaderdata, "")); $BHheaderoffset += strlen($BHdataArray['owner']) + 1; $BHdataArray['group'] = substr($BHheaderdata, $BHheaderoffset, strcspn($BHheaderdata, "")); $BHheaderoffset += strlen($BHdataArray['group']) + 1; $BHdataArray['filelength'] = getid3_lib::BigEndian2Int(substr($BHheaderdata, $BHheaderoffset, 3)); $BHheaderoffset += 3; $BHdataArray['access_flags'] = getid3_lib::BigEndian2Int(substr($BHheaderdata, $BHheaderoffset, 2)); $BHheaderoffset += 2; $BHdataArray['creation_time'] = getid3_lib::BigEndian2Int(substr($BHheaderdata, $BHheaderoffset, 4)); $BHheaderoffset += 4; $BHdataArray['modification_time'] = getid3_lib::BigEndian2Int(substr($BHheaderdata, $BHheaderoffset, 4)); $BHheaderoffset += 4; $BHdataArray['access_time'] = getid3_lib::BigEndian2Int(substr($BHheaderdata, $BHheaderoffset, 4)); $BHheaderoffset += 4; $info['szip']['BH'][] = $BHdataArray; } break; default: break 2; } } return true; }