public static function Save($strFormState, $blnBackButtonFlag) { // Compress (if available) if (function_exists('gzcompress')) { $strFormState = gzcompress($strFormState, 9); } // Setup CurrentStateIndex (if none yet exists) if (!array_key_exists('qform_current_state_index', $_SESSION)) { $_SESSION['qform_current_state_index'] = 0; } // Increment CurrentStateIndex if BackButtonFlag is true // Otherwise, we're in an ajax-to-ajax call, and the back button is invalid anyway // No need to increment session state index -- let's not to save space // if ($blnBackButtonFlag) $_SESSION['qform_current_state_index'] = $_SESSION['qform_current_state_index'] + 1; $intStateIndex = $_SESSION['qform_current_state_index']; // Save THIS formstate // NOTE: if gzcompress is used, we are saving the *BINARY* data stream of the compressed formstate // In theory, this SHOULD work. But if there is a webserver/os/php version that doesn't like // binary session streams, you can first base64_encode before saving to session (see note below). $_SESSION['qform_' . $intStateIndex] = $strFormState; // Return StateIndex if (!is_null(QForm::$EncryptionKey)) { // Use QCryptography to Encrypt $objCrypto = new QCryptography(QForm::$EncryptionKey, true); return $objCrypto->Encrypt($intStateIndex); } else { return $intStateIndex; } }
function compress($data, $compressed) { if ($compressed == 1) { return gzcompress($data); } return $data; }
/** * 写入缓存 * @param string $name 缓存文件名字 * @param function $callback 回调函数,必须要有返回值 * @param Array or string or Object $params 要传进去的参数 * @param int $time 写入的缓存时间 * @return array * @author wave */ public static function wirte($name, $callback, $params = null, $time = TIME) { self::init(); $file = ROOT . DS . APP_PATH . DS . self::$cache_dir; $content = ''; if (!file_exists($file . self::CACHE_PREFIX . $name)) { $content = $callback($params); if (!empty($content)) { file_put_contents($file . self::CACHE_PREFIX . $name, gzcompress(serialize($content))); return; } } if (empty($time)) { return; } if (file_exists($file . self::CACHE_PREFIX . $name)) { $cache_time = strtotime(date('Y-m-d H:i:s')) - strtotime(date('Y-m-d H:i:s', filemtime($file . self::CACHE_PREFIX . $name))); if ($cache_time / 1000 >= $time || $time == 1) { $content = $callback($params); if (!empty($content)) { file_put_contents($file . self::CACHE_PREFIX . $name, gzcompress(serialize($content))); return; } } } }
/** * 写入缓存 * @access public * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param int $expire 有效时间 0为永久 * @return boolean */ public function set($name, $value, $expire = null) { if (is_null($expire)) { $expire = $this->options['expire']; } $filename = $this->getFileName($name); $data = serialize($value); //是否数据压缩 if ($this->options['compress'] && function_exists('gzcompress')) { //数据压缩 $data = gzcompress($data, 3); } //是否数据校验 if ($this->options['check']) { $check = md5($data); } else { $check = ''; } $data = "<?php\n//" . sprintf('%012d', $expire) . $check . $data . "\n?>"; $result = file_put_contents($filename, $data); if ($result) { // if($this->options['length']>0) { // // 记录缓存队列 // $this->queue($name); // } clearstatcache(); return true; } else { return false; } }
function save_array_dump($filename, $array) { $dump = addslashes(gzcompress(var_export($array, true), 9)); $fp = fopen($filename, "wb+"); fwrite($fp, $dump); fclose($fp); }
function secure_serialize($data) { $mainframe =& JFactory::getApplication(); $secret = $mainframe->getCfg('secret'); $sData = strtr(base64_encode(addslashes(gzcompress(serialize($data), 9))), '+/=', '-_,'); return sha1($sData . $secret) . $sData; }
function print_gzipped_page() { $HTTP_ACCEPT_ENCODING = getenv("HTTP_ACCEPT_ENCODING"); if (headers_sent()) { $encoding = false; } elseif (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) { $encoding = 'x-gzip'; } elseif (strpos($HTTP_ACCEPT_ENCODING, 'gzip') !== false) { $encoding = 'gzip'; } else { $encoding = false; } if ($encoding) { $contents = ob_get_contents(); ob_end_clean(); header('Content-Encoding: ' . $encoding); header("ETag: " . md5($contents)); // ETag im Header senden header("Expires: " . date("r", mktime(0, 0, 0, date("n"), date("j") + 365))); print "�"; $size = strlen($contents); $contents = gzcompress($contents, 9); $contents = substr($contents, 0, $size); print $contents; // exit(); } else { ob_end_flush(); // exit(); } }
/** * Sends a command to the server and returns an object with the result * * @param string $cmd Protocol command to be executed * @param string $message Full email message * @param array $additionalHeaders Associative array with additional headers */ protected function exec($cmd, $message, array $additionalHeaders = array()) { $socket = $this->getSocket(); $message .= "\r\n"; $contentLength = strlen($message); if (!empty($this->maxSize)) { if ($contentLength > $this->maxSize) { throw new Exception("Message exceeds the maximum allowed size of {$this->maxSize} kbytes"); } } $cmd = $cmd . ' SPAMC/' . $this->protocolVersion . "\r\n"; $cmd .= "Content-length: {$contentLength}\r\n"; if ($this->enableZlib && function_exists('gzcompress')) { $cmd .= "Compress: zlib\r\n"; $message = gzcompress($message); } if (!empty($this->user)) { $cmd .= 'User: '******': ' . $val . "\r\n"; } } $cmd .= "\r\n"; $cmd .= $message; $cmd .= "\r\n"; $this->write($socket, $cmd); list($headers, $message) = $this->read($socket); return $this->parseOutput($headers, $message); }
function compile($compressionLevel = 0) { $this->header->setCompressed($compressionLevel > 0); $data = ''; foreach ($this->tags as $tag) { $data .= $tag->getTagContent(); } $header = $this->header->getPacked(); $len = strlen($header) + strlen($data); $this->header->filelength->set($len); $data = $this->header->getPacked() . $data; if ($compressionLevel > 0) { $compressionStartTime = $this->microtime_float(); // The first eight bytes are uncompressed $uncompressedBytes = substr($data, 0, 8); // Remove first eight bytes $data = substr_replace($data, '', 0, 8); // Compress the rest of the SWF $data = gzcompress($data, $compressionLevel); // Add the uncompressed header $data = $uncompressedBytes . $data; $compressionDuration = $this->microtime_float() - $compressionStartTime; if (LOG_ALL) { error_log('[SWX] PROFILING: SWF compression took ' . $compressionDuration . ' seconds.'); } // Stats $compressedSize = strlen($data); if (LOG_ALL) { error_log('[SWX] INFO Compressed size of SWF: ' . $compressedSize . ' bytes.'); } } $this->data = $data; }
/** * Forwards the logging event to the Graylog2 server. * @param LoggerLoggingEvent $event */ protected function append(LoggerLoggingEvent $event) { $message = gzcompress($this->layout->format($event)); $socket = $this->getSocketConnection(); if (strlen($message) > $this->getChunkSize()) { // A unique id which consists of the microtime and a random value $messageId = uniqid(); // Split the message into chunks $messageChunks = str_split($message, $this->getChunkSize()); $messageChunksCount = count($messageChunks); // Send chunks to graylog server foreach ($messageChunks as $messageChunkIndex => $messageChunk) { $bytesWritten = $this->writeMessageChunkToSocket($socket, $messageId, $messageChunk, $messageChunkIndex, $messageChunksCount); if (false === $bytesWritten) { // Abort due to write error return false; } } } else { // A single write is enough to get the message published if (false === $this->writeMessageToSocket($socket, $message)) { // Abort due to write error return false; } } }
public function set($key, $value, $expire = '') { $freeSpace = disk_free_space($this->config['path']); $freeSpaceMB = $freeSpace ? floor($freeSpace / 1024 / 1024) : 0; if ($freeSpaceMB < 10) { Axion_log::getinstance()->newMessage('磁盘容量过小,无法存储数据缓存文件', AXION_LOG::WARNING); return false; } $hash = md5($key); $expire = $expire ? $expire : $this->config['expire']; $expire = sprintf('%09d', $expire); $data = serialize($value); self::$_data[$hash] = $data; if (!is_dir($this->config['path'])) { if (!AXION_UTIL_FILE::mkdir($this->config['path'])) { throw new AXION_EXCEPTION('无法创建Cache文件目录:' . $this->config['path']); } } $fileName = $this->genFileName($key); if (IS_SHM && function_exists('gzcompress')) { $data = gzcompress($data, 4); } $data = $expire . $data; $result = file_put_contents($fileName, $data); if ($result) { clearstatcache(); return true; } else { return false; } }
public static function save($label, $data, $expires = null, $compress = true) { $label = urlencode($label); $dir = rtrim(self::$dir, "/"); if (is_object($data) || is_array($data)) { if (method_exists($data, "__toString")) { $data = call_user_func(array($data, '__toString')); } else { $data = serialize($data); } } $str = (string) gzcompress($data); if (strlen($str) > $data) { $str = $data; } if ((bool) file_put_contents("{$dir}/{$label}", $str)) { if ($expires) { $expires = time() + (int) $expires; } else { $expires = time() + 60 * 60 * 24 * 365 * 10; } touch("{$dir}/{$label}", time(), $expires); return $data; } else { throw new Exception("Could not cache file.", 0); } }
protected function encode($value = null) { if (!$value) { return ''; } return base64_encode(gzcompress(serialize($value))); }
function ncd_new($sx, $sy, $prec = 0, $MAXLEN = 9000) { # NCD with gzip artifact correctoin and percentual return. # sx,sy = strings to compare. # Use $prec=-1 for result range [0-1], $pres=0 for percentual, # For NCD definition see http://arxiv.org/abs/0809.2553 $x = $min = strlen(gzcompress($sx)); $y = $max = strlen(gzcompress($sy)); $xy = strlen(gzcompress($sx . $sy)); $a = $sx; if ($x > $y) { # swap min/max $min = $y; $max = $x; $a = $sy; } $res = ($xy - $min) / $max; # NCD definition. #Little strings): if ($MAXLEN < 0 || $xy < $MAXLEN) { $aa = strlen(gzcompress($a . $a)); $ref = ($aa - $min) / $min; $res = $res - $ref; # correction } return $prec < 0 ? $res : 100 * round($res, 2 + $prec); }
public static function serialize($data, $type) { $types = explode('|', $type, 2); switch ($types[0]) { case self::SERIALIZE_TYPE_BASE64: if (!empty($types[1])) { $data = self::serialize($data, $types[1]); } return self::SERIALIZE_TYPE_BASE64 . ' ' . base64_encode($data); case self::SERIALIZE_TYPE_GZIP: if (!empty($types[1])) { $data = self::serialize($data, $types[1]); } if (strlen($data) < self::GZIP_MIN_LENGTH) { return $data; } return self::SERIALIZE_TYPE_GZIP . ' ' . gzcompress($data); case self::SERIALIZE_TYPE_PHP_SERIALIZE: return self::SERIALIZE_TYPE_PHP_SERIALIZE . ' ' . serialize($data); case self::SERIALIZE_TYPE_JSON: return self::SERIALIZE_TYPE_JSON . ' ' . json_encode($data); default: throw new InvalidArgumentException(); } }
function vdk_pack($vdk, $dirname, &$table = [], &$folders = 0, $parent = null) { if (!($folder = scandir($dirname))) { return; } usort($folder, 'strcasecmp'); if (is_null($parent)) { array_splice($folder, 1, 1); } $current = ftell($vdk); $last = count($folder) - 1; foreach ($folder as $i => $filename) { echo $pathname = "{$dirname}/{$filename}", "\n"; if (is_dir($pathname)) { $start = ftell($vdk); fseek($vdk, 145, SEEK_CUR); if (!in_array($filename, ['.', '..'])) { vdk_pack($vdk, $pathname, $table, $folders, $current); $folders++; } $end = ftell($vdk); fseek($vdk, $start); fwrite($vdk, pack('Ca128V4', 1, $filename, 0, 0, $filename == '..' ? $parent : $start + ($filename == '.' ? 0 : 145), $i == $last ? 0 : $end)); fseek($vdk, $end); } else { $table[$pathname] = ftell($vdk); $data = gzcompress(file_get_contents($pathname), $GLOBALS['level']); fwrite($vdk, pack('Ca128V4', 0, $filename, filesize($pathname), $size = strlen($data), 0, $i == $last ? 0 : $table[$pathname] + 145 + $size) . $data); } } }
/** * Save data * * @param string $data * @param string $id * @param array $tags * @param int $lifeTime * @return bool */ public function save($data, $id, $tags = array(), $lifeTime = null) { if (!in_array(self::CACHE_TAG, $tags)) { $tags[] = self::CACHE_TAG; } if (is_null($lifeTime)) { $lifeTime = (int) $this->getFrontend()->getOption('lifetime'); } // edit cached object $cacheData = new Varien_Object(); $cacheData->setCachedata($data); $cacheData->setCacheId($id); $cacheData->setTags($tags); $cacheData->setLifeTime($lifeTime); Mage::dispatchEvent('fpc_save_data_before', array('cache_data' => $cacheData)); $data = $cacheData->getCachedata(); $id = $cacheData->getCacheId(); $tags = $cacheData->getTags(); $lifeTime = $cacheData->getLifeTime(); $compressLevel = Mage::getStoreConfig(self::GZCOMPRESS_LEVEL_XML_PATH); if ($compressLevel != -2) { $data = gzcompress($data, $compressLevel); } return $this->_frontend->save($data, $this->_id($id), $this->_tags($tags), $lifeTime); }
function _gzipOutput(& $output) { global $HTTP_SERVER_VARS; if(defined('OUTPUT_GZIP_ENABLED') && constant('OUTPUT_GZIP_ENABLED') == false) return; if(isset($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING']) && strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')) { $size = strlen($output); if(extension_loaded('zlib') && $size >= 20000) { $crc = crc32($output); $output = gzcompress($output, 9); // We can't just output it here, since the CRC is messed up. Strip off the old CRC $output = substr($output, 0, strlen($output) - 4); _gzipAppend4_chars($output, $crc); _gzipAppend4_chars($output, $size); $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $output; header('Content-Encoding: gzip'); } } }
public function set($name, $value, $expireTime = 0) { $data = serialize($value); $name = addslashes($name); $this->W(1); if (C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) { $data = gzcompress($data, 3); } if (C('DATA_CACHE_CHECK')) { $crc = md5($data); } else { $crc = ''; } $expire = !empty($expireTime) ? $expireTime : $this->options['expire']; $map = array(); $map['cachekey'] = $name; $map['data'] = $data; $map['datacrc'] = $crc; $map['expire'] = $expire == -1 ? -1 : time() + $expire; $map['datasize'] = strlen($data); $result = $this->db->getRow('select `id` from `' . $this->options['table'] . '` where `cachekey`=\'' . $name . '\' limit 0,1'); if (false !== $result) { $result = $this->db->save($map, $this->options['table'], '`cachekey`=\'' . $name . '\''); } else { $result = $this->db->add($map, $this->options['table']); } if ($result) { return true; } else { return false; } }
/** * Compress * @param mixed $data * @return string binary blob of data */ public static function compress($data) { if (Audit::getInstance()->compressData) { $data = gzcompress($data); } return $data; }
public function patch($data) { $this->reset(); $swfdata = $this->swfdata; while (list($tag_start_pos, $tag_type, $tag_header_len, $tag_len) = $this->getNextTag()) { if ($tag_type == self::SWF_TAG_DefineBinaryData) { $signature = substr($swfdata, $tag_start_pos + $tag_header_len + 2 + 4, strlen($this->signature)); if ($signature != $this->signature) { continue; } $tag_prefix = substr($swfdata, $tag_start_pos + $tag_header_len, 6); $data_len = strlen($tag_prefix) + strlen($data); if ($data_len < 63) { $record_header = pack("v1", (self::SWF_TAG_DefineBinaryData << 6) + $data_len); } else { $record_header = pack("v1V1", (self::SWF_TAG_DefineBinaryData << 6) + 0x3f, $data_len); } $new_tag = $record_header . $tag_prefix . $data; $new_swfdata = substr($swfdata, 0, $tag_start_pos) . $new_tag . substr($swfdata, $this->pos); $header = substr($this->header, 0, 4) . pack("V1", 8 + strlen($new_swfdata)); $zdata = gzcompress($new_swfdata, 9); return $header . $zdata; } } }
/** * Given some data, this function will compress it using gzcompress * and then base64_encodes the output. If this fails, false is returned * otherwise the compressed data * * @param string $data * The data to compress * @return string|boolean * The compressed data, or false if an error occurred */ public function compressData($data) { if (!($data = base64_encode(gzcompress($data)))) { return false; } return $data; }
public static function t($category, $t, $resetCategory = false) { if (empty($t)) { return 'Empty text'; } if (empty(self::$t[$category]) || $resetCategory) { $categoryList = self::find()->where(['lang' => \Yii::$app->language])->all(); self::$t[$category] = []; foreach ($categoryList as $categoryItem) { self::$t[$categoryItem->category][$categoryItem->alias] = $categoryItem->t; } $resetCategory = false; } $t = trim($t); $alias = md5(gzcompress($t)); if (!empty(self::$t[$category][$alias])) { return self::$t[$category][$alias]; } $model = new Language(); $model->id = $model->nextId; $model->lang = Lang::getLang()->code; $model->alias = $alias; $model->category = $category; $model->t = $t; $model->create(); return self::t($category, $t, true); }
private function error($errorID, $header = "HTTP/1.0 400 Bad Request") { $error = $this->ersArray[$errorID]; header($header); echo gzcompress("<error>{$error['desc']}</error>", 9); exit; }
public function testFilterCombinations() { $dataHex = '48 65 6c 6c 6f 20 57 6f 72 6c 64 21>'; $dataHexFlate = gzcompress($dataHex); $streamObjectTemplate = <<<EOT 1 0 obj << /Length %s /Filter [ /FlateDecode /ASCIIHexDecode ] >> stream %s endstream endobj EOT; $streamObject = sprintf($streamObjectTemplate, strlen($dataHexFlate), $dataHexFlate); $streamData = 'data://text/plain;base64,' . base64_encode($streamObject); $handle = fopen($streamData, 'rb'); $pdfStream = new PdfStream($handle); $crossReferenceTable = new CrossReferenceTable(); $crossReferenceTable[] = new CrossReferenceTableEntry(1, 0, 0, 'n'); $objectRepository = new ObjectRepository($pdfStream, $crossReferenceTable); $pdfStreamObject = $objectRepository->getObjectByIdAndRevision(1, 0)->getValue(); $streamDecoder = new StreamDecoder($pdfStream); $dataDecoded = $streamDecoder->decodeStream($pdfStreamObject); $this->assertEquals($dataDecoded, 'Hello World!'); }
public static function end() { $content = gzuncompress(gzcompress(ob_get_contents())); ob_end_clean(); $r = RenderingStack::peek(); if (self::$store_mode == self::STORE_MODE_OVERWRITE || self::$store_mode == self::STORE_MODE_ERROR_ON_OVERWRITE) { $r->set(self::$sector_path, $content); } if (self::$store_mode == self::STORE_MODE_APPEND) { if ($r->is_set(self::$sector_path)) { $old_content = $r->get(self::$sector_path); $r->set(self::$sector_path, $old_content . $content); } else { $r->set(self::$sector_path, $content); } } if (self::$store_mode == self::STORE_MODE_PREPEND) { if ($r->is_set(self::$sector_path)) { $old_content = $r->get(self::$sector_path); $r->set(self::$sector_path, $content . $old_content); } else { $r->set(self::$sector_path, $content); } } self::$sector_opened = false; self::$store_mode = null; self::$sector_path = null; }
public function createAction($extensionKey, $sourcePath, $t3xFilePath) { $sourcePath = rtrim($sourcePath, '/') . '/'; if (!is_dir($sourcePath)) { throw new \Exception('Cant read "' . $sourcePath . '"'); } if (!file_exists($sourcePath . 'ext_emconf.php')) { throw new \Exception('ext_emconf.php missing in "' . $sourcePath . '"'); } if (file_exists($t3xFilePath)) { throw new \Exception('File already exists "' . $t3xFilePath . '"'); } if (!is_writable(dirname($t3xFilePath))) { throw new \Exception('Cant write "' . $t3xFilePath . '"'); } $extensionData = array('extKey' => $extensionKey, 'EM_CONF' => \etobi\extensionUtils\ter\Helper::getEmConf($extensionKey, $sourcePath), 'misc' => array(), 'techInfo' => array(), 'FILES' => \etobi\extensionUtils\ter\Helper::getExtensionFilesData($sourcePath)); $data = serialize($extensionData); $md5 = md5($data); $compress = ''; if (function_exists('gzcompress')) { $compress = 'gzcompress'; $data = gzcompress($data); } $success = file_put_contents($t3xFilePath, $md5 . ':' . $compress . ':' . $data); if ($success === FALSE) { throw new \Exception('Error writing "' . $t3xFilePath . '"'); } echo 'created "' . $t3xFilePath . '"' . chr(10); }
/** * Label compressed entries and check if gzcompress exists * * @param string $data * @return string */ private function handleCompression($data) { if (function_exists('gzcompress')) { $data = self::COMPRESSION_PREFIX . gzcompress($data); } return $data; }
function gzip($filename) { mkdir_recursive($filename); $data = file_get_contents($filename); $gzdata = gzcompress($data, 9); save($filename, $data); }
function _endpage() { parent::_endpage(); if ($this->compress) { $this->pages[$this->page] = gzcompress($this->pages[$this->page]); } }