/** * Method to test for a valid color in hexadecimal. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param JRegistry $input An optional JRegistry object with the entire data set to validate against the entire form. * @param JForm $form The form object for which the field is being tested. * * @return boolean True if the value is valid, false otherwise. * * @since 11.2 */ public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null) { $value = trim($value); if (empty($value)) { // A color field can't be empty, we default to black. This is the same as the HTML5 spec. $value = '#000000'; return true; } if ($value[0] != '#') { return false; } // Remove the leading # if present to validate the numeric part $value = ltrim($value, '#'); // The value must be 6 or 3 characters long if (!((strlen($value) == 6 || strlen($value) == 3) && ctype_xdigit($value))) { return false; } // Prepend the # again $value = '#' . $value; return true; }
/** * Filter Stream Through Buckets * * @param resource $in userfilter.bucket brigade * pointer to a group of buckets objects containing the data to be filtered * @param resource $out userfilter.bucket brigade * pointer to another group of buckets for storing the converted data * @param int $consumed counter passed by reference that must be incremented by the length * of converted data * @param boolean $closing flag that is set to TRUE if we are in the last cycle and the stream is * about to close * @return int */ function filter($in, $out, &$consumed, $closing) { // $in and $out are opaque "bucket brigade" objects which consist of a // sequence of opaque "buckets", which contain the actual stream data. // The only way to use these objects is the stream_bucket_* functions. // Unfortunately, there doesn't seem to be any way to access a bucket // without turning it into a string using stream_bucket_make_writeable(), // even if you want to pass the bucket along unmodified. // Each call to this pops a bucket from the bucket brigade and // converts it into an object with two properties: datalen and data. // This same object interface is accepted by stream_bucket_append(). while ($bucket = stream_bucket_make_writeable($in)) { $outbuffer = ''; $offset = 0; // Loop through the string. For efficiency, we don't advance a character // at a time but try to zoom ahead to where we think the next chunk // boundary should be. // Since the stream filter divides the data into buckets arbitrarily, // we have to maintain state ($this->chunkremaining) across filter() calls. while ($offset < $bucket->datalen) { if ($this->chunkremaining === 0) { // start of new chunk, or the start of the transfer $firstline = strpos($bucket->data, "\r\n", $offset); $chunkline = substr($bucket->data, $offset, $firstline - $offset); $chunklen = current(explode(';', $chunkline, 2)); // ignore MIME-like extensions $chunklen = trim($chunklen); if (!ctype_xdigit($chunklen)) { // There should have been a chunk length specifier here, but since // there are non-hex digits something must have gone wrong. return PSFS_ERR_FATAL; } $this->chunkremaining = hexdec($chunklen); // $firstline already includes $offset in it $offset = $firstline + 2; // +2 is CRLF if ($this->chunkremaining === 0) { //end of the transfer break; } // ignore possible trailing headers } // get as much data as available in a single go... $nibble = substr($bucket->data, $offset, $this->chunkremaining); $nibblesize = strlen($nibble); $offset += $nibblesize; // ...but recognize we may not have got all of it if ($nibblesize === $this->chunkremaining) { $offset += 2; } // skip over trailing CRLF $this->chunkremaining -= $nibblesize; $outbuffer .= $nibble; } $consumed += $bucket->datalen; $bucket->data = $outbuffer; stream_bucket_append($out, $bucket); } return PSFS_PASS_ON; }
/** * Generate a Host Unique Identifier * * @param string $primaryNS The primary namespace, 4 hexadecimal characters * @param string $secondaryNS The secondary namespace, 3 hexadecimal characters * @param string $format The desired output format, one of 'str', 'hex', 'bin', or 'obj'. Default 'str' * - str: Return a 36 character string in the format AAAAAAAAAAAAAA-BBBBB-CCCC-DDDD-EEEEE * - hex: Return a 32 digit hexadecimal value in the format AAAAAAAAAAAAAABBBBBCCCCDDDDEEEEE * - bin: Return a 16 byte binary string * - obj: Return an object containing all 3 formats * * @return mixed Returns a string in the requested format, or false if parameters are incorrect * @example /reference/php/example.php */ function getHUID($primaryNS, $secondaryNS, $format = 'str') { if (strlen($primaryNS) === 4 && strlen($secondaryNS) === 4 && ctype_xdigit($primaryNS . $secondaryNS)) { if (in_array($format, ['hex', 'bin'])) { $delimiter = ''; } else { $delimiter = '-'; } $huid = strtolower(str_pad(dechex(time()), 14, '0', STR_PAD_LEFT) . $delimiter . str_pad(dechex(substr(microtime(), 2, 5)), 5, '0', STR_PAD_LEFT) . $delimiter . $primaryNS . $delimiter . $secondaryNS . $delimiter . str_pad(dechex(mt_rand(0, 0xfffff)), 5, '0', STR_PAD_LEFT)); switch ($format) { case 'bin': return hex2bin($huid); break; case 'obj': $huids = new stdClass(); $huids->str = $huid; $huids->hex = str_replace('-', '', $huid); $huids->bin = hex2bin($huids->hex); return $huids; break; default: return $huid; break; } } return false; }
function storeRegistration() { require_once JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'helpers' . DS . 'config.php'; $ret = new stdClass(); $d = JRequest::getVar('opc_registration_company', ''); $ret->opc_registration_company = str_replace('"', '\\"', $d); $d = JRequest::getVar('opc_registration_name', ''); $ret->opc_registration_name = str_replace('"', '\\"', $d); $d = JRequest::getVar('opc_registration_username', ''); $ret->opc_registration_username = str_replace('"', '\\"', $d); $d = JRequest::getVar('rupostel_email', ''); $ret->opc_registration_email = str_replace('"', '\\"', $d); $ret->opc_registration_hash = JRequest::getVar('opc_registration_hash', ''); $reg = OPCconfig::store('opc_registration', '', 0, $ret); if (!empty($ret->opc_registration_hash)) { include JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'config' . DS . 'api.php'; if ($api_key !== $ret->opc_registration_hash) { $a = explode('_', $ret->opc_registration_hash); if (count($a) == 2) { if (is_numeric($a[0]) && ctype_xdigit($a[1])) { $api_key = $a[0] . '_' . $a[1]; $towrite = '<?php defined( \'_JEXEC\' ) or die( \'Restricted access\' ); ' . "\n"; $towrite .= ' $api_key = \'' . $api_key . '\'; ' . "\n"; $towrite .= ' $api_stamp = \'' . time() . '\'; ' . "\n"; jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); JFile::write(JPATH_SITE . DS . 'components' . DS . 'com_onepage' . DS . 'config' . DS . 'api.php', $towrite); } } } else { } } //die('h'); }
/** * Fix up percent-encoding by decoding unreserved characters and normalizing * @param $string String to normalize */ function normalize($string) { if ($string == '') { return ''; } $parts = explode('%', $string); $ret = array_shift($parts); foreach ($parts as $part) { $length = strlen($part); if ($length < 2) { $ret .= '%25' . $part; continue; } $encoding = substr($part, 0, 2); $text = substr($part, 2); if (!ctype_xdigit($encoding)) { $ret .= '%25' . $part; continue; } $int = hexdec($encoding); if ($int >= 48 && $int <= 57 || $int >= 65 && $int <= 90 || $int >= 97 && $int <= 122 || $int == 126 || $int == 45 || $int == 46 || $int == 95) { $ret .= chr($int) . $text; continue; } $encoding = strtoupper($encoding); $ret .= '%' . $encoding . $text; } return $ret; }
/** * Import * @param mixed $id ID * @return mixed */ public static function import($id) { if ($id instanceof static) { return $id; } elseif ($id instanceof \MongoId) { $id = (string) $id; } elseif (!is_string($id)) { if (is_array($id) && isset($id['$id'])) { return static::import($id['$id']); } return false; } elseif (strlen($id) === 24) { if (!ctype_xdigit($id)) { return false; } } elseif (ctype_alnum($id)) { $id = gmp_strval(gmp_init(strrev($id), 62), 16); if (strlen($id) > 24) { return false; } if (strlen($id) < 24) { $id = str_pad($id, 24, '0', STR_PAD_LEFT); } } else { return false; } return new static($id); }
/** * Return if the string passed is a valid hexadecimal number. * This check is necessary because PHP 7 doesn't recognize hexadecimal string as numeric anymore. * * @param mixed $item * @return boolean */ private function isHexadecimal($item) { if (is_string($item) && preg_match('/^0x(.*)$/', $item, $matches)) { return ctype_xdigit($matches[1]); } return false; }
/** * Function validatePasswordLogin * * compare user password-hash with given user-password * and check if they are the same * additionally it updates the hash if the system settings changed * or if the very old md5() sum is used * * @param array $userinfo user-data from table * @param string $password the password to validate * @param string $table either panel_customers or panel_admins * @param string $uid user-id-field in $table * * @return boolean */ function validatePasswordLogin($userinfo = null, $password = null, $table = 'panel_customers', $uid = 'customerid') { $systype = 3; // SHA256 if (Settings::Get('system.passwordcryptfunc') !== null) { $systype = (int) Settings::Get('system.passwordcryptfunc'); } $pwd_hash = $userinfo['password']; $update_hash = false; // check for good'ole md5 if (strlen($pwd_hash) == 32 && ctype_xdigit($pwd_hash)) { $pwd_check = md5($password); $update_hash = true; } else { // cut out the salt from the hash $pwd_salt = str_replace(substr(strrchr($pwd_hash, "\$"), 1), "", $pwd_hash); // create same hash to compare $pwd_check = crypt($password, $pwd_salt); // check whether the hash needs to be updated $hash_type_chk = substr($pwd_hash, 0, 3); if ($systype == 1 && $hash_type_chk != '$1$' || $systype == 2 && $hash_type_chk != '$2$' || $systype == 3 && $hash_type_chk != '$5$' || $systype == 4 && $hash_type_chk != '$6$') { $update_hash = true; } } if ($pwd_hash == $pwd_check) { // check for update of hash if ($update_hash) { $upd_stmt = Database::prepare("\n\t\t\t\tUPDATE " . $table . " SET `password` = :newpasswd WHERE `" . $uid . "` = :uid\n\t\t\t"); $params = array('newpasswd' => makeCryptPassword($password), 'uid' => $userinfo[$uid]); Database::pexecute($upd_stmt, $params); } return true; } return false; }
function pickImageDir($directory, $levels) { if ($levels) { $dirs = array(); // Check which subdirs are actually present... $dir = opendir($directory); while (false !== ($entry = readdir($dir))) { if (ctype_xdigit($entry) && strlen($entry) == 1) { $dirs[] = $entry; } } closedir($dir); $place = mt_rand(0, count($dirs) - 1); // In case all dirs are not filled, // cycle through next digits... for ($j = 0; $j < count($dirs); $j++) { $char = $dirs[($place + $j) % count($dirs)]; $return = $this->pickImageDir("{$directory}/{$char}", $levels - 1); if ($return) { return $return; } } // Didn't find any images in this directory... empty? #echo "found not image"; return false; } else { return $this->pickImageFromDir($directory); } }
public function get_visibility_value() { $return = (object) ["templates" => get_page_templates()]; if (isset($_REQUEST["layout_id"]) && ctype_xdigit($_REQUEST["layout_id"]) && isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"])) { $field_id = $_REQUEST["layout_id"]; $post_id = $_REQUEST["id"]; } else { wp_send_json_success($return); } $post = get_post($post_id); $post_obj = unserialize($post->post_content); $found = false; foreach ($post_obj["layouts"] as $obj) { if ($obj["key"] == $field_id) { $found = true; break; } } if (!$found) { wp_send_json_success($return); } if (is_array($obj) && isset($obj["visibility"])) { if (!empty($obj["visibility"])) { $return->visibility = explode(",", $obj["visibility"]); wp_send_json_success($return); } else { wp_send_json_success($return); } } else { wp_send_json_success($return); } }
public function check($args) { if (ctype_xdigit($args)) { return true; } return false; }
function clm_function_is_color($colorCode) { if (!ctype_xdigit($colorCode) || strlen($colorCode) != 6 && strlen($colorCode) != 3) { return false; } return true; }
/** * Read header of next chunk into buffer. * * This method will likely start to read and buffer contents of the next chunk. */ protected function readNextChunk() : \Generator { if ($this->remainder === 0) { if ("\r\n" !== (yield $this->stream->readBuffer(2))) { throw new StreamException('Missing CRLF after chunk'); } } if (empty($this->remainder)) { if (null === ($header = (yield $this->stream->readLine()))) { return; } $header = \trim(\preg_replace("';.*\$'", '', $header)); if (!\ctype_xdigit($header) || \strlen($header) > 7) { throw new StreamException(\sprintf('Invalid HTTP chunk length received: "%s"', $header)); } $this->remainder = \hexdec($header); if ($this->remainder === 0) { if ("\r\n" !== (yield $this->stream->readBuffer(2))) { throw new StreamException('Missing CRLF after last chunk'); } return; } } return (yield $this->stream->read(\min($this->bufferSize, $this->remainder))); }
public function testNameBased() { // test UUID parts $uuid = explode('-', Uuid::nameBased('bar')); $this->assertEquals(5, count($uuid)); $this->assertEquals(true, ctype_xdigit($uuid[0]), 'time-low'); $this->assertEquals(true, ctype_xdigit($uuid[1]), 'time-mid'); $this->assertEquals(true, ctype_xdigit($uuid[2]), 'time-high-and-version'); $this->assertEquals(true, ctype_xdigit($uuid[3]), 'clock-seq-and-reserved / clock-seq-low'); $this->assertEquals(true, ctype_xdigit($uuid[4]), 'node'); $this->assertEquals(8, strlen($uuid[0]), 'time-low'); $this->assertEquals(4, strlen($uuid[1]), 'time-mid'); $this->assertEquals(4, strlen($uuid[2]), 'time-high-and-version'); $this->assertEquals(4, strlen($uuid[3]), 'clock-seq-and-reserved / clock-seq-low'); $this->assertEquals(12, strlen($uuid[4]), 'node'); $this->assertEquals(5, hexdec($uuid[2]) >> 12, 'Set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3.'); $this->assertEquals(2, hexdec($uuid[3]) >> 14, 'Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively.'); // the UUIDs generated at different times from the same name in the same // namespace MUST be equal. $uuid = Uuid::nameBased('foobar'); sleep(1); $this->assertEquals($uuid, Uuid::nameBased('foobar')); // the UUIDs generated from two different names in the same namespace // should be different (with very high probability). $this->assertTrue(Uuid::nameBased('foobar') != Uuid::nameBased('bar')); }
/** * Sanitises a HEX value. * The way this works is by splitting the string in 6 substrings. * Each sub-string is individually sanitized, and the result is then returned. * * @var string The hex value of a color * @param boolean Whether we want to include a hash (#) at the beginning or not * @return string The sanitized hex color. */ public static function sanitize_hex($color = '#FFFFFF', $hash = true) { $word_colors = array('aliceblue' => 'F0F8FF', 'antiquewhite' => 'FAEBD7', 'aqua' => '00FFFF', 'aquamarine' => '7FFFD4', 'azure' => 'F0FFFF', 'beige' => 'F5F5DC', 'bisque' => 'FFE4C4', 'black' => '000000', 'blanchedalmond' => 'FFEBCD', 'blue' => '0000FF', 'blueviolet' => '8A2BE2', 'brown' => 'A52A2A', 'burlywood' => 'DEB887', 'cadetblue' => '5F9EA0', 'chartreuse' => '7FFF00', 'chocolate' => 'D2691E', 'coral' => 'FF7F50', 'cornflowerblue' => '6495ED', 'cornsilk' => 'FFF8DC', 'crimson' => 'DC143C', 'cyan' => '00FFFF', 'darkblue' => '00008B', 'darkcyan' => '008B8B', 'darkgoldenrod' => 'B8860B', 'darkgray' => 'A9A9A9', 'darkgreen' => '006400', 'darkgrey' => 'A9A9A9', 'darkkhaki' => 'BDB76B', 'darkmagenta' => '8B008B', 'darkolivegreen' => '556B2F', 'darkorange' => 'FF8C00', 'darkorchid' => '9932CC', 'darkred' => '8B0000', 'darksalmon' => 'E9967A', 'darkseagreen' => '8FBC8F', 'darkslateblue' => '483D8B', 'darkslategray' => '2F4F4F', 'darkslategrey' => '2F4F4F', 'darkturquoise' => '00CED1', 'darkviolet' => '9400D3', 'deeppink' => 'FF1493', 'deepskyblue' => '00BFFF', 'dimgray' => '696969', 'dimgrey' => '696969', 'dodgerblue' => '1E90FF', 'firebrick' => 'B22222', 'floralwhite' => 'FFFAF0', 'forestgreen' => '228B22', 'fuchsia' => 'FF00FF', 'gainsboro' => 'DCDCDC', 'ghostwhite' => 'F8F8FF', 'gold' => 'FFD700', 'goldenrod' => 'DAA520', 'gray' => '808080', 'green' => '008000', 'greenyellow' => 'ADFF2F', 'grey' => '808080', 'honeydew' => 'F0FFF0', 'hotpink' => 'FF69B4', 'indianred' => 'CD5C5C', 'indigo' => '4B0082', 'ivory' => 'FFFFF0', 'khaki' => 'F0E68C', 'lavender' => 'E6E6FA', 'lavenderblush' => 'FFF0F5', 'lawngreen' => '7CFC00', 'lemonchiffon' => 'FFFACD', 'lightblue' => 'ADD8E6', 'lightcoral' => 'F08080', 'lightcyan' => 'E0FFFF', 'lightgoldenrodyellow' => 'FAFAD2', 'lightgray' => 'D3D3D3', 'lightgreen' => '90EE90', 'lightgrey' => 'D3D3D3', 'lightpink' => 'FFB6C1', 'lightsalmon' => 'FFA07A', 'lightseagreen' => '20B2AA', 'lightskyblue' => '87CEFA', 'lightslategray' => '778899', 'lightslategrey' => '778899', 'lightsteelblue' => 'B0C4DE', 'lightyellow' => 'FFFFE0', 'lime' => '00FF00', 'limegreen' => '32CD32', 'linen' => 'FAF0E6', 'magenta' => 'FF00FF', 'maroon' => '800000', 'mediumaquamarine' => '66CDAA', 'mediumblue' => '0000CD', 'mediumorchid' => 'BA55D3', 'mediumpurple' => '9370D0', 'mediumseagreen' => '3CB371', 'mediumslateblue' => '7B68EE', 'mediumspringgreen' => '00FA9A', 'mediumturquoise' => '48D1CC', 'mediumvioletred' => 'C71585', 'midnightblue' => '191970', 'mintcream' => 'F5FFFA', 'mistyrose' => 'FFE4E1', 'moccasin' => 'FFE4B5', 'navajowhite' => 'FFDEAD', 'navy' => '000080', 'oldlace' => 'FDF5E6', 'olive' => '808000', 'olivedrab' => '6B8E23', 'orange' => 'FFA500', 'orangered' => 'FF4500', 'orchid' => 'DA70D6', 'palegoldenrod' => 'EEE8AA', 'palegreen' => '98FB98', 'paleturquoise' => 'AFEEEE', 'palevioletred' => 'DB7093', 'papayawhip' => 'FFEFD5', 'peachpuff' => 'FFDAB9', 'peru' => 'CD853F', 'pink' => 'FFC0CB', 'plum' => 'DDA0DD', 'powderblue' => 'B0E0E6', 'purple' => '800080', 'red' => 'FF0000', 'rosybrown' => 'BC8F8F', 'royalblue' => '4169E1', 'saddlebrown' => '8B4513', 'salmon' => 'FA8072', 'sandybrown' => 'F4A460', 'seagreen' => '2E8B57', 'seashell' => 'FFF5EE', 'sienna' => 'A0522D', 'silver' => 'C0C0C0', 'skyblue' => '87CEEB', 'slateblue' => '6A5ACD', 'slategray' => '708090', 'slategrey' => '708090', 'snow' => 'FFFAFA', 'springgreen' => '00FF7F', 'steelblue' => '4682B4', 'tan' => 'D2B48C', 'teal' => '008080', 'thistle' => 'D8BFD8', 'tomato' => 'FF6347', 'turquoise' => '40E0D0', 'violet' => 'EE82EE', 'wheat' => 'F5DEB3', 'white' => 'FFFFFF', 'whitesmoke' => 'F5F5F5', 'yellow' => 'FFFF00', 'yellowgreen' => '9ACD32'); if (is_array($color)) { $color = $color[0]; } // Remove any spaces and special characters before and after the string $color = trim($color); // Check if the color is a standard word-color. // If it is, then convert to hex. if (array_key_exists($color, $word_colors)) { $color = $word_colors[$color]; } // Remove any trailing '#' symbols from the color value $color = str_replace('#', '', $color); // If the string is 6 characters long then use it in pairs. if (3 == strlen($color)) { $color = substr($color, 0, 1) . substr($color, 0, 1) . substr($color, 1, 1) . substr($color, 1, 1) . substr($color, 2, 1) . substr($color, 2, 1); } $substr = array(); for ($i = 0; $i <= 5; $i++) { $default = 0 == $i ? 'F' : $substr[$i - 1]; $substr[$i] = substr($color, $i, 1); $substr[$i] = false === $substr[$i] || !ctype_xdigit($substr[$i]) ? $default : $substr[$i]; } $hex = implode('', $substr); return !$hash ? $hex : '#' . $hex; }
/** * Ajax call from browser * @param SS_HTTPRequest $request sent by browser * @return string json response to send to back to the browser */ public function analyse(SS_HTTPRequest $request) { // Set the tenon options $tenon_options = $this->buildOptions($request); // Origin check if (strpos($request->postVar('tURL'), Director::absoluteURL(Director::baseURL())) === 0) { // Only proceed if the key is set if (strlen(trim($tenon_options["key"])) > 28 && ctype_xdigit(trim($tenon_options["key"]))) { // Store the page and create a hash of its contents $this->tenon_page = $request->postVar('tURL'); $this->tenon_hash = $this->createHash($request); $this->log("TenonAjax.requestTenon", "url=" . $this->tenon_url . ", options=" . print_r($tenon_options, true)); // If the page/hash combination has not already been checked, do it now if (!$this->existingPageHash()) { if ($this->requestSend($tenon_options) && $this->responseSave() && $this->savePageHash()) { $out = $this->jsonResponse(true); $this->log("TenonAjax.analyse", "out={$out}"); return $out; } } } } else { $this->log('Invalid request received by ' . Director::absoluteURL(Director::baseURL()) . ' from ' . $request->postVar('tURL')); } return $this->jsonResponse(false); }
function get_select_box() { $return = (object) ["options" => $this->get_icons()]; if (isset($_REQUEST["layout_id"]) && ctype_xdigit($_REQUEST["layout_id"]) && isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"])) { $field_id = $_REQUEST["layout_id"]; $post_id = $_REQUEST["id"]; } else { wp_send_json_success($return); } $post = get_post($post_id); $post_obj = unserialize($post->post_content); $found = false; foreach ($post_obj["layouts"] as $obj) { if ($obj["key"] == $field_id) { $found = true; break; } } if (!$found) { wp_send_json_success($return); } if (is_array($obj) && isset($obj["icon"])) { if (!empty($obj["icon"])) { $return->icon = $obj["icon"]; wp_send_json_success($return); } else { wp_send_json_success($return); } } else { wp_send_json_success($return); } }
public function delete() { if (count($this->messageIds) > 0) { foreach ($this->messageIds as $i => $row) { if (is_numeric($row['id'])) { $mngData[] = array('_id' => new MongoId(substr(hash('sha1', $row['id']), 0, 24)), 'modKey' => isset($row['modKey']) ? hash('sha512', $row['modKey']) : ''); } else { if (ctype_xdigit($row['id'])) { $mngData[] = array('_id' => new MongoId($row['id']), 'modKey' => isset($row['modKey']) ? hash('sha512', $row['modKey']) : ''); } } } $mngDataAgregate = array('$or' => $mngData); if ($ref = Yii::app()->mongo->findAll('personalFolders', $mngDataAgregate, array('_id' => 1, 'file' => 1))) { foreach ($ref as $doc) { if ($files = json_decode($doc['file'], true)) { foreach ($files as $names) { FileWorks::deleteFile($names); } } } } if (Yii::app()->mongo->removeAll('personalFolders', $mngDataAgregate)) { echo '{"results":"success"}'; } else { echo '{"results":"fail"}'; } } }
public function retrieve($id) { if (!ctype_xdigit($id)) { throw new Exception\ClientException('Job ID is invalid'); } return $this->get("jobs/{$id}"); }
public function show() { //move new email to mongo if (is_numeric($this->messageId)) { $query = array('_id' => new MongoId(substr(hash('sha1', $this->messageId), 0, 24)), 'modKey' => hash('sha512', $this->modKey)); if ($ref = Yii::app()->mongo->findOne('personalFolders', $query, array('_id' => 1, 'meta' => 1, 'body' => 1))) { $result['results']['messageHash'] = $this->messageId; $result['results']['meta'] = base64_encode(substr($ref['meta']->bin, 0, 16)) . ';' . base64_encode(substr($ref['meta']->bin, 16)); $result['results']['body'] = base64_encode(substr($ref['body']->bin, 0, 16)) . ';' . base64_encode(substr($ref['body']->bin, 16)); echo json_encode($result); } else { echo '{"results":"empty"}'; } } else { if (ctype_xdigit($this->messageId) && strlen($this->messageId) == 24) { $query = array('_id' => new MongoId($this->messageId), 'modKey' => hash('sha512', $this->modKey)); if ($ref = Yii::app()->mongo->findOne('personalFolders', $query, array('_id' => 1, 'meta' => 1, 'body' => 1))) { $result['results']['messageHash'] = $this->messageId; $result['results']['meta'] = base64_encode(substr($ref['meta']->bin, 0, 16)) . ';' . base64_encode(substr($ref['meta']->bin, 16)); $result['results']['body'] = base64_encode(substr($ref['body']->bin, 0, 16)) . ';' . base64_encode(substr($ref['body']->bin, 16)); echo json_encode($result); } else { echo '{"results":"empty"}'; } } else { echo '{"results":"empty"}'; } } }
public function extendedCode($command, $value) { if (!ctype_xdigit($command) || !ctype_xdigit($value)) { throw new \Exception("Command and value in custom extended code must both be hex codes."); } return $this->rawCommand(__METHOD__, func_get_args(), "{$command} {$value}"); }
public function trackEtl($data = [], $history = true, $callSave = false) { $data = array_merge(['action' => 'Record synced by ETL'], $data); $etl = $this->etl ? $this->etl : new \Winponta\ETL\Models\Jenssegers\Mongodb\Etl(); $etl->touch(); foreach ($data as $key => $value) { $etl->{$key} = $value; } if ($history && count($this->original) > 0) { $history = new \Winponta\ETL\Models\Jenssegers\Mongodb\EtlDocumentHistory(); if (is_string($this->id) and strlen($this->id) === 24 and ctype_xdigit($this->id)) { $history->document_id = new ObjectID($this->id); } else { $history->document_id = null; } $history->document_type = static::class; $history->document = $this->original; $history->save(); } if ($callSave) { $this->etl()->save($etl); } else { $this->etl()->associate($etl); } }
public static function decrypt($string, $key = null, $salt = null, $iv = null) { $config = ConfigManager::getConfig('Crypto', 'AES256')->AuxConfig; if ($key === null) { $key = $config->key; } if ($salt === null) { $salt = $config->salt; } if ($iv === null) { $iv = $config->iv; } $td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, ''); $ks = mcrypt_enc_get_key_size($td); $bs = mcrypt_enc_get_block_size($td); $iv = substr(hash("sha256", $iv), 0, $bs); // Create key $key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks); // Initialize encryption module for decryption mcrypt_generic_init($td, $key, $iv); $decryptedString = ""; // Decrypt encrypted string try { if (ctype_xdigit($string)) { $decryptedString = trim(mdecrypt_generic($td, pack("H*", $string))); } } catch (ErrorException $e) { } // Terminate decryption handle and close module mcrypt_generic_deinit($td); mcrypt_module_close($td); // Show string return $decryptedString; }
public function send($mac, $ip, $subnet = null) { // Reset the last error $this->lastError = 0; // If we're not given a subnet assume a broadcast IP if (is_null($subnet)) { $broadcastIP = $ip; } else { $broadcastIP = $this->getBroadcastIP($ip, $subnet); } $hexMac = str_replace(':', '', $mac); if (!ctype_xdigit($hexMac) || strlen($hexMac) != 12) { $this->lastError = self::ERR_INVALID_MAC; return false; } if (!filter_var($broadcastIP, FILTER_VALIDATE_IP)) { $this->lastError = self::ERR_INVALID_IP; return false; } $binMac = pack('H12', $hexMac); $prefix = pack('H12', str_repeat('FF', 6)); $magicPacket = $prefix . str_repeat($binMac, 16); $this->socket->sendBroadcastUDP($magicPacket, $broadcastIP, 7); return true; }
function getRGB($colorStr) { $colorStr = @ltrim($colorStr, "#"); $colorKeys = array("r", "g", "b"); // The color string must be a valid hexadecimal value. if (!ctype_xdigit($colorStr)) { return false; } // ColorStr is in the long format -> AA22CC if (strlen($colorStr) === 6) { $colors = array_combine($colorKeys, sscanf($colorStr, "%2x%2x%2x")); } else { if (strlen($colorStr) === 3) { $tmpColors = sscanf($colorStr, "%1s%1s%1s"); // Expand the shortened color code to the actual value. for ($i = 0; $i < count($tmpColors); $i++) { $tmpColors[$i] = hexdec($tmpColors[$i] . $tmpColors[$i]); } $colors = array_combine($colorKeys, $tmpColors); } else { return false; } } return $colors; }
/** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { static $colors = null; if ($colors === null) { $colors = $config->get('Core.ColorKeywords'); } $string = trim($string); if (empty($string)) { return false; } $lower = strtolower($string); if (isset($colors[$lower])) { return $colors[$lower]; } if ($string[0] === '#') { $hex = substr($string, 1); } else { $hex = $string; } $length = strlen($hex); if ($length !== 3 && $length !== 6) { return false; } if (!ctype_xdigit($hex)) { return false; } if ($length === 3) { $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; } return "#{$hex}"; }
function testSaltedFieldnameIsHashed() { $input = new T_Form_Upload('myalias', 'mylabel'); $input->setFieldnameSalt('mysalt', new T_Filter_RepeatableHash()); $this->assertNotEquals('myalias', $input->getFieldname()); $this->assertTrue(ctype_xdigit($input->getFieldname())); }
/** * Checks if value is a valid HEX color. * * @param mixed $value * * @throws InvalidArgumentException */ protected function validate($value) { $colorCode = ltrim($value, '#'); if (!ctype_xdigit($colorCode) || strlen($colorCode) !== 6 && strlen($colorCode) !== 3) { throw new InvalidArgumentException('HEX color is invalid: ' . $value); } }
public static function init() { if (!ctype_xdigit(Config::get('encryption.cipher'))) { throw new Exception('Change your cipher code in app/config/encryption.php file!'); } static::$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); static::$key = pack('H*', Config::get('encryption.cipher')); }
/** * Checks that the data is a valid hexadecimal hash (32 characters long). * * @param string $value data to filter * @return string hex hash * @throws T_Exception_Filter if the input is not a valid hex hash */ protected function doTransform($value) { if (!ctype_xdigit($value) || strlen($value) !== 32) { throw new T_Exception_Filter("Invalid hexadecimal 32-char hash {$value}"); } return $value; }