Beispiel #1
1
 function convert_uudecode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     if (strlen($string) < 8) {
         user_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING);
         return false;
     }
     $decoded = '';
     foreach (explode("\n", $string) as $line) {
         $c = count($bytes = unpack('c*', substr(trim($line), 1)));
         while ($c % 4) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 4) as $b) {
             $b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20;
             $b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20;
             $b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20;
             $b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20;
             $b0 <<= 2;
             $b0 |= $b1 >> 4 & 0x3;
             $b1 <<= 4;
             $b1 |= $b2 >> 2 & 0xf;
             $b2 <<= 6;
             $b2 |= $b3 & 0x3f;
             $decoded .= pack('c*', $b0, $b1, $b2);
         }
     }
     return rtrim($decoded, "");
 }
Beispiel #2
1
 /**
  * Sets selected items (by keys).
  * @param  array
  * @return self
  */
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = [];
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     if ($this->checkAllowedValues && ($diff = array_diff($values, array_keys($this->items)))) {
         $set = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, array_keys($this->items))), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed set [{$set}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
 public function __construct($value)
 {
     if (!is_scalar($value) && null !== $value) {
         throw new InvalidNativeArgumentException($value, ['string', 'int', 'bool', 'null']);
     }
     $this->value = $value;
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof Length) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Length');
     }
     if (null === $value || '' === $value) {
         return;
     }
     if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
         throw new UnexpectedTypeException($value, 'string');
     }
     $stringValue = (string) $value;
     if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
         $length = grapheme_strlen($stringValue);
     } elseif (function_exists('mb_strlen')) {
         $length = mb_strlen($stringValue, $constraint->charset);
     } else {
         $length = strlen($stringValue);
     }
     if (null !== $constraint->max && $length > $constraint->max) {
         $this->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->maxMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->max)->setInvalidValue($value)->setPlural((int) $constraint->max)->setCode(Length::TOO_LONG_ERROR)->addViolation();
         return;
     }
     if (null !== $constraint->min && $length < $constraint->min) {
         $this->buildViolation($constraint->min == $constraint->max ? $constraint->exactMessage : $constraint->minMessage)->setParameter('{{ value }}', $this->formatValue($stringValue))->setParameter('{{ limit }}', $constraint->min)->setInvalidValue($value)->setPlural((int) $constraint->min)->setCode(Length::TOO_SHORT_ERROR)->addViolation();
     }
 }
Beispiel #5
0
 public function validate($input)
 {
     if (!is_scalar($input)) {
         return false;
     }
     return (bool) preg_match($this->regex, $input);
 }
Beispiel #6
0
 function convert_uuencode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     $u = 0;
     $encoded = '';
     while ($c = count($bytes = unpack('c*', substr($string, $u, 45)))) {
         $u += 45;
         $encoded .= pack('c', $c + 0x20);
         while ($c % 3) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 3) as $b) {
             $b0 = ($b[0] & 0xfc) >> 2;
             $b1 = (($b[0] & 0x3) << 4) + (($b[1] & 0xf0) >> 4);
             $b2 = (($b[1] & 0xf) << 2) + (($b[2] & 0xc0) >> 6);
             $b3 = $b[2] & 0x3f;
             $b0 = $b0 ? $b0 + 0x20 : 0x60;
             $b1 = $b1 ? $b1 + 0x20 : 0x60;
             $b2 = $b2 ? $b2 + 0x20 : 0x60;
             $b3 = $b3 ? $b3 + 0x20 : 0x60;
             $encoded .= pack('c*', $b0, $b1, $b2, $b3);
         }
         $encoded .= "\n";
     }
     // Add termination characters
     $encoded .= "`\n";
     return $encoded;
 }
Beispiel #7
0
 public function setValue($values)
 {
     if (is_scalar($values) || $values === NULL) {
         $values = (array) $values;
     } elseif (!is_array($values)) {
         throw new Nette\InvalidArgumentException(sprintf("Value must be array or NULL, %s given in field '%s'.", gettype($values), $this->name));
     }
     $flip = array();
     foreach ($values as $value) {
         if (!is_scalar($value) && !method_exists($value, '__toString')) {
             throw new Nette\InvalidArgumentException(sprintf("Values must be scalar, %s given in field '%s'.", gettype($value), $this->name));
         }
         $flip[(string) $value] = TRUE;
     }
     $values = array_keys($flip);
     $items = $this->items;
     $nestedKeys = array();
     array_walk_recursive($items, function ($value, $key) use(&$nestedKeys) {
         $nestedKeys[] = $key;
     });
     if ($diff = array_diff($values, $nestedKeys)) {
         $range = Nette\Utils\Strings::truncate(implode(', ', array_map(function ($s) {
             return var_export($s, TRUE);
         }, $nestedKeys)), 70, '...');
         $vals = (count($diff) > 1 ? 's' : '') . " '" . implode("', '", $diff) . "'";
         throw new Nette\InvalidArgumentException("Value{$vals} are out of allowed range [{$range}] in field '{$this->name}'.");
     }
     $this->value = $values;
     return $this;
 }
 protected function normalize($data)
 {
     if (null === $data || is_scalar($data)) {
         return $data;
     }
     if (is_array($data) || $data instanceof \Traversable) {
         $normalized = array();
         $count = 1;
         foreach ($data as $key => $value) {
             if ($count++ >= 1000) {
                 $normalized['...'] = 'Over 1000 items, aborting normalization';
                 break;
             }
             $normalized[$key] = $this->normalize($value);
         }
         return $normalized;
     }
     if ($data instanceof \DateTime) {
         return $data->format($this->dateFormat);
     }
     if (is_object($data)) {
         if ($data instanceof Exception) {
             return $this->normalizeException($data);
         }
         return sprintf("[object] (%s: %s)", get_class($data), $this->toJson($data, true));
     }
     if (is_resource($data)) {
         return '[resource]';
     }
     return '[unknown(' . gettype($data) . ')]';
 }
Beispiel #9
0
 function bcinvert($a, $n)
 {
     // Sanity check
     if (!is_scalar($a)) {
         user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($n)) {
         user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING);
         return false;
     }
     $u1 = $v2 = '1';
     $u2 = $v1 = '0';
     $u3 = $n;
     $v3 = $a;
     while (bccomp($v3, '0')) {
         $q0 = bcdiv($u3, $v3);
         $t1 = bcsub($u1, bcmul($q0, $v1));
         $t2 = bcsub($u2, bcmul($q0, $v2));
         $t3 = bcsub($u3, bcmul($q0, $v3));
         $u1 = $v1;
         $u2 = $v2;
         $u3 = $v3;
         $v1 = $t1;
         $v2 = $t2;
         $v3 = $t3;
     }
     if (bccomp($u2, '0') < 0) {
         return bcadd($u2, $n);
     } else {
         return bcmod($u2, $n);
     }
 }
Beispiel #10
0
 /**
  * Add a single value to the Parameter
  * @param mixed $value 
  */
 public function addValue($value)
 {
     if (!is_scalar($value)) {
         throw new Exception('Only scalar values permitted');
     }
     $this->value[] = $value;
 }
 /**
  * {@inheritdoc}
  */
 public function format(array $record)
 {
     $record = parent::format($record);
     if (!isset($record['datetime'], $record['message'], $record['level'])) {
         throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, ' . var_export($record, true) . ' given');
     }
     $message = new Message();
     $message->setTimestamp($record['datetime'])->setShortMessage((string) $record['message'])->setHost($this->systemName)->setLevel($this->logLevels[$record['level']]);
     if (isset($record['channel'])) {
         $message->setFacility($record['channel']);
     }
     if (isset($record['extra']['line'])) {
         $message->setLine($record['extra']['line']);
         unset($record['extra']['line']);
     }
     if (isset($record['extra']['file'])) {
         $message->setFile($record['extra']['file']);
         unset($record['extra']['file']);
     }
     foreach ($record['extra'] as $key => $val) {
         $message->setAdditional($this->extraPrefix . $key, is_scalar($val) ? $val : $this->toJson($val));
     }
     foreach ($record['context'] as $key => $val) {
         $message->setAdditional($this->contextPrefix . $key, is_scalar($val) ? $val : $this->toJson($val));
     }
     if (null === $message->getFile() && isset($record['context']['exception']['file'])) {
         if (preg_match("/^(.+):([0-9]+)\$/", $record['context']['exception']['file'], $matches)) {
             $message->setFile($matches[1]);
             $message->setLine($matches[2]);
         }
     }
     return $message;
 }
Beispiel #12
0
 /**
  * Converts a value to a DateTime.
  * Supports microseconds
  *
  * @throws InvalidArgumentException if $value is invalid
  * @param  mixed $value \DateTime|\MongoDate|int|float
  * @return \DateTime
  */
 public static function getDateTime($value)
 {
     $datetime = false;
     $exception = null;
     if ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {
         return $value;
     } elseif ($value instanceof \MongoDate) {
         $datetime = static::craftDateTime($value->sec, $value->usec);
     } elseif (is_numeric($value)) {
         $seconds = $value;
         $microseconds = 0;
         if (false !== strpos($value, '.')) {
             list($seconds, $microseconds) = explode('.', $value);
             $microseconds = (int) str_pad((int) $microseconds, 6, '0');
             // ensure microseconds
         }
         $datetime = static::craftDateTime($seconds, $microseconds);
     } elseif (is_string($value)) {
         try {
             $datetime = new \DateTime($value);
         } catch (\Exception $e) {
             $exception = $e;
         }
     }
     if ($datetime === false) {
         throw new \InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception);
     }
     return $datetime;
 }
Beispiel #13
0
 /**
  * @param string $key
  * @param mixed$val
  *
  * @return mixed
  *
  * @throws InvalidArgumentException
  */
 protected function getScalar($key, $val)
 {
     if (!is_scalar($val) && !(is_object($val) && method_exists($val, '__toString'))) {
         throw new InvalidArgumentException(sprintf('%s must be a scalar or implement __toString got "%s".', $key, is_object($val) ? get_class($val) : gettype($val)));
     }
     return is_object($val) ? (string) $val : $val;
 }
/**
 * Replace bcpowmod()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/function.bcpowmod
 * @author      Sara Golemon <*****@*****.**>
 * @version     $Revision: 1.1 $
 * @since       PHP 5.0.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_bcpowmod($x, $y, $modulus, $scale = 0)
{
    // Sanity check
    if (!is_scalar($x)) {
        user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($y)) {
        user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($modulus)) {
        user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($scale)) {
        user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING);
        return false;
    }
    $t = '1';
    while (bccomp($y, '0')) {
        if (bccomp(bcmod($y, '2'), '0')) {
            $t = bcmod(bcmul($t, $x), $modulus);
            $y = bcsub($y, '1');
        }
        $x = bcmod(bcmul($x, $x), $modulus);
        $y = bcdiv($y, '2');
    }
    return $t;
}
 /**
  * Generate a variable name for a given object. 
  * 
  * 
  * * If $value is an object, the generated variable name
  * will be [$object-class-short-name]_$occurence in lower case e.g. 'point_0',
  * 'assessmenttest_3', ... 
  * 
  * * If $value is a PHP scalar value (not including the null value), the generated
  * variable name will be [gettype($value)]_$occurence e.g. 'string_1', 'boolean_0', ...
  * 
  * * If $value is an array, the generated variable name will be array_$occurence such as
  * 'array_0', 'array_2', ...
  * 
  * * If $value is the null value, the generated variable name will be nullvalue_$occurence
  * such as 'nullvalue_3'.
  * 
  * * Finally, if the $value cannot be handled by this method, an InvalidArgumentException
  * is thrown.
  * 
  * @param mixed $value A value.
  * @param integer $occurence An occurence number.
  * @return string A variable name.
  * @throws InvalidArgumentException If $occurence is not a positive integer or if $value cannot be handled by this method.
  */
 public static function variableName($value, $occurence = 0)
 {
     if (is_int($occurence) === false || $occurence < 0) {
         $msg = "The 'occurence' argument must be a positive integer (>= 0).";
         throw new InvalidArgumentException($msg);
     }
     if (is_object($value) === true) {
         $object = new ReflectionObject($value);
         $className = mb_strtolower($object->getShortName(), 'UTF-8');
         return "{$className}_{$occurence}";
     } else {
         // Is it a PHP scalar value?
         if (is_scalar($value) === true) {
             return gettype($value) . '_' . $occurence;
         } else {
             if (is_array($value) === true) {
                 return 'array_' . $occurence;
             } else {
                 if (is_null($value) === true) {
                     return 'nullvalue_' . $occurence;
                 } else {
                     $msg = "Cannot handle the given value.";
                     throw new InvalidArgumentException($msg);
                 }
             }
         }
     }
 }
 protected function createFieldValue($typeMeta, $key, $value)
 {
     $result = null;
     $expectedType = $typeMeta->getType();
     if (is_scalar($value) || is_null($value) || $expectedType === "polymorphic") {
         $result = $value;
     } elseif (is_array($value)) {
         if ($typeMeta->isObjectType() && $typeMeta->isListType()) {
             $result = [];
             foreach ($value as $listValue) {
                 $childObj = $this->objectMetaService->createObject($typeMeta->getTargetClass());
                 $this->fill($childObj, $listValue);
                 $result[] = $childObj;
             }
         } elseif (in_array($expectedType, ["array", "entity", "entitylist"])) {
             $result = $value;
         } else {
             throw new InvalidObjectValueException(sprintf(Translate::t("Invalid value for the `%s` property."), $key));
         }
     } elseif (is_object($value)) {
         if ($expectedType === "map") {
             $result = (array) $value;
         } else {
             if (!$typeMeta->isObjectType()) {
                 throw new InvalidObjectValueException(sprintf(Translate::t("Invalid value for the `%s` property."), $key));
             }
             $result = $this->objectMetaService->createObject($typeMeta->getTargetClass());
             $this->fill($result, $value);
         }
     }
     return $result;
 }
 /**
  * Dumps a node or array.
  *
  * @param array|PHPParser_Node $node Node or array to dump
  *
  * @return string Dumped value
  */
 public function dump($node)
 {
     if ($node instanceof PHPParser_Node) {
         $r = $node->getType() . '(';
     } elseif (is_array($node)) {
         $r = 'array(';
     } else {
         throw new InvalidArgumentException('Can only dump nodes and arrays.');
     }
     foreach ($node as $key => $value) {
         $r .= "\n" . '    ' . $key . ': ';
         if (null === $value) {
             $r .= 'null';
         } elseif (false === $value) {
             $r .= 'false';
         } elseif (true === $value) {
             $r .= 'true';
         } elseif (is_scalar($value)) {
             $r .= $value;
         } else {
             $r .= str_replace("\n", "\n" . '    ', $this->dump($value));
         }
     }
     return $r . "\n" . ')';
 }
Beispiel #18
0
 public function setProductName($productName)
 {
     if (!is_scalar($productName)) {
         throw new \InvalidArgumentException('Invalid name');
     }
     $this->productName = $productName;
 }
 /**
  * Validate data for autocompletion
  *
  * @param  mixed $data
  * @return bool
  */
 public function validateData($data)
 {
     if (!is_array($data) && !is_scalar($data)) {
         return false;
     }
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof Date) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Date');
     }
     if (null === $value || '' === $value || $value instanceof \DateTime) {
         return;
     }
     if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
         throw new UnexpectedTypeException($value, 'string');
     }
     $value = (string) $value;
     if (!preg_match(static::PATTERN, $value, $matches)) {
         if ($this->context instanceof ExecutionContextInterface) {
             $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(Date::INVALID_FORMAT_ERROR)->addViolation();
         } else {
             $this->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(Date::INVALID_FORMAT_ERROR)->addViolation();
         }
         return;
     }
     if (!self::checkDate($matches[1], $matches[2], $matches[3])) {
         if ($this->context instanceof ExecutionContextInterface) {
             $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(Date::INVALID_DATE_ERROR)->addViolation();
         } else {
             $this->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(Date::INVALID_DATE_ERROR)->addViolation();
         }
     }
 }
Beispiel #21
0
 public function append($value)
 {
     if (is_scalar($value) || $value instanceof HString) {
         return $this->hString . $value;
     }
     throw new \InvalidArgumentException(sprintf("Cannot concatenate an HString with a %s", Helper::getType($value)));
 }
 public static function render(array $parameters)
 {
     // Sets defaults
     $parameters = array_merge(self::$defaultParameters, $parameters);
     // Begins widget
     $xmlOutput = parent::begin($parameters['class']);
     // Checks for...
     if (is_scalar($parameters['message']) && $parameters['message'] !== null) {
         // Checks if a subject was given
         if ($parameters['subject'] !== null) {
             // Uses subject-based message
             $message = DataCenterUI::message('heading', $parameters['message'], $parameters['subject']);
         } elseif ($parameters['type'] !== null) {
             // Checks if a type was given
             // Uses type-based message
             $message = DataCenterUI::message('heading', $parameters['message'], DataCenterUI::message('type', $parameters['type']));
         } else {
             // Uses plain message
             $message = DataCenterUI::message('heading', $parameters['message']);
         }
         // Returns heading with message
         $xmlOutput .= $message;
         // Checks if text was given
     } elseif ($parameters['text'] !== null) {
         // Adds a heading with text
         $xmlOutput .= $parameters['text'];
     }
     // Ends widget
     $xmlOutput .= parent::end();
     // Returns results
     return $xmlOutput;
 }
Beispiel #23
0
 /**
  * Returns `true` if value is of the specified type
  *
  * @param string $type
  * @param mixed $value
  * @return bool
  */
 protected function checkType($type, $value)
 {
     switch ($type) {
         case 'array':
             return is_array($value);
         case 'bool':
         case 'boolean':
             return is_bool($value);
         case 'callable':
             return is_callable($value);
         case 'float':
         case 'double':
             return is_float($value);
         case 'int':
         case 'integer':
             return is_int($value);
         case 'null':
             return is_null($value);
         case 'numeric':
             return is_numeric($value);
         case 'object':
             return is_object($value);
         case 'resource':
             return is_resource($value);
         case 'scalar':
             return is_scalar($value);
         case 'string':
             return is_string($value);
         case 'mixed':
             return true;
         default:
             return $value instanceof $type;
     }
 }
Beispiel #24
0
 /**
  * Add a single format
  *
  * @param string $format
  * @param string $requestHeader
  */
 public static function addFormat($format, $requestHeader)
 {
     if (!is_scalar($format) || !is_scalar($requestHeader)) {
         throw new InvalidArgumentException('Invalid argument given, string expected!');
     }
     self::$_mapping[$format] = $requestHeader;
 }
Beispiel #25
0
	/**
	 * Replaces or appends a item.
	 * @return void
	 */
	public function offsetSet($key, $value)
	{
		if (!is_scalar($key)) { // prevents NULL
			throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', gettype($key)));
		}
		$this->$key = $value;
	}
Beispiel #26
0
 /**
  * Send a request to the server and return a JHttpResponse object with the response.
  *
  * @param   string   $method     The HTTP method for sending the request.
  * @param   JUri     $uri        The URI to the resource to request.
  * @param   mixed    $data       Either an associative array or a string to be sent with the request.
  * @param   array    $headers    An array of request headers to send with the request.
  * @param   integer  $timeout    Read timeout in seconds.
  * @param   string   $userAgent  The optional user agent string to send with the request.
  *
  * @return  JHttpResponse
  *
  * @since   11.3
  * @throws  RuntimeException
  */
 public function request($method, JUri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
 {
     $connection = $this->connect($uri, $timeout);
     // Make sure the connection is alive and valid.
     if (is_resource($connection)) {
         // Make sure the connection has not timed out.
         $meta = stream_get_meta_data($connection);
         if ($meta['timed_out']) {
             throw new RuntimeException('Server connection timed out.');
         }
     } else {
         throw new RuntimeException('Not connected to server.');
     }
     // Get the request path from the URI object.
     $path = $uri->toString(array('path', 'query'));
     // If we have data to send make sure our request is setup for it.
     if (!empty($data)) {
         // If the data is not a scalar value encode it to be sent with the request.
         if (!is_scalar($data)) {
             $data = http_build_query($data);
         }
         if (!isset($headers['Content-Type'])) {
             $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
         }
         // Add the relevant headers.
         $headers['Content-Length'] = strlen($data);
     }
     // Build the request payload.
     $request = array();
     $request[] = strtoupper($method) . ' ' . (empty($path) ? '/' : $path) . ' HTTP/1.0';
     $request[] = 'Host: ' . $uri->getHost();
     // If an explicit user agent is given use it.
     if (isset($userAgent)) {
         $headers['User-Agent'] = $userAgent;
     }
     // If there are custom headers to send add them to the request payload.
     if (is_array($headers)) {
         foreach ($headers as $k => $v) {
             $request[] = $k . ': ' . $v;
         }
     }
     // If we have data to send add it to the request payload.
     if (!empty($data)) {
         $request[] = null;
         $request[] = $data;
     }
     // Send the request to the server.
     fwrite($connection, implode("\r\n", $request) . "\r\n\r\n");
     // Get the response data from the server.
     $content = '';
     while (!feof($connection)) {
         $content .= fgets($connection, 4096);
     }
     $content = $this->getResponse($content);
     // Follow Http redirects
     if ($content->code >= 301 && $content->code < 400 && isset($content->headers['Location'])) {
         return $this->request($method, new JUri($content->headers['Location']), $data, $headers, $timeout, $userAgent);
     }
     return $content;
 }
 /**
  * Replaces $NASTYSTRING vars for a nasty string.
  *
  * @Transform /^((.*)\$NASTYSTRING(\d)(.*))$/
  * @param string $argument The whole argument value.
  * @return string
  */
 public function arg_replace_nasty_strings($argument)
 {
     if (!is_scalar($argument)) {
         return $argument;
     }
     return $this->replace_nasty_strings($argument);
 }
 /**
  * Format XML for single DC element.
  * @param $propertyName string
  * @param $value array
  * @param $multilingual boolean optional
  */
 function formatElement($propertyName, $values, $multilingual = false)
 {
     if (!is_array($values)) {
         $values = array($values);
     }
     // Translate the property name to XML syntax.
     $openingElement = str_replace(array('[@', ']'), array(' ', ''), $propertyName);
     $closingElement = String::regexp_replace('/\\[@.*/', '', $propertyName);
     // Create the actual XML entry.
     $response = '';
     foreach ($values as $key => $value) {
         if ($multilingual) {
             $key = str_replace('_', '-', $key);
             assert(is_array($value));
             foreach ($value as $subValue) {
                 if ($key == METADATA_DESCRIPTION_UNKNOWN_LOCALE) {
                     $response .= "\t<{$openingElement}>" . OAIUtils::prepOutput($subValue) . "</{$closingElement}>\n";
                 } else {
                     $response .= "\t<{$openingElement} xml:lang=\"{$key}\">" . OAIUtils::prepOutput($subValue) . "</{$closingElement}>\n";
                 }
             }
         } else {
             assert(is_scalar($value));
             $response .= "\t<{$openingElement}>" . OAIUtils::prepOutput($value) . "</{$closingElement}>\n";
         }
     }
     return $response;
 }
 public function setVar($name, $var)
 {
     if (is_scalar($name)) {
         JqueryBoxManager::$__collectionList[$name] = $var;
         return true;
     }
 }
 /**
  * Returns true if and only if $value is a number correctly expressed with the scientific notation
  *
  * Note that it can only validate string inputs.
  *
  * @param mixed $value
  * @return bool
  */
 public function isValid($value)
 {
     if (!is_scalar($value) || is_bool($value)) {
         $this->error(self::INVALID_INPUT);
         return false;
     }
     $formatter = new \NumberFormatter($this->getLocale(), \NumberFormatter::SCIENTIFIC);
     $flags = 'i';
     $expSymbol = 'E';
     if (StringUtils::hasPcreUnicodeSupport()) {
         $expSymbol = preg_quote($formatter->getSymbol(\NumberFormatter::EXPONENTIAL_SYMBOL));
         $flags .= 'u';
     }
     // Check that exponentation symbol is present
     $search = str_replace("‎", '', sprintf('/%s/%s', $expSymbol, $flags));
     $value = str_replace("‎", '', $value);
     if (!preg_match($search, $value)) {
         $this->error(self::NOT_SCIENTIFIC);
         return false;
     }
     // Check that the number expressed in scientific notation is a valid number
     $float = new IsFloat(['locale' => $this->getLocale()]);
     if (!$float->isValid($value)) {
         $this->error(self::NOT_NUMBER);
         return false;
     }
     return true;
 }