save() public method

Save some data in a cache file
public save ( string $data, string $id = NULL, string $group = 'default' ) : boolean
$data string data to put in cache (can be another type than strings if automaticSerialization is on)
$id string cache id
$group string name of the cache group
return boolean true if no problem (else : false or a PEAR_Error object)
Exemplo n.º 1
0
 function getFromUserFunction()
 {
     $result = $this->object->{$this->method}();
     if ($result) {
         $this->oCache->save(serialize($result), $this->cacheId, $this->groupId);
         return $result;
     }
     return $this->getFromPermamentCache();
 }
 /**
  * A method to save the permanent cache content. The content will be serialized and
  * compressed to save space
  *
  * @param mixed  $data     The content to save
  * @param string $cacheName The name of the original file we are storing
  * @return bool True if the cache was correctly saved
  */
 function save($data, $cacheName)
 {
     if (is_writable($this->cachePath) && extension_loaded('zlib')) {
         $id = $this->_getId($cacheName);
         $group = $this->_getGroup($cacheName);
         return $this->oCache->save(gzcompress(serialize($data), 9), $id, $group);
     }
     return false;
 }
Exemplo n.º 3
0
 public function getData()
 {
     $Cache_Lite = new Cache_Lite(parent::getCacheOptions());
     $url = sprintf('https://readitlaterlist.com/v2/get?username=%s&password=%s&apikey=%s&count=%s&format=json', $this->config['username'], $this->config['password'], $this->config['apikey'], $this->config['total']);
     $id = $url;
     if ($data = $Cache_Lite->get($id)) {
         $data = json_decode($data);
     } else {
         $Cache_Lite->get($id);
         PubwichLog::log(2, Pubwich::_('Rebuilding cache for a Readitlater'));
         PubwichLog::log(2, $this->url);
         $data = file_get_contents($url);
         $data = json_decode($data);
         foreach ($data->list as $item) {
             // Default value
             $item->title = parse_url($item->url, PHP_URL_HOST);
             // If check page title
             if (!empty($this->config['getTitle'])) {
                 $file = @fopen($item->url, "r");
                 if ($file) {
                     $text = fread($file, 1024 * 3);
                     if (preg_match('/<title>(.*?)<\\/title>/is', $text, $found)) {
                         $item->title = $found[1];
                     }
                 }
             }
         }
         // Write cache
         $cacheWrite = $Cache_Lite->save(json_encode($data));
     }
     return $data->list;
 }
Exemplo n.º 4
0
 /**
  * Retrieves data from cache, if it's there.  If it is, but it's expired,
  * it performs a conditional GET to see if the data is updated.  If it
  * isn't, it down updates the modification time of the cache file and
  * returns the data.  If the cache is not there, or the remote file has been
  * modified, it is downloaded and cached.
  *
  * @param string URL of remote file to retrieve
  * @param int Length of time to cache file locally before asking the server
  *            if it changed.
  * @return string File contents
  */
 function retrieveFile($url, $cacheLength, $cacheDir)
 {
     $cacheID = md5($url);
     $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength));
     if ($data = $cache->get($cacheID)) {
         return $data;
     } else {
         // we need to perform a request, so include HTTP_Request
         include_once 'HTTP/Request.php';
         // HTTP_Request has moronic redirect "handling", turn that off (Alexey Borzov)
         $req = new HTTP_Request($url, array('allowRedirects' => false));
         // if $cache->get($cacheID) found the file, but it was expired,
         // $cache->_file will exist
         if (isset($cache->_file) && file_exists($cache->_file)) {
             $req->addHeader('If-Modified-Since', gmdate("D, d M Y H:i:s", filemtime($cache->_file)) . " GMT");
         }
         $req->sendRequest();
         if (!($req->getResponseCode() == 304)) {
             // data is changed, so save it to cache
             $data = $req->getResponseBody();
             $cache->save($data, $cacheID);
             return $data;
         } else {
             // retrieve the data, since the first time we did this failed
             if ($data = $cache->get($cacheID, 'default', true)) {
                 return $data;
             }
         }
     }
     Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED);
     return false;
 }
Exemplo n.º 5
0
 public function Cacheing($url, $flag, $date, $time = 360)
 {
     $cacheoptions = array('caching' => true, 'lifeTime' => $time, 'automaticCleaningFactor' => '100', 'cacheDir' => dirname(__FILE__) . '/nicocache/cache/');
     $CacheLite = new Cache_Lite($cacheoptions);
     $returndate;
     switch ($flag) {
         case TRUE:
             if ($filedate = $CacheLite->get($url)) {
                 switch ($date) {
                     case "xml":
                         $xml = simplexml_load_string($filedate, 'SimpleXMLElement', LIBXML_NOCDATA);
                         if ($xml) {
                             $returndate = $xml;
                         } else {
                             $returndate = $filedate;
                         }
                         break;
                     case "html":
                         $returndate = $filedate;
                         break;
                 }
             } else {
                 $returndate = FALSE;
             }
             break;
         case FALSE:
             if ($CacheLite->save($date, $url)) {
                 $returndate = TRUE;
             } else {
                 $returndate = FALSE;
             }
             break;
     }
     return $returndate;
 }
Exemplo n.º 6
0
function transaction($sql)
{
    global $response, $apiKey, $data, $basePath;
    $parsedSQL = SqlParser::ParseString($sql)->getArray();
    //$tokens = SqlParser::Tokenize($sql, true);
    if (strpos($sql, ';') !== false) {
        $response['success'] = false;
        $response['message'] = "You can't use ';'. Use the bulk transaction API instead";
    } elseif (strpos($sql, '--') !== false) {
        $response['success'] = false;
        $response['message'] = "SQL comments '--' are not allowed";
    } elseif ($parsedSQL['drop']) {
        $response['success'] = false;
        $response['message'] = "DROP is not allowed through the API";
    } elseif ($parsedSQL['alter']) {
        $response['success'] = false;
        $response['message'] = "ALTER is not allowed through the API";
    } elseif ($parsedSQL['create']) {
        $response['success'] = false;
        $response['message'] = "CREATE is not allowed through the API";
    } elseif ($parsedSQL['update'] || $parsedSQL['insert'] || $parsedSQL['delete']) {
        if ($apiKey == $_REQUEST['key'] || $apiKey == false) {
            $api = new sqlapi();
            $response = $api->transaction($_REQUEST['q']);
        } else {
            $response['success'] = false;
            $response['message'] = "Not the right key!";
        }
    } elseif ($parsedSQL['select']) {
        parse_str(urldecode($_SERVER['QUERY_STRING']), $args);
        $id = $args['q'];
        if (!$args['lifetime']) {
            $args['lifetime'] = 0;
        }
        $options = array('cacheDir' => "{$basePath}/tmp/", 'lifeTime' => $args['lifetime']);
        $Cache_Lite = new Cache_Lite($options);
        if ($data = $Cache_Lite->get($id)) {
            //echo "cached";
        } else {
            ob_start();
            if ($_REQUEST['srs']) {
                $srs = $_REQUEST['srs'];
            } else {
                $srs = "900913";
            }
            $api = new sqlapi($srs);
            $api->execQuery("set client_encoding='UTF8'", "PDO");
            $response = $api->sql($_REQUEST['q']);
            echo json_encode($response);
            // Cache script
            $data = ob_get_contents();
            $Cache_Lite->save($data, $id);
            ob_get_clean();
        }
    } else {
        $response['success'] = false;
        $response['message'] = "Check your SQL. Could not recognise it as either SELECT, INSERT, UPDATE or DELETE";
    }
    return $response;
}
 /**
  * versionCheck - Get the most current version of nterchange and cache the result.
  *
  * @return 	array 	Information about the newest version of nterchange.
  **/
 function versionCheck()
 {
     require_once 'Cache/Lite.php';
     $options = array('cacheDir' => CACHE_DIR . '/ntercache/', 'lifeTime' => $this->check_version_interval);
     $cache = new Cache_Lite($options);
     $yaml = $cache->get($this->cache_name, $this->cache_group);
     if (empty($yaml)) {
         include_once 'HTTP/Request.php';
         $req = new HTTP_Request($this->check_version_url);
         if (!PEAR::isError($req->sendRequest())) {
             $yaml = $req->getResponseBody();
             $cached = $cache->save($yaml, $this->cache_name, $this->cache_group);
             if ($cached == true) {
                 NDebug::debug('Version check - data is from the web and is now cached.', N_DEBUGTYPE_INFO);
             } else {
                 NDebug::debug('Version check - data is from the web and is NOT cached.', N_DEBUGTYPE_INFO);
             }
         }
     } else {
         NDebug::debug('Version check - data is from the cache.', N_DEBUGTYPE_INFO);
     }
     require_once 'vendor/spyc.php';
     $newest_version_info = @Spyc::YAMLLoad($yaml);
     return $newest_version_info;
 }
Exemplo n.º 8
0
 public function save($contents)
 {
     global $config;
     if ($config['cache']['disable']) {
         return false;
     }
     return parent::save($contents, $this->cache_id, $this->cache_group);
 }
 /**
  * Overrides Cache_Lite save() method.
  *
  * @access public
  *
  * @param string  $data  Data to put in cache (can be another type than strings
  *                       if automaticSerialization is on).
  * @param string  $id    (optional) Cache id.
  * @param string  $group (optional) Name of the cache group.
  *
  * @return boolean True if no problem (else : false or a PEAR_Error object).
  */
 public function save($data, $id = NULL, $group = 'default')
 {
     $result = parent::save($data, $id, $group);
     // Change the permissions on the cache file, so users other than the web server
     // user can manage the file.
     chmod($this->_file, 0664);
     return $result;
 }
Exemplo n.º 10
0
 /**
  * 保存Cache文件
  * @param Cache_Lite $oCache
  * @param string $id
  * @param string $group
  * @param array $data
  * @param string $cachePath
  */
 public static function saveCache($oCache, $id, $group, $data, $cachePath)
 {
     if (is_writable($cachePath) && extension_loaded('zlib')) {
         $data = gzcompress(serialize($data), 9);
         return $oCache->save($data, $id, $group);
     }
     return false;
 }
Exemplo n.º 11
0
 private function get_file($type)
 {
     include_once 'Cache_Lite/Lite.php';
     $db = Input::getPath()->part(5);
     $baseLayer = Input::get("baselayer");
     $layers = Input::get("layers");
     $center = Input::get("center");
     $zoom = Input::get("zoom");
     $size = Input::get("size");
     $sizeArr = explode("x", Input::get("size"));
     $bbox = Input::get("bbox");
     $sql = Input::get("sql");
     $id = $db . "_" . $baseLayer . "_" . $layers . "_" . $center . "_" . $zoom . "_" . $size . "_" . $bbox . "_" . $sql;
     $lifetime = Input::get('lifetime') ?: 0;
     $options = array('cacheDir' => \app\conf\App::$param['path'] . "app/tmp/", 'lifeTime' => $lifetime);
     $Cache_Lite = new \Cache_Lite($options);
     if ($data = $Cache_Lite->get($id)) {
         //echo "Cached";
     } else {
         ob_start();
         $fileName = md5(time() . rand(10000, 99999) . microtime());
         $file = \app\conf\App::$param["path"] . "/app/tmp/_" . $fileName . "." . $type;
         $cmd = "wkhtmltoimage " . "--height {$sizeArr[1]} --disable-smart-width --width {$sizeArr[0]} --quality 90 --javascript-delay 1000 " . "\"" . "http://127.0.0.1" . "/api/v1/staticmap/html/{$db}?baselayer={$baseLayer}&layers={$layers}&center={$center}&zoom={$zoom}&size={$size}&bbox={$bbox}&sql={$sql}\" " . $file;
         //die($cmd);
         exec($cmd);
         switch ($type) {
             case "png":
                 $res = imagecreatefrompng($file);
                 break;
             case "jpg":
                 $res = imagecreatefromjpeg($file);
                 break;
         }
         if (!$res) {
             $response['success'] = false;
             $response['message'] = "Could not create image";
             $response['code'] = 406;
             header("HTTP/1.0 {$response['code']} " . \app\inc\Util::httpCodeText($response['code']));
             echo \app\inc\Response::toJson($response);
             exit;
         }
         header('Content-type: image/png');
         imageAlphaBlending($res, true);
         imageSaveAlpha($res, true);
         imagepng($res);
         // Cache script
         $data = ob_get_contents();
         $Cache_Lite->save($data, $id);
         ob_get_clean();
     }
     header("Content-type: image/png");
     echo $data;
     exit;
 }
Exemplo n.º 12
0
 public function getPage($pageID, $apply_shortcodes = false)
 {
     $options = array('caching' => true, 'cacheDir' => APP_ROOT . 'app/' . APP_NAME . '/cache/', 'lifeTime' => 3600, 'fileNameProtection' => true);
     $cache = new Cache_Lite($options);
     $cacheName = 'wptool' . self::$wp_root . $pageID . '_' . $apply_shortcodes;
     if ($_cachedData = $cache->get($cacheName)) {
         return unserialize($_cachedData);
     }
     $c = self::_fetchPage($pageID, $apply_shortcodes);
     $cache->save(serialize($c));
     return $c;
 }
Exemplo n.º 13
0
 /**
  * Stores data into cache
  *
  * @param	string	$id
  * @param	mixed	$data
  * @param	array	(optional) $tags
  * @param	int		(optional) $lifetime
  * @return	bool
  */
 public function put($id, $data, array $tags = null, $lifetime = null)
 {
     if (($lifetime = (int) $lifetime) <= 0) {
         $lifetime = null;
     } elseif ($lifetime <= 2592000) {
         $lifetime += VIVVO_START_TIME - 1;
     } else {
         $lifetime -= 1;
     }
     $this->cache_lite->setLifeTime($lifetime);
     return $this->cache_lite->save($data, md5($id), 'vivvo_cache') === true;
 }
Exemplo n.º 14
0
function getCachedContent($url, $anonfunction)
{
    $options = array('lifeTime' => 86400, 'pearErrorMode' => CACHE_LITE_ERROR_DIE);
    $cache = new Cache_Lite($options);
    if ($data = $cache->get($url)) {
        return $data;
    } else {
        // No valid cache found (you have to make and save the page)
        $data = $anonfunction;
        $cache->save($data);
        return $data;
    }
}
 function _list_output()
 {
     $sm = vivvo_lite_site::get_instance();
     $content_template = $this->load_template($this->_template_root . 'content.xml');
     require_once VIVVO_FS_FRAMEWORK . '/PEAR/Lite.php';
     $options = array('cacheDir' => VIVVO_FS_ROOT . 'cache/', 'lifeTime' => 600);
     $cache_manager = new Cache_Lite($options);
     $web_stat = $cache_manager->get('web_statistics', 'admin');
     if (empty($web_stat)) {
         $web_stat = $this->web_statistics();
         $cache_manager->save($web_stat, 'web_statistics', 'admin');
     }
     $system_stat = $cache_manager->get('system_statistics', 'admin');
     if (empty($system_stat)) {
         $system_stat = $this->system_statistics();
         $cache_manager->save($system_stat, 'system_statistics', 'admin');
     }
     $today_stat = $cache_manager->get('today_statistics', 'admin');
     if (empty($today_stat)) {
         $today_stat = $this->today_statistics();
         $cache_manager->save($today_stat, 'today_statistics', 'admin');
     }
     $signup_stat = $cache_manager->get('signup_statistics', 'admin');
     if (empty($signup_stat)) {
         $signup_stat = $this->signup_statistics();
         $cache_manager->save($signup_stat, 'signup_statistics', 'admin');
     }
     $content_template->assign('web_statistics', $web_stat);
     $content_template->assign('system_statistics', $system_stat);
     $content_template->assign('today_statistics', $today_stat);
     $content_template->assign('signup_statistics', $signup_stat);
     $log_file = VIVVO_FS_ROOT . VIVVO_FS_FILES_DIR . 'logs/' . date('Y') . '-' . date('m') . '.txt';
     $handle = @fopen($log_file, "r");
     if ($handle) {
         $i = 0;
         while (!feof($handle) && $i < 10) {
             $buffer .= str_replace(',', ', ', str_replace('"', '', fgets($handle, 4096)));
             $i++;
         }
         fclose($handle);
         $content_template->assign('activity_log', strval($buffer));
     } else {
         $content_template->assign('activity_log', strval(''));
     }
     $content_template->assign('activity_log_link', strval(VIVVO_URL . VIVVO_FS_ADMIN_DIR . 'download.php?file=' . VIVVO_FS_FILES_DIR . 'logs/' . date('Y') . '-' . date('m') . '.txt'));
     return $content_template;
 }
 /**
  * Store the data to cache by ID and group
  *
  * @param   string  $id     The cache data ID
  * @param   string  $group  The cache data group
  * @param   string  $data   The data to store in cache
  *
  * @return  boolean
  *
  * @since   11.1
  */
 public function store($id, $group, $data)
 {
     $dir = $this->_root . '/' . $group;
     // If the folder doesn't exist try to create it
     if (!is_dir($dir)) {
         // Make sure the index file is there
         $indexFile = $dir . '/index.html';
         @mkdir($dir) && file_put_contents($indexFile, '<!DOCTYPE html><title></title>');
     }
     // Make sure the folder exists
     if (!is_dir($dir)) {
         return false;
     }
     static::$CacheLiteInstance->setOption('cacheDir', $this->_root . '/' . $group . '/');
     // This call is needed to ensure $this->rawname is set
     $this->_getCacheId($id, $group);
     return static::$CacheLiteInstance->save($data, $this->rawname, $group);
 }
Exemplo n.º 17
0
 /**
  * Parses the data files of the map.
  *
  * @access public
  * @return array
  */
 function parse()
 {
     foreach ($this->dataFiles as $dataFile => $color) {
         $cacheID = md5($dataFile . '_' . $color);
         $lineSet = false;
         if (is_object($this->cache) && ($lineSet = $this->cache->get($cacheID, 'Image_GIS'))) {
             $lineSet = unserialize($lineSet);
         }
         if ($lineSet === false) {
             $lineSet = $this->parseFile($dataFile, $color);
             if (is_object($this->cache)) {
                 $this->cache->save(serialize($lineSet), $cacheID, 'Image_GIS');
             }
         }
         $this->lineSets[] = $lineSet;
     }
     return $this->lineSets;
 }
Exemplo n.º 18
0
 /**
  * Save some data in a cache file
  *
  * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
  * @param string $id cache id
  * @param string $group name of the cache group
  * @param int $lifetime The time in seconds that this entry should live. Defaults to the lifetime
  *  set by the constructor.
  * @return boolean true if no problem (else : false or a PEAR_Error object)
  * @access public
  */
 function save($data, $id = NULL, $group = 'default', $lifetime = null)
 {
     $res = parent::save($data, $id, $group);
     if ($res === true) {
         if ($lifetime == null) {
             $lifetime = $this->_bufferedLifetime;
         }
         if ($lifetime == null) {
             $lifetime = $this->_lifeTime;
         }
         $res = $this->_setLastModified(time() + $lifetime);
         if (is_object($res)) {
             // $res is a PEAR_Error object
             if (!$this->_errorHandlingAPIBreak) {
                 return false;
                 // we return false (old API)
             }
         }
     }
     return $res;
 }
Exemplo n.º 19
0
 protected function generateOptions()
 {
     $AuthOptions = PEAR::getStaticProperty('m_office', 'options');
     $userOpt = $AuthOptions['auth'];
     $opt = array('all' => PEAR::getStaticProperty('Module', 'global'));
     $options = array('caching' => MODE == 'developpement' ? false : true, 'cacheDir' => $opt['all']['cacheDir'] . '/config/' . ($userOpt ? User::getInstance('office')->getId() . '/' : ''), 'lifeTime' => null, 'fileNameProtection' => false, 'automaticSerialization' => true);
     $optcache = new Cache_Lite($options);
     if (!($moduleopt = $optcache->get($this->_modulename))) {
         if (@(include_once $this->_path . $this->_modulename . '.conf.php')) {
             if (!is_array($config)) {
                 $config = array();
             }
             $moduleopt = MArray::array_merge_recursive_unique($opt, $config);
         } else {
             $moduleopt = $opt;
         }
         $useropt = Mreg::get('authHelper')->getPrivilegesForModule(User::getInstance('office'), $this->_modulename);
         $moduleopt = MArray::array_merge_recursive_unique($moduleopt, $useropt);
         $optcache->save($moduleopt);
     }
     return $moduleopt;
 }
 /**
  * Response controller.
  *
  * @param  integer $cache_lifetime
  * @param  boolean $respond_to_conditional_request
  * @param  string  $format (rss1|rss2)
  * @return void
  */
 public function getFeed($cache_lifetime = 0, $respond_to_conditional_request = true, $format = 'rss2', $format_output = false)
 {
     $cache_lifetime = (int) $cache_lifetime;
     $use_cache = !empty($this->cacheDir) and $cache_lifetime > 0;
     if ($use_cache) {
         $cache = new Cache_Lite(array('cacheDir' => $this->cacheDir, 'lifeTime' => $cache_lifetime));
         $cache_id = $_SERVER['REQUEST_URI'];
         if ($respond_to_conditional_request) {
             $this->emulateLastModified($cache_id, $cache_lifetime);
         }
     }
     if (!$use_cache or false === ($feed = $cache->get($cache_id))) {
         $this->analyze();
         $doc = $this->buildFeed($format, $format_output);
         $feed = $doc->saveXML();
         if ($use_cache) {
             $cache->save($feed, $cache_id);
         }
     }
     header('Content-Type: application/xml;charset=UTF-8');
     echo $feed;
     exit;
 }
Exemplo n.º 21
0
 function _retrieveFile($url, $cacheLength, $cacheDir)
 {
     $cacheID = md5($url);
     $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength));
     if ($data = $cache->get($cacheID)) {
         return $data;
     } else {
         $fp = fopen($url, 'r');
         $data = stream_get_contents($fp);
         if (strlen($data) > 10) {
             // data is changed, so save it to cache
             $cache->save($data, $cacheID);
             return $data;
         } else {
             // retrieve the data, since the first time we did this failed
             if ($data = $cache->get($cacheID, 'default', true)) {
                 return $data;
             }
         }
     }
     Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED);
     return false;
 }
Exemplo n.º 22
0
            $locT = $_GET['locT'];
            $url = $url . "&locId=" . $locId . "&locT=" . $locT;
        }
        if (isset($_GET['title'])) {
            $title = $_GET['title'];
            $url = $url . "&sc.jobTitle=" . $title;
        }
    }
}
// Query cache
if ($content = $Cache_Lite->get($url)) {
    error_log("Cache hit: " . $url);
} else {
    $curl = new Net_Curl($url);
    $content = $curl->execute();
    $Cache_Lite->save($content, $url);
}
// Write JSON output
$final_json = array("contents" => $content);
$result = json_encode($final_json, JSON_HEX_TAG);
if (isset($_GET['callback'])) {
    header('Content-Type: text/json; charset=utf8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
    $callback = $_GET['callback'];
    echo $callback . '(' . $result . ');';
} else {
    // normal JSON string
    header('Content-Type: application/json; charset=utf8');
    echo $result;
 /**
  * Calculates infos on the given file and returns an array containing these infos
  */
 function GetFileInfo($url)
 {
     global $serendipity;
     $this->log("GetFileInfo for {$url}");
     $fileInfo = array();
     //caching metadata
     $cacheOptions = array('lifeTime' => '2592000', 'automaticSerialization' => true, 'cacheDir' => $serendipity['serendipityPath'] . 'templates_c/');
     if (serendipity_db_bool($this->get_config('use_cache', 'true'))) {
         $this->log("GetFileInfo: Trying cached infos");
         //md5 for not having strange characters in that id..
         $cacheId = md5($url) . '.2';
         include_once S9Y_PEAR_PATH . "Cache/Lite.php";
         $cache = new Cache_Lite($cacheOptions);
         if ($fileInfo = $cache->get($cacheId)) {
             $this->log("GetFileInfo: Cached infos found in file {$cacheId}");
             //return directly on cache hit
             return $fileInfo;
         }
     }
     //cache miss! -> get data, store it in cache and return.
     // translate pontential relative url to absolute url
     if (preg_match('@https?://@', $url)) {
         $absolute_url = $url;
     } else {
         $absolute_url = $this->GetHostUrl() . $url;
     }
     if ($this->debug) {
         $fileInfo['absolute_url'] = $absolute_url;
     }
     // Now remove configured base URL
     $rel_path = str_replace($serendipity['baseURL'], "", $absolute_url);
     if ($this->debug) {
         $fileInfo['rel_path'] = $rel_path;
     }
     // do we have a local file here?
     //$localMediaFile = $serendipity['serendipityPath'] . $urlParts['path'];
     $localMediaFile = $serendipity['serendipityPath'] . $rel_path;
     $fileInfo['localMediaFile'] = $localMediaFile;
     $this->log("Absolute_url: {$absolute_url} - Relative: {$localMediaFile}");
     // Remember extension of file
     list($sName, $fileInfo['extension']) = serendipity_parseFileName($localMediaFile);
     if (file_exists($localMediaFile)) {
         $this->log("GetFileInfo: Local file exists");
         $fileInfo['length'] = filesize($localMediaFile);
         $fileInfo['md5'] = md5_file($localMediaFile);
         $this->GetID3Infos($localMediaFile, $fileInfo);
         $this->log(print_r($fileInfo, true));
         // Set default
         $fileInfo['mime'] = $this->getFileMime($fileInfo['extension'], $fileInfo['mime']);
     } elseif (preg_match('@https?://@', $url)) {
         include_once S9Y_PEAR_PATH . 'HTTP/Request.php';
         if (function_exists('serendipity_request_start')) {
             serendipity_request_start();
         }
         $this->Log("Execute HTTP_Request for {$url}");
         $http = new HTTP_Request($url);
         $http->setMethod(HTTP_REQUEST_METHOD_HEAD);
         if (!PEAR::isError($http->sendRequest(false))) {
             $fileInfo['length'] = intval($http->getResponseHeader('content-length'));
             $fileInfo['md5'] = $http->getResponseHeader('content-md5');
             //will return false if not present
             $fileInfo['mime'] = $http->getResponseHeader('content-type');
             $this->Log("Filling MIME with HTTP Header: " . print_r($fileInfo, true));
         }
         if (function_exists('serendipity_request_end')) {
             serendipity_request_end();
         }
     } else {
         // Not found locally and no URL
         $fileInfo['notfound'] = true;
     }
     if (serendipity_db_bool($this->get_config('use_cache', 'true'))) {
         $cache->save($fileInfo, $cacheId);
     }
     return $fileInfo;
 }
Exemplo n.º 24
0
 /**
  * Check if the last two parts of the FQDN are whitelisted.
  *
  * @param  string Host to check if it is whitelisted
  * @access protected
  * @return boolean True if the host is whitelisted
  */
 function isDoubleCcTld($fqdn)
 {
     // 30 Days should be way enough
     $options = array('lifeTime' => '2592000', 'automaticSerialization' => true);
     $id = md5($this->doubleCcTldFile);
     $cache = new Cache_Lite($options);
     if ($data = $cache->get($id)) {
         // Cache hit
     } else {
         // Cache miss
         $http =& new HTTP_Request($this->doubleCcTldFile);
         if (!PEAR::isError($http->sendRequest())) {
             $data = $http->getResponseBody();
         }
         $data = explode("\n", $data);
         $data = array_flip($data);
         $cache->save($data, $id);
     }
     // if
     if (array_key_exists($fqdn, $data)) {
         return true;
     } else {
         return false;
     }
     // if
 }
Exemplo n.º 25
0
 /**
  * Sets access token data from an HTTP_OAuth_Store_Data object
  * 
  * @param HTTP_OAuth_Store_Data $data The access token data
  * 
  * @return bool true on success, false or PEAR_Error on failure
  */
 public function setAccessToken(HTTP_OAuth_Store_Data $data)
 {
     $this->setOptions(self::TYPE_ACCESS);
     $key = $this->getAccessTokenKey($data->consumerUserID, $data->providerName);
     return $this->cache->save(serialize($data), $key);
 }
Exemplo n.º 26
0
            if (strstr($this->ms['MODULES']['PRODUCTS_LISTING_TYPE'], "..")) {
                die('error in PRODUCTS_LISTING_TYPE value');
            } else {
                if (strstr($this->ms['MODULES']['PRODUCTS_LISTING_TYPE'], "/")) {
                    require $this->DOCUMENT_ROOT . $this->ms['MODULES']['PRODUCTS_LISTING_TYPE'] . '.php';
                } else {
                    if (!$this->ms['MODULES']['PRODUCTS_LISTING_TYPE']) {
                        $this->ms['MODULES']['PRODUCTS_LISTING_TYPE'] = 'default';
                    }
                    require \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('multishop') . 'scripts/front_pages/includes/products_listing/' . $this->ms['MODULES']['PRODUCTS_LISTING_TYPE'] . '.php';
                }
            }
            // pagination
            if (!$this->hidePagination and $pageset['total_rows'] > $this->ms['MODULES']['PRODUCTS_LISTING_LIMIT']) {
                if (!isset($this->ms['MODULES']['PRODUCTS_LISTING_PAGINATION_TYPE']) || $this->ms['MODULES']['PRODUCTS_LISTING_PAGINATION_TYPE'] == 'default') {
                    require \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('multishop') . 'scripts/front_pages/includes/products_listing_pagination.php';
                } else {
                    require \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('multishop') . 'scripts/front_pages/includes/products_listing_pagination_with_number.php';
                }
            }
            // pagination eof
        } else {
            $this->no_database_results = 1;
            $content .= '<div class="main-heading"><h2>' . $this->pi_getLL('no_new_products_found_heading') . '</h2></div>' . "\n";
            $content .= '<p>' . $this->pi_getLL('no_new_products_found_description') . '</p>' . "\n";
        }
    }
    if ($this->ms['MODULES']['CACHE_FRONT_END']) {
        $Cache_Lite->save($content);
    }
}
Exemplo n.º 27
0
<?php

// Bench script of Cache_Lite
// $Id: bench.php,v 1.1 2009/03/26 18:56:29 mhoegh Exp $
require_once 'Cache/Lite.php';
$options = array('caching' => true, 'cacheDir' => '/tmp/', 'lifeTime' => 10);
$Cache_Lite = new Cache_Lite($options);
if ($data = $Cache_Lite->get('123')) {
    echo $data;
} else {
    $data = '';
    for ($i = 0; $i < 1000; $i++) {
        $data .= '0123456789';
    }
    echo $data;
    $Cache_Lite->save($data);
}
Exemplo n.º 28
0
Arquivo: Util.php Projeto: demental/m
 public static function &getSearchForm($do, $module)
 {
     MyQuickForm::registerElementType('advandate', 'HTML/QuickForm/advandate.php', 'HTML_QuickForm_advandate');
     $form = new MyQuickForm('formSearch', 'GET', self::getQueryParams(array(), array('page', '_c_'), false));
     $fields = $_GET;
     unset($fields['_c_']);
     unset($fields['page']);
     unset($fields['module']);
     unset($fields['action']);
     unset($fields['filterField']);
     unset($fields['filterValue']);
     if (count($fields) == 0) {
         Log::info('caching search form');
         $cache = true;
     } else {
         Log::info('NO SEARCH FORM CACHING');
         $cache = false;
     }
     $cacheName = 'searchform_' . $module;
     $options = array('caching' => $cache, 'cacheDir' => APP_ROOT . 'app/' . APP_NAME . '/cache/forms/', 'lifeTime' => 3600, 'fileNameProtection' => false);
     $cache = new Cache_Lite($options);
     if ($_cachedData = $cache->get($cacheName)) {
         Mreg::append('autoloadcallback', array(array('MyQuickForm', 'autoloadElements')));
         $_cachedData = unserialize($_cachedData);
         foreach ($_cachedData as $element) {
             $form->addElement($element);
         }
     } else {
         $do->fb_selectAddEmpty = array();
         if (is_array($do->links())) {
             foreach ($do->links() as $field => $link) {
                 $do->fb_selectAddEmpty[] = $field;
             }
         }
         if (is_array($do->fb_enumFields)) {
             foreach ($do->fb_enumFields as $field) {
                 $do->fb_selectAddEmpty[] = $field;
             }
         }
         $do->fb_formHeaderText = __('Search');
         $do->fb_submitText = '>>';
         $do->fb_linkNewValue = false;
         $formBuilder =& MyFB::create($do);
         $formBuilder->_cacheOptions = array('name' => 'office_searchform', 'cacheDir' => APP_ROOT . 'app/' . APP_NAME . '/cache/forms/');
         $formBuilder->preGenerateFormCallback = array($do, 'prepareSearchForm');
         $do->prepareSearchForm($fb);
         $do->fb_userEditableFields = $do->fb_fieldsToRender;
         $table = $do->table();
         foreach ($do->fb_fieldsToRender as $field) {
             if ($table[$field] & DB_DATAOBJECT_DATE || $table[$field] & DB_DATAOBJECT_TIME) {
                 $label = $do->fb_fieldLabels[$field] ? $do->fb_fieldLabels[$field] : $field;
                 $do->fb_preDefElements[$field] = MyQuickForm::createElement('advandate', $field, $label, array("language" => T::getLang()));
             }
         }
         $formBuilder->postGenerateFormCallback = array($do, 'postPrepareSearchForm');
         $formBuilder->useForm($form);
         $formBuilder->getForm();
         foreach ($form->_elements as $elem) {
             $cached[] = $elem;
         }
         if ($cache) {
             $cache->save(serialize($cached));
         }
     }
     $form->_rules = array();
     $form->_formRules = array();
     $form->_required = array();
     self::addHiddenFields($form, array('search', 'page', '__dontpaginate', '_c_'), true);
     $form->addElement('checkbox', '__dontpaginate', 'Afficher les résultats sur une seule page');
     return $form;
 }
Exemplo n.º 29
0
 /**
  * A method for saving a plugin module/package's data in a plugin cache file.
  *
  * @static
  * @param mixed $data The data to save in the cache (automaticSerialization is on, so
  *                    any data type should be okay to save).
  * @param string $id An item ID for the cache data.
  * @param string $module The plugin module name (i.e. /plugins/module directory).
  * @param string $package The plugin package name (i.e. /plugins/module/package
  *                        directory).
  * @param string $name Optional name of the PHP file which contains the plugin,
  *                     otherwise the plugin with the same name as the package
  *                     is assumed.
  * @param array $aOptions An optional array of constructor options for
  *                        PEAR::Cache_Lite. The default values are those
  *                        obtained from {@link MAX_Plugin::prepareCacheOptions()}.
  * @return boolean True on success, false otherwise.
  *
  */
 function saveCacheForPlugin($data, $id, $module, $package, $name = null, $aOptions = null)
 {
     if (is_null($name)) {
         $name = $package;
     }
     if (is_null($aOptions)) {
         $aOptions = MAX_Plugin::prepareCacheOptions($module, $package);
     }
     $cache = new Cache_Lite($aOptions);
     return $cache->save($data, $id, $name);
 }
Exemplo n.º 30
0
 function save($data, $id = NULL, $group = 'default')
 {
     parent::save($data, $id, $group);
     touch($this->_file . '_time');
 }