public function save() { self::purge($this); if (file_put_contents($this->path, Spyc::YAMLDump($this))) { cache::getInstance()->config = $this; } return $this; }
/** * Initialize the cache object */ private static function initCache() { self::$saveCacheFiles = false; self::$cacheFiles = cache::getInstance(); $tmp = self::$searchFiles; self::$searchFiles = array(); self::$cacheFiles->get(self::$searchFiles, array('ttl' => 0, 'id' => 'nyroExists', 'request' => array('uri' => false, 'meth' => array()), 'serialize' => true)); self::$searchFiles = array_merge($tmp, self::$searchFiles); self::$saveCacheFiles = true; }
/** * 入口点 */ function run() { $response = new response(); $cacheConfig = config('cache'); if ($cacheConfig['cache']) { $cache = cache::getInstance($cacheConfig); $content = $cache->check($this->http->url()); if (!empty($content)) { $response->setBody($content); $response->send(); } } try { $handler = $this->parseUrl(); if (is_array($handler)) { list($control, $action) = $handler; $path = ROOT . '/application/control/' . $control . '.php'; if (file_exists($path)) { include $path; $class = 'application\\control\\' . $control . 'Control'; if (class_exists($class)) { //$class = new \ReflectionClass($class); $class = new $class(); $class->response =& $response; if (method_exists($class, $action) && is_callable(array($class, $action)) || method_exists($class, '__call')) { $response->setCode(200); $response->setBody($this->__200($class, $action)); } else { $response->setCode(404); $response->setBody($this->__404($control, $action)); } } else { $response->setCode(404); $response->setBody($this->__404($control, $action)); } } else { $response->setCode(404); $response->setBody($this->__404($control, $action)); } } else { include ROOT . '/application/thread/' . $handler . '.php'; $class = 'application\\thread\\' . $handler . 'Thread'; $class = new $class(); $class->run(); } } catch (\Exception $e) { $response->setCode(500); $response->setBody($this->__500($e)); } finally { $response->send(); } }
/** * Сброс кэша. */ public static function rpc_get_reload(Context $ctx) { $tmpdir = $ctx->config->getPath('main/tmpdir'); $files = glob(os::path($tmpdir, 'mcms-fetch.*')); if (!empty($files)) { foreach ($files as $tmp) { unlink($tmp); } } $ctx->registry->broadcast('ru.molinos.cms.reload', array($ctx)); $ctx->registry->rebuild(); unset(cache::getInstance()->route); return $ctx->getRedirect(); }
public static function transform($xml, $xsltName, $mimeType = 'text/html', $status = 200) { if (null !== self::$lock) { Logger::backtrace('XSLT recursion: ' . $xsltName . ' while in ' . self::$lock); throw new RuntimeException(t('Рекурсия в XSLT недопустима.')); } $mode = empty($_GET['xslt']) ? 'server' : $_GET['xslt']; $xml = self::fixEntities($xml); if ('none' == $mode or empty($xsltName)) { return new Response('<?xml version="1.0"?>' . $xml, 'text/xml', $status); } if (!file_exists($xsltName)) { throw new RuntimeException(t('Шаблон %name не найден.', array('%name' => $xsltName))); } if ('client' == $mode) { $xml = str_replace('?>', '?><?xml-stylesheet type="text/xsl" href="' . $xsltName . '"?>', $xml); return new Response($xml, 'text/xml'); } $nocache = !empty($_GET['nocache']); $cache = cache::getInstance(); $ckey = 'xml:xsl:' . md5($xml) . ',' . filemtime($xsltName); if (false === ($output = $cache->{$ckey}) or $nocache) { set_error_handler(array(__CLASS__, 'eh')); $doc = new DOMDocument(); $doc->loadXML($xml); if (class_exists('xsltCache') and !$nocache) { $proc = new xsltCache(); $proc->importStyleSheet($xsltName); } else { $xsl = new DOMDocument(); @$xsl->load($xsltName); $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); } self::$lock = $xsltName; if ($output = str_replace(' xmlns=""', '', $proc->transformToXML($doc))) { $cache->{$ckey} = $output; } self::$lock = null; restore_error_handler(); } if (empty($output)) { throw new RuntimeException(t('Шаблон %xslt ничего не вернул.', array('%xslt' => $xsltName))); } if (null === $mimeType) { return trim(str_replace('<?xml version="1.0"?>', '', $output)); } return new Response($output, $mimeType, $status); }
/** * @route GET//api/xml/cached.xml */ public static function on_get_import(Context $ctx) { if ($ttl = intval($ctx->get('cache')) < 600) { $ttl = 600; } if (!($url = $ctx->get('url'))) { throw new BadRequestException(t('Не указан адрес импортируемого XML канала (GET-параметр url).')); } $cache = cache::getInstance(); $ttl = floor(time() / $ttl); $ckey = sprintf('XmlCache|%u|%s', $ttl, $url); if ($cached = $cache->{$ckey}) { return new Response($cached, 'text/xml'); } $xml = http::fetch($url, http::CONTENT); $cache->{$ckey} = $xml; Logger::log('Imported XML from ' . $url); return new Response($xml, 'text/xml'); }
public function getResponse(Context $ctx) { if (class_exists('APIStream')) { APIStream::init($ctx); } $page = array('status' => 200, 'base' => $ctx->url()->getBase($ctx), 'host' => MCMS_HOST_NAME, 'folder' => $ctx->folder(), 'sitefolder' => os::webpath(MCMS_SITE_FOLDER), 'prefix' => os::webpath(MCMS_SITE_FOLDER, 'themes'), 'query' => $ctx->query(), 'version' => defined('MCMS_VERSION') ? MCMS_VERSION : 'unknown', 'cache' => cache::getInstance()->getName(), 'memory' => ini_get('memory_limit'), 'time' => microtime(true) - MCMS_START_TIME, 'back' => urlencode(MCMS_REQUEST_URI), 'back_raw' => MCMS_REQUEST_URI, 'next' => $ctx->get('destination'), 'api' => 'cms://localhost/api/', 'rss' => class_exists('RSSRouter')); $request = ''; if ($userid = $ctx->user->id) { $request .= html::wrap('user', Node::findXML(array('id' => $userid), $ctx->db)); } $request .= $ctx->url()->getArgsXML(); $this->content .= html::wrap('request', $request); foreach ((array) $ctx->registry->poll('ru.molinos.cms.page.head', array($ctx, array(), null)) as $block) { if (!empty($block['result'])) { $this->content .= $block['result']; } } return xslt::transform(html::em('page', $page, $this->content), $this->xsl); }
/** * Формирует обратное облако (используемых объектов). Применяется, например, * для оценки редакторской активности. */ public static function on_get_cloud_rev_xml(Context $ctx) { list($st, $tt, $limit, $cache) = self::get_params($ctx); if ($cache) { $ckey = 'cloud/rev'; if ($ctx->get('extended')) { $ckey .= '/ext'; } $ttl = floor(time() / $cache); $ckey = sprintf($ckey . '/%s/%s/%u/%u', $st, $tt, $limit, floor(time() / $cache)); if ($cached = cache::getInstance()->{$ckey}) { return new Response($cached, 'text/xml'); } } $params = array(); $sql1 = sql::in(explode(' ', $st), $params); $sql2 = sql::in(explode(' ', $tt), $params); $data = $ctx->db->getResults($sql = 'SELECT n.id AS id, n.name AS name, ' . 'COUNT(*) AS `cnt` ' . 'FROM node n ' . 'INNER JOIN node__rel r ON r.nid = n.id ' . 'WHERE n.class ' . $sql1 . ' ' . 'AND n.published = 1 ' . 'AND n.deleted = 0 ' . 'AND r.tid IN (SELECT id FROM node WHERE published = 1 AND deleted = 0 AND class ' . $sql2 . ') ' . 'GROUP BY n.id, n.name ' . 'ORDER BY cnt DESC LIMIT ' . $limit, $params); // Идентификаторы объектов, для получения расширенной информации $nids = array(); // Считаем общее количество объектов. $count = 0; foreach ($data as $item) { $count += $item['cnt']; $nids[] = $item['id']; } $percent = $count / 100; $nodes = $ctx->get('extended') ? Node::find(array('id' => $nids), $ctx->db) : array(); $result = ''; $keys = array(); foreach ($data as $item) { $p = round($item['cnt'] / $percent); $name = isset($nodes[$item['id']]) ? $nodes[$item['id']]->getName() : $item['name']; $result .= html::em('item', array('id' => $item['id'], 'name' => trim($name), 'count' => $item['cnt'], 'percent' => $p, 'weight' => round($p / 10) + 1)); $keys[] = $item['id']; } $xml = html::em('cloud', array('total' => $count), $result); if ($cache) { cache::getInstance()->{$ckey} = $xml; } return new Response($xml, 'text/xml'); }
public function __construct() { $lang = cookie::get('jq_session_language'); Translator::setLang($lang ?: 'ru'); $const_data = constData::load(BASEDIR . '/caru/config.php'); $request = coreInput::getCleanInput(); $output = coreOutput::getInstance(); $output->assign('SERVER_URL', SERVER_URL); $output->assign('SITE_PATH', SITE_PATH); $output->assign('erp_flag', defined('SECTIONS') && SECTIONS == 'erp'); $output->assign('const_data', $const_data); $output->assign('cache', cache::getInstance()); $output->assign('language', Translator::getLang()); $output->setDir(BASEDIR . '/caru/'); $postfix = !defined('SECTIONS') || SECTIONS != 'terminal' ? "/" : "/terminal"; $output->setDir(BASEDIR . '/caru/', $postfix); $output->setTemplate('blank'); $this->section = isset($request['section']) ? $request['section'] : null; $this->act = isset($request['act']) ? $request['act'] : null; //----------------- // Авторизация //----------------- /* // для обратной совместимости с логином CashAssist if($this->act=='ext_login') { if(empty($request['login']) || empty($request['pass'])) die(0); die($this->externalLogin($request['login'],$request['pass'])); } */ $session = user_bo::session(); if (!$session) { // #36015 $backurl = filter_input(INPUT_SERVER, 'REQUEST_URI') ? filter_input(INPUT_SERVER, 'REQUEST_URI') : ''; $output->setTemplate('login'); $output->toTemplate('backurl', $backurl); $output->display(); return false; } // удаленным - нет if (in_array('deleted', user_bo::getSessionUserGroups())) { header('HTTP/1.1 403 Forbidden, please log in'); LogErrors::add("\n-------BEGIN-----\n" . "\n{$_SERVER['REQUEST_URI']}\n" . 'Case 3 (deleted). s_user: '******'session_false.log'); user_bo::logout(); $output->setTemplate('login'); $output->display(); return false; } if (!$this->checkAccess()) { LogErrors::add("\n-------BEGIN-----\n" . "\n{$_SERVER['REQUEST_URI']}\n" . 'Case 5 (no access). s_user: '******'session_false.log'); header('HTTP/1.1 403 Forbidden, please log in'); return false; } if ($this->section && $this->act) { $output->setTemplate($this->section . "/" . $this->act); } //----------------- // Подключаем контроллер //----------------- try { if (class_exists($this->section . "_controller")) { $cont_class = $this->section . "_controller"; $cont = new $cont_class($this); } else { $cont = new Controller($this); } if ($this->act && is_callable(array($cont, $this->act))) { call_user_func(array($cont, $this->act)); } } catch (Exception $e) { $output->setTemplate('_error'); $output->assign('exeption', $e); } $user = user_bo::getSessionUser(); $sections = $this->getAllowedSections(); $user['groups'] = user_bo::getSessionUserGroups(); $output->assign('sections', $sections); $output->assign('user', $user); $output->assign('section', $this->section ? $sections[$this->section] : null); $output->assign('act', $this->act); $output->assign('title', $this->act ? $sections[$this->section]['items'][$this->act] : null); $output->display(); return true; }
/** * Возвращает текущее зерно кэша, опционально его изменяет. */ private static function seed($reset = false) { $cache = cache::getInstance(); $result = intval($cache->widgetseed); if ($reset) { $cache->widgetseed = ++$result; if (defined('MCMS_FLOG_CACHE')) { Logger::log('widget seed changed to ' . $result); } } return $result; }
public function dispatch(Context $ctx) { $cache = cache::getInstance(); $ckey = $this->getCacheKey(); // Если страница есть в кэше — выводим сразу, даже не ищем маршрут. if (empty($_GET['nocache']) and is_array($cached = $cache->{$ckey})) { if (isset($cached['expires']) and time() < $cached['expires']) { Logger::log('hit: ' . MCMS_HOST_NAME . $_SERVER['REQUEST_URI'], 'cache'); header('HTTP/1.1 ' . $cached['code'] . ' ' . $cached['text']); header('Content-Type: ' . $cached['type']); header('Content-Length: ' . $cached['length']); die($cached['content']); } } if (false === ($tmp = $this->find($ctx, $ctx->query()))) { $tmp = $this->find($ctx, 'errors/404'); } if (!empty($tmp[0]['cache'])) { Logger::log('mis: ' . MCMS_HOST_NAME . '/' . $ctx->query(), 'cache'); } elseif (0 !== strpos($ctx->query(), 'api/')) { Logger::log('ign: ' . MCMS_HOST_NAME . '/' . $ctx->query(), 'cache'); } if ($ctx->debug('route')) { mcms::debug($tmp, $this); } if (false === $tmp) { return false; } list($match, $args) = $tmp; if (!empty($match['call'])) { array_unshift($args, $match); array_unshift($args, $ctx->query()); array_unshift($args, $ctx); list($class, $method) = explode('::', $match['call']); if (!class_exists($class) or !method_exists($class, $method)) { throw new RuntimeException(t('Неверный обработчик: <tt>%call()</tt>.', array('%call' => $match['call']))); } $output = call_user_func_array($match['call'], $args); if (empty($output)) { throw new RuntimeException(t('Обработчик этого адреса — %call — ничего не вернул.', array('%call' => $match['call'] . '()'))); } if ($output instanceof Response and !empty($match['cache'])) { $output->setCache($cache, $ckey, $match['cache']); } return $output; } return false; }
/** * Fetch the template * * @param array $prm Array parameter for retrieve the tpl file (exemple: used to force the tpl extension via tplExt) * return string The result fetched * @see file::nyroExists */ public function fetch(array $prm=array()) { $content = null; $cachedContent = false; $cachedLayout = false; $oldProxy = response::getProxy(); response::setProxy($this->responseProxy); $cacheResp = null; if ($this->cfg->cache['auto']) { $cache = cache::getInstance(array_merge(array('serialize'=>false), $this->cfg->cache)); $cache->get($content, array( 'id'=>$this->cfg->module.'-'.$this->cfg->action.'-'.str_replace(':', '..', $this->cfg->param) )); $cacheResp = cache::getInstance($this->cfg->cache); $cacheResp->get($callResp, array( 'id'=>$this->cfg->module.'-'.$this->cfg->action.'-'.str_replace(':', '..', $this->cfg->param).'-callResp' )); if (!empty($content)) { $cachedContent = true; $cachedLayout = $this->cfg->cache['layout']; if (!empty($callResp)) { $this->responseProxy->doCalls($callResp); $this->responseProxy->initCall(); } } } if (!$cachedContent) { // Nothing was cached $action = $this->cfg->action; if (array_key_exists('callback', $prm)) $action = call_user_func($prm['callback'], $prm['callbackPrm']); $file = $this->findTpl($prm, array( 'module_'.$this->cfg->module.'_view_'.$action, 'module_'.$this->cfg->defaultModule.'_view_'.$this->cfg->default )); if (file::exists($file)) $content = $this->_fetch($file); } if ($this->cfg->layout && !$cachedLayout) { // Action layout $file = $this->findTpl($prm, array( 'module_'.$this->cfg->module.'_view_'.$this->cfg->action.'Layout', 'module_'.$this->cfg->module.'_view_layout' )); if (file::exists($file)) { $this->content = $content; $content = $this->_fetch($file); } if ($this->cfg->cache['auto'] && $this->cfg->cache['layout']) $cache->save(); } if ($cacheResp && $this->responseProxy->hasCall()) { $callResp = $this->responseProxy->getCall(); $cacheResp->save(); } response::setProxy($oldProxy); return $content; }
private function loadVersionMd5List() { $ff_repo_url = self::REMOTE_CHECKSUM . '?version=' . version; $save_cache_name = 'antivirus_checksum_' . version; if (cache::getInstance()->get($save_cache_name, self::REMOTE_CACHETIME)) { $this->version_md5 = @unserialize(cache::getInstance()->get($save_cache_name, self::REMOTE_CACHETIME)); return null; } $response = system::getInstance()->url_get_contents($ff_repo_url); if (!is_null($response) && $response != 'error') { $this->version_md5 = @unserialize($response); } else { $md5file = root . "/resource/antivirus/.md5sum"; if (file_exists($md5file)) { $this->version_md5 = unserialize(@file_get_contents($md5file)); logger::getInstance()->log(logger::LEVEL_NOTIFY, 'Using local antivirus signature. Remote repository with hashsum antivirus is not available: ' . $ff_repo_url); } else { logger::getInstance()->log(logger::LEVEL_WARN, 'Local antivirus hashsum signature not founded:' . $md5file); } } cache::getInstance()->save($save_cache_name, serialize($this->version_md5)); }
public static function getSignature(Context $ctx = null, $full = false) { $result = array('version' => mcms::version(), 'client' => $_SERVER['REMOTE_ADDR']); try { if (null === $ctx) { $ctx = Context::last(); } $result['at'] = $ctx->host() . $ctx->folder(); $result['version_link'] = 'http://code.google.com/p/molinos-cms/wiki/ChangeLog_' . str_replace('.', '_', mcms::version(mcms::VERSION_STABLE)); if ($full) { $options = array(); if (count($parts = explode(':', mcms::config('db')))) { if (in_array($parts[0], Database::listDrivers())) { $options[] = $parts[0]; } } $options[] = str_replace('_provider', '', get_class(cache::getInstance())); $options[] = ini_get('memory_limit'); $result['options'] = join('+', $options); } } catch (Exception $e) { } return $result; }
/** * Get a cache instance * * @return cache_abstract */ public function getCache() { return cache::getInstance($this->cfg->cache); }
/** * Удаляет из кэша указанный тип документа. */ public static function flush($className) { unset(cache::getInstance()->{'schema:' . $className}); }
/** * Website main */ public static function main() { define('NYROVERSION', '0.2'); $globalContent = null; $globalVars = null; $cacheInst = null; $cacheInstVars = null; try { self::init(); $resp = response::getInstance(); self::$cfg->overload(__CLASS__.'Response'); if (self::$cfg->globalCache && !request::isPost() && count($_GET) == 0 && $resp->canGlobalCache()) { $prm = is_array(self::$cfg->globalCache) ? self::$cfg->globalCache : array(); $cacheInst = cache::getInstance(array_merge(array('serialize'=>false), $prm)); $id = str_replace('/', '._.', '/'.request::get('request')).(request::isAjax() ? '-ajax' : ''); $cacheInst->get($globalContent, array( 'id'=>$id )); $cacheInstVars = cache::getInstance(array_merge(array('serialize'=>true), $prm)); $cacheInstVars->get($globalVars, array( 'id'=>$id.'-vars' )); } if (is_null($globalContent)) { request::execModule(); if (DEV) { debug::timer('nyroProcess'); debug::timer('nyroRender'); } $resp->setContent(request::publishModule()); } } catch (module_exception $e) { session::setFlash('nyroError', 'MODULE or ACTION NOT FOUND<br />'.self::handleError($e)); $resp->error(null, 404); } catch (nException $e) { session::setFlash('nyroError', self::handleError($e)); $resp->error(null, 500); } catch (PDOException $e) { session::setFlash('nyroError', self::handleError($e)); $resp->error(null, 500); } catch (Exception $e) { session::setFlash('nyroError', self::handleError($e)); $resp->error(null, 500); } try { factory::saveCache(); if ($cacheInst) { if ($globalContent) { $resp->setVarsFromGlobalCache($globalVars); echo $globalContent; } else { $globalVars = $resp->getVarsForGlobalCache(); $globalContent = $resp->send(); $cacheInst->save(); $cacheInstVars->save(); echo $globalContent; } } else { echo $resp->send(); } } catch (Exception $e) { echo debug::trace($e); } }
/** * Сохранение сессионных данных. * * Перед сохранением из БД удаляются ранее существовавшие данные этой сессии. * @todo менять sid надо при _каждом_ сохранении, см. Session Fixation * Vulnerability. * * Если сессия не была загружена — возникает RuntimeException(). * * @see http://en.wikipedia.org/wiki/Session_fixation * * @return Session $this */ public function save($force = false) { static $sent = false; if ($force) { $sent = false; } // При запуске из консоли сессии никуда не сохраняем. if (empty($_SERVER['REMOTE_ADDR'])) { return; } if (null === $this->data) { throw new RuntimExeption(t('Session is being saved ' . 'without having been loaded.')); } if ($this->hash() != $this->_hash) { if (null === $this->id) { $this->id = $this->getsessionId(); } switch ($this->getStorageType()) { case 'file': os::mkdir(dirname($path = $this->getStoragePath($this->id)), t('Не удалось создать временный каталог для хранения сессий.')); if (!empty($this->data)) { os::write($path, serialize($this->data)); } elseif (file_exists($path)) { unlink($path); } break; default: $db = Context::last()->db; $db->exec("DELETE FROM node__session WHERE `sid` = ?", array($this->id)); $ckey = 'session:' . $this->id; $cache = cache::getInstance(); if (!empty($this->data)) { $db->exec("INSERT INTO node__session (`created`, `sid`, `data`) " . "VALUES (UTC_TIMESTAMP(), ?, ?)", array($this->id, serialize($this->data))); $cache->{$ckey} = serialize($this->data); } else { unset($cache->{$ckey}); } } if (!$sent) { $sent = true; // $path = '/'; $time = time() + 60 * 60 * 24 * 30; $name = self::cookie; if (!headers_sent()) { setcookie($name, empty($this->data) ? null : $this->id, $time); Logger::log("cookie set: {$name}={$this->id}", 'auth'); } } } return $this; }
/** * Initialize the cache objects */ public static function initCache() { self::$saveCacheLoad = false; self::$cacheLoad = cache::getInstance(); self::$cacheLoad->get(self::$loadFiles, array('ttl' => 0, 'id' => 'load', 'request' => array('uri' => false, 'meth' => array()), 'serialize' => true)); }
public function __construct() { $this->db = db::getInstance("guojizhan"); $this->cache = cache::getInstance("memcached"); }
/** * Compress the file requested, using MoxieCompressor library * * @param string $type File type (css or js) * @param array $prm Files to compress */ protected function compress($type, $prm) { $resp = response::getInstance(); if ($type == 'js') { $conf = $this->cfg->all; factory::mergeCfg($conf, $this->cfg->js); } else if ($type == 'css') { $conf = $this->cfg->all; factory::mergeCfg($conf, $this->cfg->css); } $key = $type.'--'.md5(serialize($prm)).'--'.md5(serialize($conf)); $supportsGzip = false; if ($conf['compress']) { $encodings = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? explode(',', strtolower(preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_ENCODING']))) : array(); if ($conf['gzip_compress'] && (in_array('gzip', $encodings) || in_array('x-gzip', $encodings) || isset($_SERVER['---------------'])) && function_exists('gzencode') && !ini_get('zlib.output_compression')) { $enc = in_array('x-gzip', $encodings) ? 'x-gzip' : 'gzip'; $supportsGzip = true; $key = 'gzip-'.$key; } } $content = null; $cache = cache::getInstance($this->cfg->cache); $cacheDate = $cache->get($content, array('id'=>$key)); if (!$conf['disk_cache'] || !$cacheDate) { foreach($prm as $file) { $f = file::nyroExists(array( 'name'=>'module_'.nyro::getCfg()->compressModule.'_'.$type.'_'.$file, 'type'=>'tpl', 'tplExt'=>$type )); if ($f) { if ($conf['php']) $content.= file::fetch($f); else $content.= file::read($f); } } if ($conf['compress']) { if ($type == 'js') { lib::load('jsMin'); $content = JSMin::minify($content); } else if ($type == 'css') { lib::load('cssMin'); $content = CssMin::minify($content, $conf['filters'], $conf['plugins']); } if ($supportsGzip) $content = gzencode($content, 9, FORCE_GZIP); } $cache->save(); } else if ($cacheDate) { $resp->addHeader('Age', time() - $cacheDate); } /* @var $resp response_http */ if ($conf['compress']) { $resp->setCompress(false); $resp->addHeader('Vary', 'Accept-Encoding'); // Handle proxies if ($conf['etags'] || preg_match('/MSIE/i', $_SERVER['HTTP_USER_AGENT'])) { // We need to use etags on IE since it will otherwise always load the contents $resp->addHeader('ETag', md5($content)); } $parseTime = $this->_parseTime($conf['expires_offset']); $resp->addHeader('Expires', gmdate('D, d M Y H:i:s', time() + $parseTime).' GMT'); $resp->addHeader('Cache-Control', 'public, max-age='.$parseTime); if ($type == 'js') { // Output explorer workaround or compressed file if (!isset($_GET['gz']) && $supportsGzip && $conf['patch_ie'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { // Build request URL $url = $_SERVER['REQUEST_URI']; if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING']) $url.= '?'.$_SERVER['QUERY_STRING'].'&gz=1'; else $url.= '?gz=1'; // This script will ensure that the gzipped script gets loaded on IE versions with the Gzip request chunk bug echo 'var gz;try {gz = new XMLHttpRequest();} catch(gz) { try {gz = new ActiveXObject("Microsoft.XMLHTTP");}'; echo 'catch (gz) {gz = new ActiveXObject("Msxml2.XMLHTTP");}}'; echo 'gz.open("GET", "'.$url.'", false);gz.send(null);eval(gz.responseText);'; die(); } } if ($supportsGzip) $resp->addHeader('Content-Encoding', $enc); } $resp->sendText($content); }