Example #1
3
 private function getRandomBytes($count)
 {
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
         // OpenSSL slow on Win
         $bytes = openssl_random_pseudo_bytes($count);
     }
     if ($bytes === '' && @is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
         $bytes = fread($hRand, $count);
         fclose($hRand);
     }
     if (strlen($bytes) < $count) {
         $bytes = '';
         if ($this->randomState === null) {
             $this->randomState = microtime();
             if (function_exists('getmypid')) {
                 $this->randomState .= getmypid();
             }
         }
         for ($i = 0; $i < $count; $i += 16) {
             $this->randomState = md5(microtime() . $this->randomState);
             if (PHP_VERSION >= '5') {
                 $bytes .= md5($this->randomState, true);
             } else {
                 $bytes .= pack('H*', md5($this->randomState));
             }
         }
         $bytes = substr($bytes, 0, $count);
     }
     return $bytes;
 }
Example #2
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, "");
 }
Example #3
0
 function hex2bin($input, $assume_safe = true)
 {
     if ($assume_safe !== true && !(strlen($input) % 2 === 0 || preg_match('/^[0-9a-f]+$/i', $input))) {
         return '';
     }
     return pack('H*', $input);
 }
Example #4
0
 public function encryptMsg($text)
 {
     $token = $this->account['token'];
     $encodingaeskey = $this->account['encodingaeskey'];
     $appid = $this->account['key'];
     $key = base64_decode($encodingaeskey . '=');
     $text = random(16) . pack("N", strlen($text)) . $text . $appid;
     $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
     $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
     $iv = substr($key, 0, 16);
     $block_size = 32;
     $text_length = strlen($text);
     $amount_to_pad = $block_size - $text_length % $block_size;
     if ($amount_to_pad == 0) {
         $amount_to_pad = $block_size;
     }
     $pad_chr = chr($amount_to_pad);
     $tmp = '';
     for ($index = 0; $index < $amount_to_pad; $index++) {
         $tmp .= $pad_chr;
     }
     $text = $text . $tmp;
     mcrypt_generic_init($module, $key, $iv);
     $encrypted = mcrypt_generic($module, $text);
     mcrypt_generic_deinit($module);
     mcrypt_module_close($module);
     $encrypt_msg = base64_encode($encrypted);
     $signature = $this->buildSignature($encrypt_msg);
     return array($signature, $encrypt_msg);
 }
 public function storeDocuments($name, array $documents = null)
 {
     if ($name === null || $documents === null || trim($name) == '') {
         return false;
     }
     if (!is_string($name) || !is_array($documents)) {
         return false;
     }
     foreach ($documents as $doc) {
         if (!$this->validateDocument($doc)) {
             return false;
         }
     }
     $fp = fopen($this->_getFilePathName($name), 'w');
     foreach ($documents as $doc) {
         $bindata1 = pack('i', intval($doc[0]));
         $bindata2 = pack('i', intval($doc[1]));
         $bindata3 = pack('i', intval($doc[2]));
         fwrite($fp, $bindata1);
         fwrite($fp, $bindata2);
         fwrite($fp, $bindata3);
     }
     fclose($fp);
     return true;
 }
 protected function appendHeader($request, $id = null)
 {
     if ($id === null) {
         $id = $this->getId();
     }
     return pack("NN", strlen($request) | 0x80000000, $id) . $request;
 }
function chapchallengeresponse($challenge, $password)
{
    // Generates a response for a challenge response CHAP Auth
    $hexChallenge = pack("H32", $challenge);
    $response = md5("" . $password . $hexChallenge);
    return $response;
}
Example #8
0
 public function convertip_tiny($ip, $ipdatafile)
 {
     static $fp = NULL, $offset = array(), $index = NULL;
     $ipdot = explode('.', $ip);
     $ip = pack('N', ip2long($ip));
     $ipdot[0] = (int) $ipdot[0];
     $ipdot[1] = (int) $ipdot[1];
     if ($fp === NULL && ($fp = @fopen($ipdatafile, 'rb'))) {
         $offset = @unpack('Nlen', @fread($fp, 4));
         $index = @fread($fp, $offset['len'] - 4);
     } elseif ($fp == FALSE) {
         return '- Invalid IP data file';
     }
     $length = $offset['len'] - 1028;
     $start = @unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
     for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) {
         if ($index[$start] . $index[$start + 1] . $index[$start + 2] . $index[$start + 3] >= $ip) {
             $index_offset = @unpack('Vlen', $index[$start + 4] . $index[$start + 5] . $index[$start + 6] . "");
             $index_length = @unpack('Clen', $index[$start + 7]);
             break;
         }
     }
     @fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
     if ($index_length['len']) {
         return '- ' . @fread($fp, $index_length['len']);
     } else {
         return '- Unknown';
     }
 }
Example #9
0
 /**
  * Returns a specific character in UTF-8.
  * @param  int     codepoint
  * @return string
  */
 public static function chr($code)
 {
     if (func_num_args() > 1 && strcasecmp(func_get_arg(1), 'UTF-8')) {
         trigger_error(__METHOD__ . ' supports only UTF-8 encoding.', E_USER_DEPRECATED);
     }
     return iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
 }
Example #10
0
 /**
  * The symmetric encryption function
  *
  * @param string $pwd Key to encrypt with (can be binary of hex)
  * @param string $data Content to be encrypted
  * @param bool $ispwdHex Key passed is in hexadecimal or not
  * @access public
  * @return string
  */
 function encrypt($pwd, $data, $ispwdHex = 0)
 {
     if ($ispwdHex) {
         $pwd = @pack('H*', $pwd);
     }
     // valid input, please!
     $key[] = '';
     $box[] = '';
     $cipher = '';
     $pwd_length = strlen($pwd);
     $data_length = strlen($data);
     for ($i = 0; $i < 256; $i++) {
         $key[$i] = ord($pwd[$i % $pwd_length]);
         $box[$i] = $i;
     }
     for ($j = $i = 0; $i < 256; $i++) {
         $j = ($j + $box[$i] + $key[$i]) % 256;
         $tmp = $box[$i];
         $box[$i] = $box[$j];
         $box[$j] = $tmp;
     }
     for ($a = $j = $i = 0; $i < $data_length; $i++) {
         $a = ($a + 1) % 256;
         $j = ($j + $box[$a]) % 256;
         $tmp = $box[$a];
         $box[$a] = $box[$j];
         $box[$j] = $tmp;
         $k = $box[($box[$a] + $box[$j]) % 256];
         $cipher .= chr(ord($data[$i]) ^ $k);
     }
     return $cipher;
 }
Example #11
0
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
    $algorithm = strtolower($algorithm);
    if (!in_array($algorithm, hash_algos(), true)) {
        die('PBKDF2 ERROR: Invalid hash algorithm.');
    }
    if ($count <= 0 || $key_length <= 0) {
        die('PBKDF2 ERROR: Invalid parameters.');
    }
    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);
    $output = "";
    for ($i = 1; $i <= $block_count; $i++) {
        // $i encoded as 4 bytes, big endian.
        $last = $salt . pack("N", $i);
        // first iteration
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        // perform the other $count - 1 iterations
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= $last = hash_hmac($algorithm, $last, $password, true);
        }
        $output .= $xorsum;
    }
    if ($raw_output) {
        return substr($output, 0, $key_length);
    } else {
        return bin2hex(substr($output, 0, $key_length));
    }
}
Example #12
0
 public function parse()
 {
     $matches = array();
     if ($this->softmode) {
         $res = preg_match(self::PATTERN_SOFTMODE, trim($this->fileContent), $matches);
     } else {
         $res = preg_match(self::PATTERN, $this->fileContent, $matches);
     }
     if ($res === false || $res === 0) {
         throw new \Exception($this->filename . ' is not a proper .srt file.');
     }
     $this->setLineEnding($matches[1]);
     $bom = pack('CCC', 0xef, 0xbb, 0xbf);
     $matches = explode($this->lineEnding . $this->lineEnding, trim($matches[0], $bom . $this->lineEnding));
     $subtitleOrder = 1;
     $subtitleTime = '';
     foreach ($matches as $match) {
         $subtitle = explode($this->lineEnding, $match, 3);
         $timeline = explode(' --> ', $subtitle[1]);
         $subtitleTimeStart = $timeline[0];
         $subtitleTimeEnd = $timeline[1];
         if (!$this->softmode && ($subtitle[0] != $subtitleOrder++ || !$this->validateTimelines($subtitleTime, $subtitleTimeStart, true) || !$this->validateTimelines($subtitleTimeStart, $subtitleTimeEnd))) {
             throw new \Exception($this->filename . ' is not a proper .srt file.');
         }
         $subtitleTime = $subtitleTimeEnd;
         $cue = new SubripCue($timeline[0], $timeline[1], isset($subtitle[2]) ? $subtitle[2] : '');
         $cue->setLineEnding($this->lineEnding);
         $this->addCue($cue);
     }
     return $this;
 }
Example #13
0
function hexstr($hexstr)
{
    $hexstr = str_replace(' ', '', $hexstr);
    $hexstr = str_replace('\\x', '', $hexstr);
    $retstr = pack('H*', $hexstr);
    return $retstr;
}
Example #14
0
 /**
  * Generate the WSBOOL biff record
  * @param Worksheet $sheet
  *
  * @return string
  */
 public function getData(Worksheet $sheet)
 {
     $grbit = 0x0;
     // Set the option flags
     $grbit |= 0x1;
     // Auto page breaks visible
     if ($sheet->getOutlineStyle()) {
         $grbit |= 0x20;
         // Auto outline styles
     }
     if ($sheet->getOutlineBelow()) {
         $grbit |= 0x40;
         // Outline summary below
     }
     if ($sheet->getOutlineRight()) {
         $grbit |= 0x80;
         // Outline summary right
     }
     if ($sheet->getPrintSetup()->isFitPage()) {
         $grbit |= 0x100;
         // Page setup fit to page
     }
     if ($sheet->isOutlineOn()) {
         $grbit |= 0x400;
         // Outline symbols displayed
     }
     $data = pack("v", $grbit);
     return $this->getFullRecord($data);
 }
Example #15
0
 /**
  * Remove the byte order mark from a string if applicable
  *
  * @param string $string
  * @return string
  */
 public static function removeBom($string)
 {
     if (substr($string, 0, 3) == pack('CCC', 0xef, 0xbb, 0xbf)) {
         $string = substr($string, 3);
     }
     return $string;
 }
Example #16
0
 /**
  * This method iterates over each record in the file, yielding each item to the procedure function.
  *
  * @access public
  * @param callable $procedure                               the procedure function to be used
  * @throws Throwable\Parse\Exception                        indicates that an invalid record was
  *                                                          encountered
  */
 public function each(callable $procedure)
 {
     $self = $this;
     IO\FileReader::read($this->file, function ($reader, $data, $index) use($self, $procedure) {
         $line = trim($data);
         if (strlen($line) > 0) {
             if ($index == 0 && $self->bom) {
                 $line = preg_replace('/^' . pack('H*', 'EFBBBF') . '/', '', $line);
             }
             $query_string = parse_url($line, PHP_URL_QUERY);
             $properties = array();
             parse_str($query_string, $properties);
             if (!empty($properties)) {
                 $source_encoding = $self->encoder !== null ? call_user_func($self->encoder . "::getEncoding", $properties) : $self->encoding[0];
                 $target_encoding = $self->encoding[1];
                 foreach ($properties as $key => &$value) {
                     $value = urldecode($value);
                     $value = Core\Data\Charset::encode($value, $source_encoding, $target_encoding);
                     $type = isset($self->schema[$key]) ? $self->schema[$key] : 'string';
                     $value = Core\Convert::changeType($value, $type);
                     $record = new Common\Mutable\HashMap();
                     $record->putEntry($key, $value);
                     $procedure($record);
                 }
             }
         }
     });
 }
Example #17
0
function Qiniu_PutFile($upToken, $key, $localFile, $putExtra)
{
    global $QINIU_UP_HOST;
    if ($putExtra === null) {
        $putExtra = new Qiniu_PutExtra();
    }
    if (!empty($putExtra->MimeType)) {
        $localFile .= ';type=' . $putExtra->MimeType;
    }
    $fields = array('token' => $upToken, 'file' => '@' . $localFile);
    if ($key === null) {
        $fname = '?';
    } else {
        $fname = $key;
        $fields['key'] = $key;
    }
    if ($putExtra->CheckCrc) {
        if ($putExtra->CheckCrc === 1) {
            $hash = hash_file('crc32b', $localFile);
            $array = unpack('N', pack('H*', $hash));
            $putExtra->Crc32 = $array[1];
        }
        $fields['crc32'] = sprintf('%u', $putExtra->Crc32);
    }
    $client = new Qiniu_HttpClient();
    return Qiniu_Client_CallWithForm($client, $QINIU_UP_HOST, $fields, 'multipart/form-data');
}
Example #18
0
 function inet_pton($ip)
 {
     # ipv4
     if (strpos($ip, '.') !== FALSE) {
         if (strpos($ip, ':') === FALSE) {
             $ip = pack('N', ip2long($ip));
         } else {
             $ip = explode(':', $ip);
             $ip = pack('N', ip2long($ip[count($ip) - 1]));
         }
     } elseif (strpos($ip, ':') !== FALSE) {
         $ip = explode(':', $ip);
         $parts = 8 - count($ip);
         $res = '';
         $replaced = 0;
         foreach ($ip as $seg) {
             if ($seg != '') {
                 $res .= str_pad($seg, 4, '0', STR_PAD_LEFT);
             } elseif ($replaced == 0) {
                 for ($i = 0; $i <= $parts; $i++) {
                     $res .= '0000';
                 }
                 $replaced = 1;
             } elseif ($replaced == 1) {
                 $res .= '0000';
             }
         }
         $ip = pack('H' . strlen($res), $res);
     }
     return $ip;
 }
 /**
  * PBKDF2 Implementation for deriving keys.
  *
  * @param   string   $p   Password
  * @param   string   $s   Salt
  * @param   integer  $kl  Key length
  * @param   integer  $c   Iteration count
  * @param   string   $a   Hash algorithm
  *
  * @return  string  The derived key.
  *
  * @see     http://en.wikipedia.org/wiki/PBKDF2
  * @see     http://www.ietf.org/rfc/rfc2898.txt
  * 
  * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
  */
 protected static function pbkdf2($p, $s, $kl, $c = 10000, $a = 'sha256')
 {
     // simple md5 version
     if (!function_exists('hash')) {
         $seed = $p . $s;
         $md5 = md5($seed);
         for ($i = 0; $i < $c; $i++) {
             $md5 = md5($md5 . md5(rand(0, 2147483647)));
         }
         return substr($md5, 0, $kl);
     }
     // Hash length.
     $hl = strlen(hash($a, null, true));
     // Key blocks to compute.
     $kb = ceil($kl / $hl);
     // Derived key.
     $dk = '';
     // Create the key.
     for ($block = 1; $block <= $kb; $block++) {
         // Initial hash for this block.
         $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
         // Perform block iterations.
         for ($i = 1; $i < $c; $i++) {
             $ib ^= $b = hash_hmac($a, $b, $p, true);
         }
         // Append the iterated block.
         $dk .= $ib;
     }
     // Return derived key of correct length.
     return substr($dk, 0, $kl);
 }
Example #20
0
function sendNotificationIOS()
{
    // Put your device token here (without spaces):
    $deviceToken = '87d4477b81a7f8f7ba80b3f5f043d83dec3c9b0940c708d24f803ef67600966f';
    // Put your private key's passphrase here:
    $passphrase = 'pushchat';
    // Put your alert message here:
    $message = 'My first push notification!';
    ////////////////////////////////////////////////////////////////////////////////
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    // Open a connection to the APNS server
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
    if (!$fp) {
        exit("Failed to connect: {$err} {$errstr}" . PHP_EOL);
    }
    echo 'Connected to APNS' . PHP_EOL;
    // Create the payload body
    $body['aps'] = array('alert' => $message, 'sound' => 'default');
    // Encode the payload as JSON
    $payload = json_encode($body);
    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));
    if (!$result) {
        echo 'Message not delivered' . PHP_EOL;
    } else {
        echo 'Message successfully delivered' . PHP_EOL;
    }
    // Close the connection to the server
    fclose($fp);
}
function xlsWriteLabel($Row, $Col, $Value)
{
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}
Example #22
0
 /**
  * Get the specified number of random bytes.
  *
  * Attempts to use a cryptographically secure (not predictable)
  * source of randomness if available. If there is no high-entropy
  * randomness source available, it will fail. As a last resort,
  * for non-critical systems, define
  * <code>Auth_OpenID_RAND_SOURCE</code> as <code>null</code>, and
  * the code will fall back on a pseudo-random number generator.
  *
  * @param int $num_bytes The length of the return value
  * @return string $bytes random bytes
  */
 function getBytes($num_bytes)
 {
     static $f = null;
     $bytes = '';
     if ($f === null) {
         if (Auth_OpenID_RAND_SOURCE === null) {
             $f = false;
         } else {
             $f = @fopen(Auth_OpenID_RAND_SOURCE, "r");
             if ($f === false) {
                 $msg = 'Define Auth_OpenID_RAND_SOURCE as null to ' . ' continue with an insecure random number generator.';
                 trigger_error($msg, E_USER_ERROR);
             }
         }
     }
     if ($f === false) {
         // pseudorandom used
         $bytes = '';
         for ($i = 0; $i < $num_bytes; $i += 4) {
             $bytes .= pack('L', mt_rand());
         }
         $bytes = substr($bytes, 0, $num_bytes);
     } else {
         $bytes = fread($f, $num_bytes);
     }
     return $bytes;
 }
 public function connect($host, $port, $path, $origin = false)
 {
     $this->_host = $host;
     $this->_port = $port;
     $this->_path = $path;
     $this->_origin = $origin;
     $key = base64_encode($this->_generateRandomString(16, false, true));
     $header = "GET " . $path . " HTTP/1.1\r\n";
     $header .= "Host: " . $host . ":" . $port . "\r\n";
     $header .= "Upgrade: websocket\r\n";
     $header .= "Connection: Upgrade\r\n";
     $header .= "Sec-WebSocket-Key: " . $key . "\r\n";
     if ($origin !== false) {
         $header .= "Sec-WebSocket-Origin: " . $origin . "\r\n";
     }
     $header .= "Sec-WebSocket-Version: 13\r\n";
     $this->_Socket = fsockopen($host, $port, $errno, $errstr, 2);
     socket_set_timeout($this->_Socket, 0, 10000);
     @fwrite($this->_Socket, $header);
     $response = @fread($this->_Socket, 1500);
     preg_match('#Sec-WebSocket-Accept:\\s(.*)$#mU', $response, $matches);
     $keyAccept = trim($matches[1]);
     $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
     $this->_connected = $keyAccept === $expectedResonse ? true : false;
     return $this->_connected;
 }
 public function enviariOS($aMensajes)
 {
     $response = ['codigoerror' => 0, 'error' => '', 'data' => []];
     try {
         $streamContext = stream_context_create();
         stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->certificate);
         if ($this->certificatepassword != '') {
             stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->certificatepassword);
         }
         $fp = stream_socket_client($this->url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext);
         if (!$fp) {
             $response['codigoerror'] = 1;
             $response['error'] = 'Error conectando a APNs: ' . $err;
             return Response::json($response);
         }
         //En este punto ya estamos conectados al APN, mandamos todos los mensajes
         foreach ($aMensajes as $mensaje) {
             $payload['aps'] = ['alert' => $mensaje['mensaje'], 'badge' => 0, 'sound' => 'default'];
             $jsonpayload = json_encode($payload);
             $msg = chr(0) . pack('n', 32) . pack('H*', $mensaje['token']) . pack('n', strlen($jsonpayload)) . $jsonpayload;
             $resultado = fwrite($fp, $msg, strlen($msg));
             $response['data'][] = ['token' => $mensaje['token'], 'resultado' => $resultado];
         }
         return Response::json($response);
     } catch (Exception $e) {
         $response['codigoerror'] = 2;
         $response['error'] = 'Error conectando a APNs: ' . $e->getMessage();
         return Response::json($response);
     }
 }
Example #25
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;
 }
Example #26
0
 public function parse()
 {
     $matches = array();
     $res = preg_match($this->options['_requireStrictFileFormat'] ? self::PATTERN_STRICT : self::PATTERN_LOOSE, $this->fileContent, $matches);
     if ($res === false || $res === 0) {
         throw new \Exception($this->filename . ' is not a proper .srt file.');
     }
     $this->setLineEnding($matches[1]);
     $bom = pack('CCC', 0xef, 0xbb, 0xbf);
     $matches = explode($this->lineEnding . $this->lineEnding, trim($matches[0], $bom . $this->lineEnding));
     $subtitleOrder = 1;
     $subtitleTime = '';
     foreach ($matches as $match) {
         $subtitle = explode($this->lineEnding, $match, 3);
         $timeline = explode(' --> ', $subtitle[1]);
         $subtitleTimeStart = $timeline[0];
         $subtitleTimeEnd = $timeline[1];
         if (!$this->options['_requireStrictFileFormat']) {
             $subtitleTimeStart = $this->cleanUpTimecode($subtitleTimeStart);
             $subtitleTimeEnd = $this->cleanUpTimecode($subtitleTimeEnd);
         }
         if ($subtitle[0] != $subtitleOrder++ || !$this->validateTimelines($subtitleTimeStart, $subtitleTimeEnd, !$this->options['_requireStrictFileFormat']) || $this->options['_requireStrictFileFormat'] && !$this->validateTimelines($subtitleTime, $subtitleTimeStart, true)) {
             throw new \Exception($this->filename . " failed timeline validation. ({$subtitleTimeStart} --> {$subtitleTimeEnd})");
         }
         $subtitleTime = $subtitleTimeEnd;
         $cue = new SubripCue($timeline[0], $timeline[1], $subtitle[2]);
         $cue->setLineEnding($this->lineEnding);
         $this->addCue($cue);
     }
     return $this;
 }
 private function Text($Row, $Col, $Value)
 {
     $Value2UTF8 = $Value;
     $L = strlen($Value2UTF8);
     $this->xls .= pack('ssssss', 0x204, 8 + $L, $Row, $Col, 0x0, $L);
     $this->xls .= $Value2UTF8;
 }
Example #28
0
 /**
  * @param $modelProxyClass
  * @return object
  */
 public function build($modelProxyClass)
 {
     $encryptionKey = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
     $encryptionMethod = 'aes-128-cbc';
     $encryptionService = new EncryptionService($encryptionKey, $encryptionMethod);
     return new MessageProxy($encryptionService);
 }
Example #29
0
function removeBOM($str = "")
{
    if (substr($str, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
        $str = substr($str, 3);
    }
    return $str;
}
 private function _getContent($file)
 {
     $file = realpath($file);
     if (!$file || in_array($file, self::$filesIncluded) || false === ($content = @file_get_contents($file))) {
         // file missing, already included, or failed read
         return '';
     }
     self::$filesIncluded[] = realpath($file);
     $this->_currentDir = dirname($file);
     // remove UTF-8 BOM if present
     if (pack("CCC", 0xef, 0xbb, 0xbf) === substr($content, 0, 3)) {
         $content = substr($content, 3);
     }
     // ensure uniform EOLs
     $content = str_replace("\r\n", "\n", $content);
     // process @imports
     $content = preg_replace_callback('/
             @import\\s+
             (?:url\\(\\s*)?      # maybe url(
             [\'"]?               # maybe quote
             (.*?)                # 1 = URI
             [\'"]?               # maybe end quote
             (?:\\s*\\))?         # maybe )
             ([a-zA-Z,\\s]*)?     # 2 = media list
             ;                    # end token
         /x', array($this, '_importCB'), $content);
     if (self::$_isCss) {
         // rewrite remaining relative URIs
         $content = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/', array($this, '_urlCB'), $content);
     }
     return $this->_importedContent . $content;
 }