Example #1
0
 /**
  * @param string $key
  * @return bool
  */
 public function hasKey($key)
 {
     if ($this->memoryCache->hasKey($key)) {
         return true;
     }
     return $this->fileCache->hasKey($key);
 }
Example #2
0
 function testSet_expire()
 {
     $cache = new FileCache();
     $cache->set($this->name, $this->data, new DateTime('-1 day'));
     $result = $cache->get($this->name);
     $this->assertSame(null, $result);
 }
 public function execute($parameters, $db)
 {
     global $base;
     chdir($base);
     if (sizeof($parameters) == 0 || $parameters[0] == "") {
         CLI::out("Usage: |g|help <command>|n| To see a list of commands, use: |g|list", true);
     }
     $command = $parameters[0];
     switch ($command) {
         case "all":
             // Cleanup old sessions
             $db->execute("delete from zz_users_sessions where validTill < now()");
             $killsLastHour = $db->queryField("select count(*) count from zz_killmails where insertTime > date_sub(now(), interval 1 hour)", "count");
             Storage::store("KillsLastHour", $killsLastHour);
             $db->execute("delete from zz_analytics where dttm < date_sub(now(), interval 24 hour)");
             $fc = new FileCache("{$base}/cache/queryCache/");
             $fc->cleanUp();
             break;
         case "killsLastHour":
             $killsLastHour = $db->queryField("select count(*) count from zz_killmails where insertTime > date_sub(now(), interval 1 hour)", "count");
             Storage::store("KillsLastHour", $killsLastHour);
             break;
         case "fileCacheClean":
             $fc = new FileCache();
             $fc->cleanUp();
             break;
     }
 }
Example #4
0
function commentListGet()
{
    $cacheFile = new FileCache();
    $cacheFile->load('commentlist.json');
    if ($cacheFile->needUpdate()) {
        return commentListGenerate();
    } else {
        return json_decode($cacheFile->read());
    }
}
Example #5
0
 public function testExpire()
 {
     $key = uniqid();
     $c = new FileCache($this->file);
     $this->assertTrue($c->set($key, ['bar' => ['baz']], 1));
     $this->assertEquals(['bar' => ['baz']], $c->get($key));
     $this->assertTrue($c->expires($key) <= time() + 1);
     sleep(2);
     $this->assertNull($c->get($key));
 }
Example #6
0
 function handle()
 {
     $cache = new FileCache();
     $info = $cache->get(self::CACHE_KEY);
     if (!is_array($info)) {
         $shokos = new VolatileTwitShokos();
         $info = $shokos->bestTalkInfo();
         $cache->set(self::CACHE_KEY, $info, new DateTime("+30 min"));
     }
     $this->assign('rate', $info['rate']);
     $this->assign('text', $info['text']);
     $this->assign('status', 'ok');
 }
Example #7
0
 function run()
 {
     $cache = new FileCache();
     $box = $cache->get(self::TWITTER_CRAWL_KEY);
     if (!is_array($box)) {
         $box = array();
     }
     $api = new TwitterApi(HIDETOBARA_OAUTH_KEY, HIDETOBARA_OAUTH_SECRET);
     $a = $api->getHomeTimeline($box);
     $storage = new TwitterStorage();
     $storage->retrieveStatus($a);
     $storage->saveStatusByDate(LOG_DIR . "status/");
     $box = $storage->updateUserCache($box);
     $cache->set(self::TWITTER_CRAWL_KEY, $box);
 }
Example #8
0
 public function __construct()
 {
     $http = new swoole_http_server('127.0.0.1', '9999');
     $http->set(array('reactor_num' => 1, 'worker_num' => 2, 'backlog' => 128, 'max_request' => 500, 'heartbeat_idle_time' => 30, 'heartbeat_check_interval' => 10, 'dispatch_mode' => 3));
     $http->on('request', function ($request, $response) {
         $request->get = isset($request->get) ? $request->get : [];
         $request->post = isset($request->post) ? $request->post : [];
         $request->cookie = isset($request->cookie) ? $request->cookie : [];
         $request->files = isset($request->files) ? $request->files : [];
         $request->server = isset($request->server) ? $request->server : [];
         if ($request->server['request_uri'] == '/favicon.ico') {
             $response->end();
             return;
         }
         $cache_dir = \Config::get('cron::cache_dir') ?: 'runtime/cron';
         $pid = \FileCache::get('pid', $cache_dir);
         $work_ids = \FileCache::get('work_ids', $cache_dir);
         ob_start();
         require __DIR__ . "/View/console.php";
         $output = ob_get_contents();
         ob_end_clean();
         $response->status(200);
         $response->end($output);
         return;
     });
     $this->http = $http;
 }
Example #9
0
 public function execute($parameters, $db)
 {
     global $enableAnalyze;
     $actualKills = Storage::retrieve("ActualKillCount");
     $iteration = 0;
     while ($actualKills > 0) {
         $iteration++;
         $actualKills -= 1000000;
         if ($actualKills > 0 && Storage::retrieve("{$iteration}mAnnounced", null) == null) {
             Storage::store("{$iteration}mAnnounced", true);
             $message = "|g|Woohoo!|r| {$iteration} million kills surpassed!";
             Log::irc($message);
             Log::ircAdmin($message);
         }
     }
     $highKillID = $db->queryField("select max(killID) highKillID from zz_killmails", "highKillID");
     if ($highKillID > 2000000) {
         Storage::store("notRecentKillID", $highKillID - 2000000);
     }
     self::apiPercentage($db);
     $db->execute("delete from zz_api_log where requestTime < date_sub(now(), interval 2 hour)");
     //$db->execute("update zz_killmails set kill_json = '' where processed = 2 and killID < 0 and kill_json != ''");
     $db->execute("delete from zz_errors where date < date_sub(now(), interval 1 day)");
     $fileCache = new FileCache();
     $fileCache->cleanup();
     $tableQuery = $db->query("show tables");
     $tables = array();
     foreach ($tableQuery as $row) {
         foreach ($row as $column) {
             $tables[] = $column;
         }
     }
     if ($enableAnalyze) {
         $tableisgood = array("OK", "Table is already up to date", "The storage engine for the table doesn't support check");
         $count = 0;
         foreach ($tables as $table) {
             $count++;
             if (Util::isMaintenanceMode()) {
                 continue;
             }
             $result = $db->queryRow("analyze table {$table}");
             if (!in_array($result["Msg_text"], $tableisgood)) {
                 Log::ircAdmin("|r|Error analyzing table |g|{$table}|r|: " . $result["Msg_text"]);
             }
         }
     }
 }
Example #10
0
 /**
  * Ziskat instanci cache komponentu
  * @return FileCache
  */
 public static function getCache()
 {
     if (null === self::$cache) {
         self::$cache = new FileCache(_indexroot . 'data/tmp/cache');
         self::$cache->setVerifyBoundFiles(1 == _dev);
     }
     return self::$cache;
 }
Example #11
0
 public function __construct($name, $dir = false, $delimiter = '', $at_least = 0)
 {
     parent::__construct($name, $dir);
     if (!empty($delimiter)) {
         $this->delimiter = $delimiter;
     }
     $this->at_least = $at_least;
 }
 public static function GetInstance($exp_time = 3600, $path = 'cache/')
 {
     if (!isset(self::$instance)) {
         //doesn't exists the isntance
         self::$instance = new self($exp_time, $path);
         //goes to the constructor
     }
     return self::$instance;
 }
 static function clear()
 {
     if (extension_loaded("memcached")) {
         $memcache = self::memcacheInit();
         $memcache->flush();
     } else {
         FileCache::clear();
     }
 }
Example #14
0
 private static function getUnsortedTopData($manual)
 {
     $allowHidden = util_isModerator(PRIV_VIEW_HIDDEN);
     $data = FileCache::getTop($manual, $allowHidden);
     if (!$data) {
         $data = TopEntry::loadUnsortedTopData($manual);
         FileCache::putTop($data, $manual, $allowHidden);
     }
     return $data;
 }
 public function init()
 {
     $sqlDir = __ROOT__ . "app/sql/";
     $lock = \FileCache::isExist("sql.lock", $sqlDir);
     if ($lock) {
         $this->fileList = \FileCache::get("sql.lock", $sqlDir);
     }
     $this->ListSql($sqlDir);
     \FileCache::set("sql.lock", $this->fileList, $sqlDir);
 }
Example #16
0
 /**
  * Initializes the properties of the class.
  * @param string $path Folder where the logs will be stored.
  * @param string $nameSpace <b>Optional</b>. recommended for a quicker access to the cache.
  * @param int $expires <b>Optional</b>. expiration date of the cache, default is 1 day.
  */
 public function __construct($path, $nameSpace = '', $expires = 86400)
 {
     $this->path = $path;
     $this->expires = (int) date('Ymd', time() + $expires);
     if (!empty($nameSpace)) {
         $this->path = $path . '/.cch' . md5($nameSpace);
     }
     if (!empty(self::$fo)) {
         self::$fo = new File($this->path);
     }
 }
Example #17
0
File: mhd.php Project: janci/MHDv2
 /**
  * In destructor saving getting data to cache - file
  */
 public function __destruct()
 {
     if (!is_null($this->cache)) {
         $this->cache->stops = $this->stops;
         $this->cache->departures = $this->departures;
         $this->cache->spoje = $this->spoje;
         $this->cache->form_url = $this->form_url;
         $this->cache->categories = $this->categories;
         $this->cache->save();
     }
 }
Example #18
0
	/**
	 * 获取缓存类
	 * @param string $type
	 * @return FileCache | RedisCache
	 */
	public static function getCacher ($type = '', $model = '') {
		$type or $type = C('DEFAULT_CACHER');
		if (!in_array($type, array('redis', 'file', 'remote'))) {
			$type = 'redis';
		}
		//如果不是正式服务上,不是用redis缓存
		if (false == SuiShiPHPConfig::get('PUBLIC_SERVICE') && 'redis' == $type) {
			$type = 'file';
		}
		$cacheId = $type.$model;
		if (isset(self::$CACHER[$cacheId])) {
			return self::$CACHER[$cacheId];
		}

		switch ($type) {
			case 'file':
				if (!class_exists("FileCache")) {
					include_once SUISHI_PHP_PATH . '/Cache/FileCache.class.php';
				}
				$c = new FileCache(C('RUN_SHELL'));
				$c->setModel($model);
				$c->setPath(SuiShiPHPConfig::getFileCacheDir());
				self::$CACHER[$cacheId] = $c;
				break;
			case 'remote':
				if (!class_exists("FileCache")) {
					include_once SUISHI_PHP_PATH . '/Cache/RemoteCacher.class.php';
				}
				$c = new RemoteCacher(C('REMOTE_CACHE_HOST'), C('REMOTE_CACHE_PORT'), 'weixinapp');
				self::$CACHER[$cacheId] = $c;
				break;
			default:
				if (!class_exists("RedisCache")) {
					include_once SUISHI_PHP_PATH . '/Cache/RedisCache.class.php';
				}
				$c = new RedisCache(SuiShiPHPConfig::get('REDIS_HOST'), SuiShiPHPConfig::get('REDIS_PORT'));
				self::$CACHER[$cacheId] = $c;
				break;
		}
		return self::$CACHER[$cacheId];
	}
 public function init()
 {
     $sqlDir = __ROOT__ . "app/sql/";
     $lock = \FileCache::isExist("sql.lock", $sqlDir);
     if ($lock) {
         $this->fileList = \FileCache::get("sql.lock", $sqlDir);
     }
     $this->ListSql($sqlDir);
     //清除lock
     $clean = new SqlCleanCommand();
     $clean->init();
 }
 public function __construct($search_paths = array())
 {
     $this->paths = $search_paths;
     $this->modules = $this->getModules();
     if (FileCache::is_cached('modules_info', 180)) {
         // cache expire after 3 mins
         $this->modules_info = FileCache::fetch('modules_info', null, 180);
     } else {
         $this->modules_info = array();
         $this->getCNModulesInfo();
         FileCache::store('modules_info', $this->modules_info, 180);
     }
 }
Example #21
0
 public function blindClass()
 {
     opcache_reset();
     $loader = (require __ROOT__ . '/vendor/autoload.php');
     $loader->setUseIncludePath(true);
     $app = new \Group\App\App();
     $app->initSelf();
     $app->doBootstrap($loader);
     $app->registerServices();
     $app->singleton('container')->setAppPath(__ROOT__);
     $classMap = new Group\Common\ClassMap();
     $classes = $classMap->doSearch();
     \FileCache::set('services', $classes, $this->cacheDir);
     $this->addClass($classes, $this->server);
 }
Example #22
0
 /**
  * 检查输入的参数与命令
  *
  */
 protected function checkArgv()
 {
     $argv = $this->argv;
     if (!isset($argv[1])) {
         return;
     }
     $config = \Config::get("async::server");
     if (!isset($config[$argv[1]])) {
         return;
     }
     $log = isset($config[$argv[1]]['config']['log_file']) ? $config[$argv[1]]['config']['log_file'] : 'runtime/async/default.log';
     $log = explode("/", $log);
     \FileCache::set(array_pop($log), '', implode("/", $log) . "/");
     $server = new Server($config[$argv[1]], $argv[1]);
     die;
 }
Example #23
0
 public function get($key)
 {
     $full_path = "{$this->path}/{$key}";
     if (file_exists($full_path)) {
         $file = fopen($full_path, 'rb');
         flock($file, LOCK_SH);
         list($expiry_time, $data) = FileCache::parse(file_get_contents($full_path));
         fclose($file);
         if ($this->has_expired($expiry_time)) {
             return $this->refresh($key);
         } else {
             return $data;
         }
     } else {
         return $this->refresh($key);
     }
 }
Example #24
0
/**
 * Class autoloader
 *
 * Include classes automatically when they are instantiated.
 * @param string
 */
function __autoload($strClassName)
{
    $objCache = FileCache::getInstance('autoload');
    // Try to load the class name from the session cache
    if (!$GLOBALS['TL_CONFIG']['debugMode'] && isset($objCache->{$strClassName})) {
        if (@(include_once TL_ROOT . '/' . $objCache->{$strClassName})) {
            return;
            // The class could be loaded
        } else {
            unset($objCache->{$strClassName});
            // The class has been removed
        }
    }
    $strLibrary = TL_ROOT . '/system/libraries/' . $strClassName . '.php';
    // Check for libraries first
    if (file_exists($strLibrary)) {
        include_once $strLibrary;
        $objCache->{$strClassName} = 'system/libraries/' . $strClassName . '.php';
        return;
    }
    // Then check the modules folder
    foreach (scan(TL_ROOT . '/system/modules/') as $strFolder) {
        if (substr($strFolder, 0, 1) == '.') {
            continue;
        }
        $strModule = TL_ROOT . '/system/modules/' . $strFolder . '/' . $strClassName . '.php';
        if (file_exists($strModule)) {
            include_once $strModule;
            $objCache->{$strClassName} = 'system/modules/' . $strFolder . '/' . $strClassName . '.php';
            return;
        }
    }
    // HOOK: include Swift classes
    if (class_exists('Swift', false)) {
        Swift::autoload($strClassName);
        return;
    }
    // HOOK: include DOMPDF classes
    if (function_exists('DOMPDF_autoload')) {
        DOMPDF_autoload($strClassName);
        return;
    }
    trigger_error(sprintf('Could not load class %s', $strClassName), E_USER_ERROR);
}
Example #25
0
 function search()
 {
     $qtData = FileCache::get($this->keyword);
     if (!$qtData) {
         $url = $this->queryUrl . urlencode($this->keyword);
         $request_result = $this->request($url);
         $json = json_decode($request_result);
         $qtData = $json->data;
     }
     if (count($qtData) > 0) {
         FileCache::set($this->keyword, $qtData);
         foreach ($qtData as $key => $value) {
             $stock = new Stock($value);
             $this->result($key, $stock->getLink(), $stock->getTitle(), $stock->getSubTitle(), null);
         }
     } else {
         $this->lastPlaceholder();
     }
 }
Example #26
0
 function search()
 {
     $cacheData = FileCache::get('__cache__' . $this->keyword);
     if (!$cacheData) {
         $url = $this->queryUrl . urlencode($this->keyword);
         $request_result = $this->request($url);
         $json = json_decode($request_result);
         $searchData = $json->data;
         if (count($searchData) > 0) {
             FileCache::set('__cache__' . $this->keyword, $searchData, 24 * 60 * 60);
         }
     } else {
         $searchData = $cacheData;
     }
     if (count($searchData) > 0) {
         $codeArray = array();
         foreach ($searchData as $value) {
             $d = explode('~', $value);
             if (preg_match('/(\\..*)$/', $d[1], $re)) {
                 $d[1] = str_replace($re[1], "", $d[1]);
             }
             if ($d[0] == 'us') {
                 $d[1] = strtoupper($d[1]);
             }
             $dCode = $d[0] . $d[1];
             if ($d[0] == 'hk') {
                 $dCode = 'r_' . $dCode;
             }
             if ($d[0] == 'jj') {
                 $dCode = 's_' . $dCode;
             }
             array_push($codeArray, $dCode);
         }
         $qt = new StockQt();
         $qt->fetchQt(implode(',', $codeArray));
         foreach ($searchData as $key => $value) {
             $stock = new Stock($value, $qt);
             $this->result($key, $stock->getLink(), $stock->getTitle(), $stock->getSubTitle(), null);
         }
     } else {
         $this->lastPlaceholder();
     }
 }
Example #27
0
 protected static function createFileCache()
 {
     return new FileCache(FileCache::getApplicationPrivateCacheDir() . '/permissions', 30);
 }
Example #28
0
 private function tinifyDirectory($dir, $recursive, &$report)
 {
     if (!file_exists($dir)) {
         $this->logWarning($dir . ' does not exist', $report);
         return;
     }
     if ($recursive) {
         $Files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
     } else {
         $Files = new FilesystemIterator($dir);
     }
     $extensions = array("png", "jpg", "jpeg");
     $pictures = array();
     foreach ($Files as $fileinfo) {
         if ($fileinfo->isFile() && in_array(strtolower($fileinfo->getExtension()), $extensions)) {
             $pictures[] = $fileinfo;
         }
     }
     $dirFileCounter = 0;
     $dirGainSize = 0;
     // Sort by size
     usort($pictures, function ($a, $b) {
         if ($a->getSize() == $b->getSize()) {
             return 0;
         }
         return $a->getSize() > $b->getSize() ? -1 : 1;
     });
     foreach ($pictures as $fileinfo) {
         $object = new FileCache($fileinfo);
         if ($object->needTinify()) {
             set_time_limit(10);
             $filename = $object->getPathname();
             $fileSize = $object->getSize();
             $object->tinify();
             $newFileSize = $object->getSize();
             $gainSize = $fileSize - $newFileSize;
             $dirFileCounter++;
             $dirGainSize += $gainSize;
             $report->update($gainSize);
             if (isset($this->logger)) {
                 $this->logger->logInfo('[' . $filename . '] ' . $fileSize . '=>' . $newFileSize . ' (' . (100 - (int) ($newFileSize * 100 / $fileSize)) . '%)');
             }
         }
     }
     if (isset($this->logger)) {
         $this->logger->logInfo('[' . $dir . ']: ' . $dirFileCounter . ' files(s), gain: ' . (int) ($dirGainSize / 1024) . 'Ko');
     }
 }
Example #29
0
/**
 * Refresh the Instagram cache
 */
function ikit_social_remote_fetch_instagram_feed()
{
    global $g_options;
    $instagram_user_id = null;
    if (isset($g_options[IKIT_PLUGIN_OPTION_INSTAGRAM_USER_ID])) {
        $instagram_user_id = $g_options[IKIT_PLUGIN_OPTION_INSTAGRAM_USER_ID];
    }
    if ($instagram_user_id != null) {
        $curl_list_request = curl_init();
        // Fetch recent media for specified user
        curl_setopt($curl_list_request, CURLOPT_URL, IKIT_SOCIAL_INSTAGRAM_API_URL . "/users/" . $instagram_user_id . '/media/recent?access_token=' . IKIT_SOCIAL_INSTAGRAM_ACCESS_TOKEN);
        curl_setopt($curl_list_request, CURLOPT_RETURNTRANSFER, true);
        $curl_list_response = curl_exec($curl_list_request);
        curl_close($curl_list_request);
        $cache = FileCache::GetInstance(IKIT_SOCIAL_INSTAGRAM_FEED_CACHE_SECS, IKIT_DIR_FILE_CACHE);
        $cache->delete(IKIT_SOCIAL_INSTAGRAM_FEED_CACHE_KEY);
        // Deletes if older than the expiry time
        $cache->cache(IKIT_SOCIAL_INSTAGRAM_FEED_CACHE_KEY, json_decode($curl_list_response));
    }
}
Example #30
0
 public static function getWordCountLastMonth()
 {
     $cachedWordCountLastMonth = FileCache::getWordCountLastMonth();
     if ($cachedWordCountLastMonth) {
         return $cachedWordCountLastMonth;
     }
     $last_month = time() - 30 * 86400;
     $result = Model::factory('Definition')->where('status', self::ST_ACTIVE)->where_gte('createDate', $last_month)->count();
     FileCache::putWordCountLastMonth($result);
     return $result;
 }