/** * JSON encode a PHP value. * * @param {void*} $value Any arbitrary PHP value. * @return {string} JSON representation of specified PHP value. */ public static function json($value) { // note: binary strings will f**k up the encoding process, remove them. $maskBinary = function (&$value) use(&$maskBinary) { if ($value instanceof \JsonSerializable) { $value = $value->jsonSerialize(); } if (is_object($value)) { foreach (get_object_vars($value) as $key => $_value) { $maskBinary($value->{$key}); } unset($_value); } else { if (is_array($value)) { array_walk($value, $maskBinary); } else { if (is_string($value) && $value && !ctype_print($value) && json_encode($value) === false) { $value = '[binary string]'; } } } }; $maskBinary($value); return json_encode($value); }
/** * Constructor * * @param array $config Configuration settings: * 'realm' => <string> * 'identity' => <string> The identity to match * 'credential' => <string> The credential to match * @throws Zend_Auth_Adapter_Exception * @return void */ public function __construct(array $config) { if (empty($config['identity'])) { throw new Zend_Auth_Adapter_Exception('Config key identity is required'); } else { $this->_identity = $config['identity']; } if (empty($config['credential'])) { throw new Zend_Auth_Adapter_Exception('Config key credential is required'); } else { $this->_credential = $config['credential']; } // Taken from Zend_Auth_Adapter_Http // Double-quotes are used to delimit the realm string in the HTTP header, // and colons are field delimiters in the password file. if (empty($config['realm']) || !ctype_print($config['realm']) || strpos($config['realm'], ':') !== false || strpos($config['realm'], '"') !== false) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Config key \'realm\' is required, and must contain only printable ' . 'characters, excluding quotation marks and colons'); } else { $this->_realm = $config['realm']; } }
/** * @param string $label * * @return AccessTokenInterface */ public function setLabel($label) { if (!empty($label) && is_string($label) && ctype_print($label)) { $this->label = trim($label); } return $this; }
/** * Performs an authentication attempt * * @return \Zend\Authentication\Result * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed */ public function authenticate() { $getHeader = $this->options['proxy_auth'] ? 'Proxy-Authorization' : 'Authorization'; if (!($authHeader = $this->request->headers->get($getHeader))) { return $this->challengeClient(); } // Decode the Authorization header $authorizationHeader = base64_decode(substr($authHeader, strlen('Basic '))); if (!$authorizationHeader) { throw new RuntimeException('Unable to base64_decode Authorization header value'); } // See ZF-1253. Validate the credentials the same way the digest // implementation does. If invalid credentials are detected, // re-challenge the client. if (!ctype_print($authorizationHeader)) { return $this->challengeClient(); } // Fix for ZF-1515: Now re-challenges on empty username or password $credentials = array_filter(explode(':', $authorizationHeader)); if (count($credentials) !== 2) { return $this->challengeClient(); } $result = $this->resolver->resolve($credentials[0], $this->options['realm'], $credentials[1]); if ($result instanceof Result && $result->isValid()) { return $result; } if (!$result instanceof Result && !is_array($result) && Utils::compareStrings($result, $credentials[1])) { $identity = ['username' => $credentials[0], 'realm' => $this->options['realm']]; return new Result(Result::SUCCESS, $identity); } elseif (is_array($result)) { return new Result(Result::SUCCESS, $result); } return $this->challengeClient(); }
/** * Generate the downloadable path for a song. * * @param Song $song * * @return string */ protected function fromSong(Song $song) { if ($s3Params = $song->s3_params) { // The song is hosted on Amazon S3. // We download it back to our local server first. $localPath = rtrim(sys_get_temp_dir(), '/') . '/' . basename($s3Params['key']); $url = $song->getObjectStoragePublicUrl(); abort_unless($url, 404); // The following function require allow_url_fopen to be ON. // We're just assuming that to be the case here. copy($url, $localPath); } else { // The song is hosted locally. Make sure the file exists. abort_unless(file_exists($song->path), 404); $localPath = $song->path; } // The BinaryFileResponse factory only accept ASCII-only file names. if (ctype_print($localPath)) { return $localPath; } // For those with high-byte characters in names, we copy it into a safe name // as a workaround. $newPath = rtrim(sys_get_temp_dir(), '/') . '/' . utf8_decode(basename($song->path)); if ($s3Params) { // If the file is downloaded from S3, we rename it directly. // This will save us some disk space. rename($localPath, $newPath); } else { // Else we copy it to another file to not mess up the original one. copy($localPath, $newPath); } return $newPath; }
public function insertAll($rows) { $generic = Factory::getGeneric(); $rowsSql = array(); foreach ($rows as $row) { $values = array(); foreach ($row as $name => $value) { if (is_null($value)) { $values[] = 'NULL'; } else { if (is_numeric($value)) { $values[] = $value; } else { if (!ctype_print($value)) { $values[] = $generic->bin2dbRawInsert($value); } else { if (is_bool($value)) { $values[] = $value ? '1' : '0'; } else { $values[] = "'{$value}'"; } } } } } $rowsSql[] = "(" . implode(',', $values) . ")"; } $sql = 'INSERT INTO ' . $this->table . ' VALUES ' . implode(',', $rowsSql); $this->db->query($sql); }
/** * {@inheritdoc} */ public function read($filename) { $meta = new ValueBag(); try { $fileEntity = $this->reader->reset()->files($filename)->first(); } catch (\Exception $e) { return $meta; } if ($fileEntity->getMetadatas()->containsKey('File:ImageWidth')) { $meta->set('image.width', new MetaValue((int) $fileEntity->getMetadatas()->get('File:ImageWidth')->getValue()->asString())); } elseif ($fileEntity->getMetadatas()->containsKey('PNG:ImageWidth')) { $meta->set('image.width', new MetaValue((int) $fileEntity->getMetadatas()->get('PNG:ImageWidth')->getValue()->asString())); } if ($fileEntity->getMetadatas()->containsKey('File:ImageHeight')) { $meta->set('image.height', new MetaValue((int) $fileEntity->getMetadatas()->get('File:ImageHeight')->getValue()->asString())); } elseif ($fileEntity->getMetadatas()->containsKey('PNG:ImageHeight')) { $meta->set('image.height', new MetaValue((int) $fileEntity->getMetadatas()->get('PNG:ImageHeight')->getValue()->asString())); } foreach ($fileEntity->getMetadatas() as $metadata) { /* @var $metadata Metadata */ if (ValueInterface::TYPE_BINARY === $metadata->getValue()->getType()) { continue; } $groupName = $metadata->getTag()->getGroupName(); $name = $metadata->getTag()->getName(); $value = (string) $metadata->getValue(); if ($groupName === 'System' || !ctype_print($value)) { continue; } $path = "{$groupName}.{$name}"; $meta->set($path, new MetaValue($value)); } return $meta; }
public function isValid($value) { if (ctype_print($value)) { return true; } $this->setError("invalid"); return false; }
/** * Static function to create a new Imagecow instance from an image file or string * * @param string $image The name of the image file or binary string * @param string $library The name of the image library to use (Gd or Imagick). If it's not defined, detects automatically the library to use. * * @return Image The Imagecow instance */ public static function create($image, $library = null) { //check if it's a binary string if (!ctype_print($image)) { return static::createFromString($image, $library); } return static::createFromFile($image, $library); }
/** * Retrieve accept language * * @return string */ protected function getAcceptLanguage() { $acceptLanguage = empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? null : $_SERVER['HTTP_ACCEPT_LANGUAGE']; if (!ctype_print($acceptLanguage)) { $acceptLanguage = null; } return $acceptLanguage; }
public function testGenerateToken() { $token = $this->generator->generateToken(); $this->assertTrue(ctype_print($token), 'is printable'); $this->assertStringNotMatchesFormat('%S+%S', $token, 'is URI safe'); $this->assertStringNotMatchesFormat('%S/%S', $token, 'is URI safe'); $this->assertStringNotMatchesFormat('%S=%S', $token, 'is URI safe'); }
/** * Helper function to transform the ip and format it correctly for extraction. * If inputted with a string, it will leave it the same. * If inputted with a binary string, it will output an unpacked human readable string. * * @return $ip string */ public function extract($ip) { //human readable string if (ctype_print($ip)) { return $ip; } return inet_ntop($ip); }
/** * Modified find static function to accept both string and binary versions of uuid * @param mixed $id The id (binary or hex string) * @param array $columns The columns to be returned (defaults to *) * @return mixed The model or null */ public static function find($id, $columns = array('*')) { if (ctype_print($id)) { return static::where('id', '=', hex2bin($id))->first($columns); } else { return parent::where('id', '=', $id)->first($columns); } }
/** * Modified findOrFail static function to accept both string and binary versions of uuid * @param mixed $id The id (binary or hex string) * @param array $columns The columns to be returned (defaults to *) * @return mixed The model or null */ public static function findOrFail($id, $columns = array('*')) { if (ctype_print($id)) { $idFinal = property_exists(static::class, 'uuidOptimization') && static::$uuidOptimization ? self::toOptimized($id) : hex2bin($id); return static::where('id', '=', $idFinal)->firstOrFail($columns); } else { return parent::where('id', '=', $id)->firstOrFail($columns); } }
/** * @param string $type type of MFA, used in audit logs * @param string $message user-friendly message used in player kick message * @param string $data printable, single-line string used in audit logs as data for this * * @throws \InvalidArgumentException if $data is not printable or single-line */ public function __construct($type, $message, $data = "") { if (!ctype_print($data)) { throw new \InvalidArgumentException("\$data is not printable"); } $this->type = $type; $this->message = $message; $this->data = $data; }
public function testGenerateToken() { $this->random->expects($this->once())->method('nextBytes')->with(self::ENTROPY / 8)->will($this->returnValue(self::$bytes)); $token = $this->generator->generateToken(); $this->assertTrue(ctype_print($token), 'is printable'); $this->assertStringNotMatchesFormat('%S+%S', $token, 'is URI safe'); $this->assertStringNotMatchesFormat('%S/%S', $token, 'is URI safe'); $this->assertStringNotMatchesFormat('%S=%S', $token, 'is URI safe'); }
function is_ascii($sourcefile) { if (is_file($sourcefile)) { $content = str_replace(array("\n", "\r", "\t", "\v", "\\b"), '', file_get_contents($sourcefile)); return ctype_print($content); } else { return false; } }
/** * Assertion Consumer Service * * The user gets sent back here after authenticating with the IdP, off-site. * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate. * * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows * LDAP side of this module to finish off loading Member data. * * @throws OneLogin_Saml2_Error */ public function acs() { $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth(); $auth->processResponse(); $error = $auth->getLastErrorReason(); if (!empty($error)) { SS_Log::log($error, SS_Log::ERR); Form::messageForForm("SAMLLoginForm_LoginForm", "Authentication error: '{$error}'", 'bad'); Session::save(); return $this->getRedirect(); } if (!$auth->isAuthenticated()) { Form::messageForForm("SAMLLoginForm_LoginForm", _t('Member.ERRORWRONGCRED'), 'bad'); Session::save(); return $this->getRedirect(); } $decodedNameId = base64_decode($auth->getNameId()); // check that the NameID is a binary string (which signals that it is a guid if (ctype_print($decodedNameId)) { Form::messageForForm("SAMLLoginForm_LoginForm", "Name ID provided by IdP is not a binary GUID.", 'bad'); Session::save(); return $this->getRedirect(); } // transform the NameId to guid $guid = LDAPUtil::bin_to_str_guid($decodedNameId); if (!LDAPUtil::validGuid($guid)) { $errorMessage = "Not a valid GUID '{$guid}' recieved from server."; SS_Log::log($errorMessage, SS_Log::ERR); Form::messageForForm("SAMLLoginForm_LoginForm", $errorMessage, 'bad'); Session::save(); return $this->getRedirect(); } // Write a rudimentary member with basic fields on every login, so that we at least have something // if LDAP synchronisation fails. $member = Member::get()->filter('GUID', $guid)->limit(1)->first(); if (!($member && $member->exists())) { $member = new Member(); $member->GUID = $guid; } $attributes = $auth->getAttributes(); foreach ($member->config()->claims_field_mappings as $claim => $field) { if (!isset($attributes[$claim][0])) { SS_Log::log(sprintf('Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, but wasn\'t passed through. Please check IdP claim rules.', $claim), SS_Log::WARN); continue; } $member->{$field} = $attributes[$claim][0]; } $member->SAMLSessionIndex = $auth->getSessionIndex(); // This will throw an exception if there are two distinct GUIDs with the same email address. // We are happy with a raw 500 here at this stage. $member->write(); // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn. // Both SAML and LDAP identify Members by the GUID field. $member->logIn(); return $this->getRedirect(); }
function is_binary($input) { if (is_null($input)) { return false; } if (is_integer($input)) { return false; } return !ctype_print($input); }
/** * @dataProvider provideItemsOfSupportedTypes */ public function testPush($item) { $serializedItem = null; $this->innerQueue->expects($this->once())->method('push')->with($this->callback(function ($subject) use(&$serializedItem) { $serializedItem = $subject; return is_string($subject) && ctype_print($subject); })); $this->queue->push($item); return ['original' => $item, 'serialized' => $serializedItem]; }
/** * Creates images on filesystem * * @throws \Exception * @return string */ public function create() { // If chars are printable, this is probably not a binary if (ctype_print($this->getBinaryData()) || !$this->getBinaryData()) { throw new \Exception('The image content must be valid binary data'); } $imageFileContent = $this->getBinaryData(); $imageFileName = $this->_getFileName(); $type = $this->getType(); switch ($type) { case 'local': $smTempDirTopLevel = \Mage::getBaseDir('var') . DS . 'sm'; $smTempDir = $smTempDirTopLevel . DS . \Mage::helper('core')->uniqHash(); $ioAdapter = new \Varien_Io_File(); $ioAdapter->checkAndCreateFolder($smTempDir); $ioAdapter->open(array('path' => $smTempDir)); $ioAdapter->write($imageFileName, $imageFileContent, 0666); unset($imageFileContent); // try to create Image object to check if image data is valid try { new \Varien_Image($smTempDir . DS . $imageFileName); } catch (\Exception $e) { $ioAdapter->rmdir($smTempDir, true); throw new \Exception($e->getMessage()); } $product = $this->getProduct(); if ($product->getId()) { // Delete existing image of the same type $this->_delete(); } $imageFileUri = $this->_getMediaGallery()->addImage($product, $smTempDir . DS . $imageFileName, $this->getTypes(), true); $ioAdapter->rmdir($smTempDir, true); if ($this->hasTypes()) { $this->_getMediaGallery()->setMediaAttribute($product, $this->getTypes(), $imageFileUri); } break; case 'favicon': case 'theme': $destFolder = \Mage::getBaseDir('media') . DS . $type; $ioAdapter = new \Varien_Io_File(); $ioAdapter->checkAndCreateFolder($destFolder); $ioAdapter->open(array('path' => $destFolder)); $ioAdapter->write($imageFileName, $imageFileContent, 0666); unset($imageFileContent); // try to create Image object to check if image data is valid try { new \Varien_Image($destFolder . DS . $imageFileName); } catch (\Exception $e) { $ioAdapter->rmdir($destFolder, true); throw new \Exception($e->getMessage()); } break; } return $this; }
/** * Normalize Path * * @param string $key * @param string $virtualSeperator * @return string */ private function prepareVirtualPath($key, $virtualSeperator) { $keylen = strlen($key); for ($i = 0; $i < $keylen; ++$i) { $c = $key[$i]; if ($c === '/' || $c === '\\' || $c === ':' || ctype_print($c) === false) { $key[$i] = $virtualSeperator; } } return strtolower($key); }
/** * Validate printable characters. * * Check that given value contains only printable characters. * * @param $input * @param ValidationInfo $info * * @return string * * @throws Invalid */ public static function printable($input, ValidationInfo $info = null) { if (ctype_print($input)) { return $input; } if ($info && $info->fix) { //remove non printable characters return preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $input); } throw new Invalid('Expecting only printable characters.'); }
/** * Constructor * * @param string|null $filename * @param bool|null $strict * * @throws Exception * @throws \JBZoo\Utils\Exception */ public function __construct($filename = null, $strict = false) { Helper::checkGD(); if (ctype_print($filename) && FS::isFile($filename)) { $this->loadFile($filename); } elseif (Helper::isGdRes($filename)) { $this->loadResource($filename); } elseif (is_string($filename) && $filename) { $this->loadString($filename, $strict); } }
public function XPath($string) { if (is_object($this->domObject) && ctype_print($string)) { $xp = new domXPath($this->domObject); $q = $xp->query($string); $tmpArray = array(); foreach ($q as $node) { $tmpArray[] = $node->textContent; } return $tmpArray; } }
/** * @param mixed $values * @return mixed */ public static function encodeValues($values) { array_walk_recursive($values, function (&$value) { if ($value instanceof DateTimeInterface) { $value = $value->format(DateTime::ISO8601); Xmlrpc::setType($value, 'datetime'); } if (!ctype_print($value)) { Xmlrpc::setType($value, 'base64'); } }); return $values; }
function quoted_printable_encode($str, $wrap = true) { $ret = ''; $l = strLen($str); $current_locale = setLocale(LC_CTYPE, 0); setLocale(LC_CTYPE, 'C'); for ($i = 0; $i < $l; ++$i) { $char = $str[$i]; if (ctype_print($char) && !ctype_cntrl($char) && $char !== '=') { $ret .= $char; } else { $ret .= sPrintF('=%02X', ord($char)); } } setLocale(LC_CTYPE, $current_locale); return $wrap ? wordWrap($ret, 67, " =\n") : $ret; }
/** * Constructor tries to guess what is the $ip * * @param $ip mixed String, binary string, int or float */ public function __construct($ip) { if (is_int($ip)) { // if an integer is provided, we have to be careful of the architecture // on 32 bits plateform, it's always a valid IP // on 64 bits plateform, we have to test the value $ip = gmp_init(sprintf('%u', $ip), 10); if (gmp_cmp($ip, self::MAX_INT) > 0) { throw new InvalidArgumentException(sprintf('The integer %s is not a valid IPv4 address', gmp_strval($ip))); } $this->ip = $ip; } elseif (is_float($ip) && floor($ip) == $ip) { // float (or double) with an integer value $ip = gmp_init(sprintf('%s', $ip), 10); if (gmp_cmp($ip, 0) < 0 || gmp_cmp($ip, self::MAX_INT) > 0) { throw new InvalidArgumentException(sprintf('The double %s is not a valid IPv4 address', gmp_strval($ip))); } $this->ip = $ip; } elseif (is_string($ip)) { // binary string if (!ctype_print($ip)) { if (strlen($ip) != 4) { throw new InvalidArgumentException("The binary string is not a valid IPv4 address"); } $hex = unpack('H*', $ip); $this->ip = gmp_init($hex[1], 16); } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $this->ip = gmp_init(sprintf('%u', ip2long($ip))); } elseif (ctype_digit($ip)) { $ip = gmp_init($ip); if (gmp_cmp($ip, self::MAX_INT) > 0) { throw new InvalidArgumentException(sprintf("%s is not a valid decimal IPv4 address", gmp_strval($ip))); } $this->ip = $ip; } else { throw new InvalidArgumentException("{$ip} is not a valid IPv4 address"); } } elseif (is_resource($ip) && get_resource_type($ip) == 'GMP integer' || $ip instanceof GMP) { if (gmp_cmp($ip, 0) < 0 || gmp_cmp($ip, self::MAX_INT) > 0) { throw new InvalidArgumentException(sprintf("%s is not a valid decimal IPv4 address", gmp_strval($ip))); } $this->ip = $ip; } else { throw new InvalidArgumentException("Unsupported argument type: " . gettype($ip)); } }
public function cleanTeamName($name) { // check if every character is printable if (ctype_print($name)) { // strip whitespace or other characters from beginning and end of the name $cleaned_name = trim($name); // "(teamless)" is a reserved name if (strcasecmp($_POST['edit_team_name'], '(teamless)') === 0) { $cleaned_name = ''; } // check if cleaned team name is different than user entered team name if (strcmp($name, $cleaned_name) === 0) { return true; } } return false; }