Exemplo n.º 1
0
 /**
  * Helper function to retrieve data with cURL.
  *
  * @param $url
  * @return string
  */
 public static function GetData($url)
 {
     if (empty($url)) {
         exit("Link given was empty. Check your configuration.");
     }
     $cache = new Cacher();
     $data = $cache->LoadData($url);
     if (!empty($data)) {
         return $data;
     }
     if (!function_exists("curl_init")) {
         exit("You don't appear to have cURL installed or configured.");
     }
     $CH = curl_init();
     curl_setopt($CH, CURLOPT_URL, $url);
     curl_setopt($CH, CURLOPT_ENCODING, 'gzip, deflate');
     curl_setopt($CH, CURLOPT_USERAGENT, USER_AGENT);
     curl_setopt($CH, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($CH, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($CH, CURLOPT_RETURNTRANSFER, true);
     $data = curl_exec($CH);
     curl_close($CH);
     if (empty($data)) {
         exit("Data downloaded was empty!");
     }
     $cache->SaveData($data, $url);
     return $data;
 }
Exemplo n.º 2
0
 public function set($key = '', $value = '', $duration = 0)
 {
     if ($this->aliasToRedis) {
         $myCacher = new Cacher($key, Cacher::STORAGE_REDIS);
         return $myCacher->set($value, $duration);
     } else {
         return false;
     }
 }
Exemplo n.º 3
0
Arquivo: Cache.php Projeto: jasny/Q
 /**
  * Remove old/all data from cache.
  * 
  * @param int $opt  Cache::% options
  */
 public function clean($opt = 0)
 {
     $this->doClean($opt);
     if (isset($this->chainNext) && ~$opt & self::NOCASCADE) {
         $this->chainNext->clean($opt);
     }
 }
Exemplo n.º 4
0
 /**
  * Returns an instance of Cacher object
  * @return Cacher
  */
 public static function getInstance()
 {
     if (self::$instance === null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Exemplo n.º 5
0
 public static function get()
 {
     /*{{{*/
     if (false == self::$ins instanceof self) {
         self::$ins = new self();
     }
     return self::$ins;
 }
Exemplo n.º 6
0
 function removeAll()
 {
     $c = new Criteria();
     $this->del($c);
     $this->site->update(array("referrerTimes" => 0), $c);
     $todayDate = date("Y-m-d");
     $this->setting->set('topReferrersLastResetDate', $todayDate);
     Cacher::getInstance()->clean("tag", array("setting"));
 }
Exemplo n.º 7
0
 function getDirectoryCondition()
 {
     $cache = Cacher::getInstance();
     if (($message = $cache->load("directoryCondition")) === null) {
         $message = $this->customMessage->findByPk("directoryCondition")->toArray();
         $cache->save($message, null, null, array("custommessage"));
     }
     return $message;
 }
Exemplo n.º 8
0
 public function getArticles()
 {
     if (Input::has('firstArticleID')) {
         $latest = Cacher::get(LATEST_ARTICLE_ID_KEY);
         if (Input::get('firstArticleID') >= $latest) {
             return $this->jsonResponse(array());
         }
     }
     $articleList = new ArticleList();
     $articleList->load();
     return $this->jsonResponse($articleList->data);
 }
Exemplo n.º 9
0
 public static function create($token, $width, $height)
 {
     /*{{{*/
     $self = new CaptchaSketchpad();
     $cacher = Cacher::get()->getCache(Cacher::CACHETYPE_CAPTCHA);
     $originalValues = $cacher->get($token);
     $self->displayStr = $originalValues['question'];
     $self->width = $width;
     $self->height = $height;
     $self->img = imagecreate($width, $height);
     imagecolorallocate($self->img, 238, 238, 238);
     return $self;
 }
Exemplo n.º 10
0
 /**
  * Index page
  */
 function indexAction()
 {
     //set adPage
     Display::set("adPage", "index");
     //set META description
     $this->set("metaDescription", Config::get("siteDescription"));
     $cache = Cacher::getInstance();
     //retrieve predefinied html directoryDescription from db
     if (($message = $cache->load("directoryDescription")) === null) {
         $message = $this->customMessage->findByPk("directoryDescription")->toArray();
         $cache->save($message, null, null, array("custommessage"));
     }
     $this->set("directoryDescription", $message);
 }
Exemplo n.º 11
0
 public static function generateByDefaultKey($app, $captchaType, $charCnt, $clientIp, $effactiveTime)
 {
     /*{{{*/
     DBC::requireTrue($effactiveTime < 60, "有效时间不能超过1小时");
     $contentObj = ContentFactory::generate($captchaType);
     $contentArr = $contentObj->generate($charCnt);
     $handler = new QBase64();
     $key = self::generateID();
     $token = $handler->crypt(microtime() . $app . $key);
     $expireTime = XDateTime::now()->addMinute($effactiveTime)->getTime();
     $originalValues = array('app' => $app, 'key' => $key, 'ip' => $clientIp, 'expiretime' => $expireTime, 'answer' => strtolower($contentArr['answer']), 'question' => $contentArr['question']);
     $cacher = Cacher::get()->getCache(Cacher::CACHETYPE_CAPTCHA);
     $cacher->add($token, $originalValues);
     return array('token' => $token, 'captchaId' => $key);
 }
Exemplo n.º 12
0
 public function __construct()
 {/*{{{*/
     $this->maxConnectTime = 80;//ms
     DAL::get()->setUp('ops');
     foreach (Cacher::getCacheTypes() as $type)
     {
         $cacher = DAL::get()->getCache($type);
         $sets = $cacher->getStats();
         $sets = array_keys($sets);
         foreach ($sets as $set)
         {
             $arr = explode(':', $set);
             $this->hosts[] = array('host' => $arr[0], 'port' => $arr[1]);
         }
     }
 }/*}}}*/
Exemplo n.º 13
0
 function listAction()
 {
     //get category to display set by /site/category
     $parentCategoryId = Display::get("currentCategoryId", 0);
     $cache = Cacher::getInstance();
     $cacheItemName = "categoryMiddleHtml" . $parentCategoryId . Config::get("language") . "Template" . Config::get("templateName");
     //check that cached version exists
     if (($categoriesMiddleHtml = $cache->load($cacheItemName, false)) === null) {
         //retrieve all categories which have this $parentCategoryId alphabetically
         $c = new Criteria();
         $c->addOrder("position, name");
         $c->add("parentCategoryId", $parentCategoryId);
         //create assoctiation array with keys = categoryId and values category data
         $categoriesList = $this->category->getArray($c, "parentCategoryId, name, urlName, imageSrc, validatedSitesCount", null, true);
         //if exists some categories having this parent
         if (!empty($categoriesList)) {
             //get count of category subcategories
             $maxSubcategoriesCount = Config::get("countOfSubcategoriesUnderCategory");
             if ($maxSubcategoriesCount) {
                 //retrieve subcategories which have categories on this page
                 $c = new Criteria();
                 $c->addOrder("position, name");
                 $c->add("parentCategoryId", array_keys($categoriesList), "IN");
                 $subcategories = $this->category->findAll($c);
                 //foreach category create subcategories container
                 foreach ($categoriesList as $key => $category) {
                     $categoriesList[$key]['subcategories'] = array();
                 }
                 //foreach subcategories add it to parent category
                 foreach ($subcategories as $subcategory) {
                     $parentCategory =& $categoriesList[$subcategory['parentCategoryId']];
                     //check that $maxSubcategoriesCount isn't reached
                     if (count($parentCategory['subcategories']) < $maxSubcategoriesCount) {
                         $parentCategory['subcategories'][] = $subcategory;
                     }
                 }
             }
             //create standard array to be able create 2 columns table (much be indexed i, i+1)
             $categoriesList = array_values($categoriesList);
         }
         $this->set("categoriesList", $categoriesList);
         $categoriesMiddleHtml = $this->render();
         //store categories with subcategories on this page to cache
         $cache->save($categoriesMiddleHtml, $cacheItemName, false, array("category", "site"));
     }
     return $categoriesMiddleHtml;
 }
Exemplo n.º 14
0
 /**
  * Retrieve main settings for application
  * @return array
  */
 public function loadSettings()
 {
     $cache = Cacher::getInstance();
     if (($settings = $cache->load("settings")) === null) {
         $settings = array();
         foreach ($this->setting->findAll(new Criteria(), "`key`, `value`") as $row) {
             $settings[$row['key']] = $row['value'];
         }
         $cache->save($settings, null, null, array("setting"));
     }
     foreach ($settings as $key => $value) {
         Config::set($key, $value);
     }
     $rawUrl = parse_url(Config::get("siteRootUrl"));
     Config::set("siteDomainUrl", "http://" . $rawUrl['host']);
     $errorHandler = ErrorHandler::getInstance();
     if (!Config::get('errorHandlerSaveToFileEnabled')) {
         $errorHandler->setOption('saveToFile', false);
     }
     if (!Config::get('errorHandlerDisplayErrorEnabled')) {
         $errorHandler->setOption('displayError', false);
     }
 }
Exemplo n.º 15
0
 function updateAction()
 {
     $this->setting->set("templateName", $this->request->templateName);
     Cacher::getInstance()->clean("tag", array("setting"));
     $this->redirect($this->moduleLink());
 }
Exemplo n.º 16
0
 private function saveToCache()
 {
     Cacher::set(FEED_CACHE_KEY, $this->data, FEED_EXPIRE_TIME);
 }
Exemplo n.º 17
0
 /**
  * Construct a Wikimedia instance.
  * @param Database $db The database with which to connect to the database.
  * @param Cacher $cache The cache with which to read and write cached data.
  */
 public function __construct($db, $cache)
 {
     $this->wikis = $cache->Get('wikimedia-wikis');
     if (!$this->wikis) {
         // build wiki list
         $this->wikis = array();
         $db->Connect('metawiki.labsdb', 'metawiki_p');
         foreach ($db->Query('SELECT dbname, lang, family, url, size, is_closed, slice FROM meta_p.wiki WHERE url IS NOT NULL')->fetchAllAssoc() as $row) {
             if ($row['dbname'] == 'votewiki') {
                 continue;
             }
             // DB schema is broken
             $this->wikis[$row['dbname']] = new Wiki($row['dbname'], $row['lang'], $row['family'], $row['url'], $row['size'], $row['is_closed'], $row['slice']);
         }
         // cache result
         if (count($this->wikis)) {
             // if the fetch failed, we *don't* want to cache the result for a full day
             $cache->Save('wikimedia-wikis', $this->wikis);
         }
         $db->ConnectPrevious();
     }
 }
Exemplo n.º 18
0
 /**
  * Save new criterion
  */
 function saveNewCriteriaAction()
 {
     $adcriteria = new AdCriteriaRecord();
     $adcriteria->name = $this->request->name;
     $adcriteria->htmlContent = $this->request->htmlContent;
     $adcriteria->save();
     Cacher::getInstance()->clean("tag", array("adCriteria"));
     $this->redirect($this->moduleLink());
 }
Exemplo n.º 19
0
 public function start()
 {
     $scriptStartTime = time();
     ignore_user_abort(true);
     set_time_limit(60 * 5);
     $taskCriteria = new Criteria();
     $taskCriteria->add("taskId", $this->taskId);
     $task = $this->task->find($taskCriteria);
     if (empty($task)) {
         return;
     }
     if (!in_array($task->status, array("init", "next"))) {
         return;
     }
     $this->data = unserialize($task->data);
     if ($task->status == "next") {
         $taskData = Cacher::getInstance()->load("taskData" . $this->taskId);
         if (empty($taskData)) {
             return;
         }
         $this->items = $taskData['items'];
         $startIndex = $taskData['startIndex'];
         $this->parsedItems = $startIndex;
     } else {
         $startIndex = 0;
         $this->loadItems();
     }
     $this->totalItems = count($this->items);
     $task->totalItems = $this->totalItems;
     $task->status = "active";
     $task->save();
     $lp = 0;
     $this->beforeParsing();
     $executeNextProcess = false;
     for ($i = $startIndex, $itemsCount = count($this->items); $i < $itemsCount && !$executeNextProcess; $i++) {
         $item = $this->items[$i];
         $this->parseItem($item);
         $task->parsedItems = ++$this->parsedItems;
         $task->save();
         if ($this->parsedItems < $this->totalItems) {
             $taskStatus = $this->task->get("status", $taskCriteria);
             if ($taskStatus == "pause") {
                 do {
                     sleep($this->pauseUpdateStatusInterval);
                     $taskStatus = $this->task->get("status", $taskCriteria);
                 } while ($taskStatus == "pause");
             }
             if ($taskStatus == "stop") {
                 break;
             }
             if (time() - $scriptStartTime > $this->scriptMaxExecutionTime) {
                 $executeNextProcess = true;
                 $taskData = array("items" => $this->items, "startIndex" => $i + 1);
                 Cacher::getInstance()->save($taskData, "taskData" . $this->taskId);
             }
         }
     }
     if ($executeNextProcess) {
         $task->status = "next";
         $task->save();
         $this->fork(AppRouter::getRewrittedUrl("/admin/task/nextStart"));
     } else {
         Cacher::getInstance()->delete("taskData" . $this->taskId);
         $task->status = "finish";
         $task->save();
         $this->afterParsing();
     }
 }
Exemplo n.º 20
0
 public function getCache($type)
 {
     return Cacher::get()->getCache($type);
 }
Exemplo n.º 21
0
 function update($data, Criteria $c)
 {
     parent::update($data, $c);
     Cacher::getInstance()->clean("tag", array("user"));
 }
 public function domobileBindUser($request, $response)
 {/*{{{*/
     if (Captcha::verify($request->key, XIpLocation::getIp(), 'password', $request->mobile, $request->token))
     {
         $newToken = Captcha::generate('password', $request->mobile, ContentFactory::TYPE_NUM, 4, XIpLocation::getIp(), 10);
         $cacher = Cacher::get()->getCache(Cacher::CACHETYPE_CAPTCHA);
         $captchaInfos = $cacher->get($newToken);
         $newKey = strtolower($captchaInfos['question']);
         $bindRes = WeixClient::getInstance()->bindUser($this->weixSpaceUser->id,$request->spaceId, WeixUser::WEIXINTYPE_SPACE); 
         if($bindRes == true )
         {
             $user = UserClient::getInstance()->login4Weix($request->spaceId);
             $res = "success";
             $forward = (empty($forward)) ? $response->router->urlfor('weixindoctor/bindsuccess') : $forward;
         }
         else
         {
             $res = "hasbind";  //该用户已绑定
         }
         $results = array('res' => $res, 'msg' => '');
     }
     else
     {
         $results = array('res' => 'failure', 'msg' => mb_convert_encoding('验证码输入有误', 'UTF-8', 'GBK'), 'next' => '');
     }
     echo json_encode($results);
     return self::DIRECT_OUTPUT;
 }/*}}}*/
Exemplo n.º 23
0
for ($i = 0; $i < $usercount; $i++) {
    //$id = mt_rand(1,1000);
    $id = $usercount - $i;
    $users[$id] = new User($id);
}
function GetFromAnyExternal($arr, $users)
{
    $r = array();
    foreach ($arr as $key) {
        $r[$key] = array('_id' => $users[$key]->id, date('h:i:s A'));
    }
    return $r;
}
$toFill = array();
$keys = array_keys($users);
$slots = Cacher::create('Test', $keys);
$CacheData = array();
//echo "<hr><pre>";var_export($slots);echo '</pre><hr>'; exit;
foreach ($slots as $key => $slot) {
    if (!($CacheData[$key] = $slot->get())) {
        $toFill[] = $key;
    }
}
$rez = GetFromAnyExternal($toFill, $users);
foreach ($toFill as $key) {
    //$slot->addTag(Cacher_Tag::create('SmplTag',  $User)); // Создаем и сразуже добавляем новый тег к слоту перед сохрананеием в кеш
    //$slot->addTag(Cacher_Tag::create('SmplTag1', $User)); // Создаем и сразуже добавляем новый тег к слоту перед сохрананеием в кеш
    //echo "<hr>setTag: ", Cacher_Tag::create('SmplTag', $key)->getKey();
    //$slots[$key]->addTag( Cacher_Tag::create('SmplTag', $key) );
    //sleep(1);// hard data
    $val = $rez[$key];
Exemplo n.º 24
0
 public function saveCampaignFilters($filters)
 {
     $this->setting->set('campaignFilters', serialize($filters));
     Cacher::getInstance()->clean('all');
 }
Exemplo n.º 25
0
 /**
  * Uses the cache, if available.
  *
  * @static
  * @access public
  * @param ICacheable $obj the object we're operating on
  * @return string the cached data if available, false otherwise
  */
 public static function useCache(ICacheable &$obj)
 {
     return false;
     if (!($cacheModifiedTime = Cacher::isCached($obj))) {
         return false;
     }
     if (!$obj->useCache($cacheModifiedTime)) {
         return false;
     }
     $path = Cacher::getCacheDirectory($obj) . '/cache';
     if (!($buffer = file_get_contents($path))) {
         return false;
     }
     Site::getLog()->info("using cache for {$path}");
     return $buffer;
 }
Exemplo n.º 26
0
function replaceImgURL($content)
{
    return str_replace('static.cnbetacdn.com', 'cnbeta1.sinaapp.com', $content);
}
# App shutdown
App::shutdown(function () {
    Cacher::close();
});
# Constants
const ARTICLE_CACHE_TIME = 1814400;
// 3600 * 24 * 21, 21 days
const ARTICLE_REFRESH_TIME = 300;
// 5min
const ARTICLE_RECENT_DAY = 2;
// article in 1 day is 'recent'
# For cache keys
const ARTICLE_CACHE_KEY_PREFIX = 'A:';
const UPTODATE_KEY_PREFIX = 'U:';
const LATEST_ARTICLE_ID_KEY = 'LatestArticle';
const INDEX_CACHE_KEY = 'IndexData';
const FEED_CACHE_KEY = 'FeedData';
# Index Page
const INDEX_ARTICLE_NUM = 20;
const INDEX_EXPIRE_TIME = 180;
// 3min
# Feed
const FEED_EXPIRE_TIME = 86400;
// 1 day
# Init Cache Engine
Cacher::setCacher(new RedisCacher());
Exemplo n.º 27
0
 function updateStats()
 {
     $this->category->updateValidatedSitesCount();
     Cacher::getInstance()->clean("tag", array("site", "category", "keyword"));
 }
Exemplo n.º 28
0
 public function doFindPwdVerifyKey($request, $response) {/*{{{*/
     if (Captcha::verify($request->key, XIpLocation::getIp(), 'password', $request->mobile, $request->token))
     {
         $newToken = Captcha::generate('password', $request->mobile, ContentFactory::TYPE_NUM, 4, XIpLocation::getIp(), 10);
         $cacher = Cacher::get()->getCache(Cacher::CACHETYPE_CAPTCHA);
         $captchaInfos = $cacher->get($newToken);
         $newKey = strtolower($captchaInfos['question']);
         if(stripos($request->forward, 'weixUserId') === 0)
         {
             $nextUrl = $response->router->urlfor('weixin/afterfinduserpwd').'?'.$request->forward;
             $results = array('res' => 'success', 'msg' => '', 'next' => $nextUrl, 'forward' => $request->forward);
         }
         else
         {
             $results = array('res' => 'success', 'msg' => '', 'next' => $response->router->urlfor('user/findpwd', array('userId' => $request->userId, 'mobile' => $request->mobile,'key' => $newKey, 'token' => $newToken, 'forward' => $request->forward)));
         }
     }
     else
     {
         $results = array('res' => 'failure', 'msg' => mb_convert_encoding('验证码输入有误', 'UTF-8', 'GBK'), 'next' => '');
     }
     echo json_encode($results);
     return self::DIRECT_OUTPUT;
 }/*}}}*/
Exemplo n.º 29
0
 public static function setCacher($cacher)
 {
     Cacher::$cacher = $cacher;
 }
Exemplo n.º 30
0
 function displayTagCloudAction()
 {
     //check is tag cloud was cached before
     $cache = Cacher::getInstance();
     $cacheItemName = "tagCloudHtml" . Config::get("language") . "Template" . Config::get("templateName");
     if (($tagCloudHtml = $cache->load($cacheItemName, false)) === null) {
         //get stats defined in statistic model
         $this->set("tags", $this->searchTag->getTagCloud());
         $this->viewFile = "menuright/tagCloud";
         $tagCloudHtml = $this->render();
         $cache->save($tagCloudHtml, $cacheItemName, false, array("searchTag"));
     }
     return $tagCloudHtml;
 }