get() 공개 메소드

public get ( $key, $expires = null )
예제 #1
0
파일: auth.php 프로젝트: odilitime/infinity
function create_pm_header()
{
    global $mod, $config;
    if ($config['cache']['enabled'] && ($header = cache::get('pm_unread_' . $mod['id'])) != false) {
        if ($header === true) {
            return false;
        }
        return $header;
    }
    $query = prepare("SELECT `id` FROM ``pms`` WHERE `to` = :id AND `unread` = 1");
    $query->bindValue(':id', $mod['id'], PDO::PARAM_INT);
    $query->execute() or error(db_error($query));
    if ($pm = $query->fetch(PDO::FETCH_ASSOC)) {
        $header = array('id' => $pm['id'], 'waiting' => $query->rowCount() - 1);
    } else {
        $header = true;
    }
    if ($config['cache']['enabled']) {
        cache::set('pm_unread_' . $mod['id'], $header);
    }
    if ($header === true) {
        return false;
    }
    return $header;
}
예제 #2
0
function get_id64($player_id)
{
    global $db, $settings;
    if (!is_id64($player_id)) {
        $url = sprintf("http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s", $settings['api_key'], $player_id);
    } else {
        return $player_id;
    }
    // Try the easy way
    $i = $db->query_first("SELECT id64 FROM tf2_players WHERE custom_url = %s", array($player_id));
    if ($i['id64']) {
        return $i['id64'];
    }
    require_once 'classes/cache.php';
    $json_string = cache::get($url);
    try {
        $rgResult = json_decode($json_string, true);
        $rgResponse = $rgResult['response'];
    } catch (Exception $e) {
        // Bad XML data. Purge and throw an error
        cache::purge($url);
        $bad_xml = true;
        return false;
        //echo "BAD XML!!!: ".$url;
    }
    if ($rgResponse['success'] == k_EResultOK) {
        $id64 = $rgResponse['steamid'];
        // Update this in the db
        $db->query("UPDATE tf2_players SET custom_url=%s WHERE id64=%s", array($player_id, $id64));
    }
    return $id64;
}
예제 #3
0
 function hitfailcacheitem()
 {
     try {
         $r = cache::get('bar');
     } catch (CacheException $e) {
     }
 }
예제 #4
0
 function preload_stats($multi = false)
 {
     global $settings;
     $url = sprintf('http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=440&key=%s&steamid=%s', $settings['api_key'], $this->id64);
     $stats_json = cache::get($url, false, $multi);
     if ($stats_json) {
         $this->multi_stats($stats_json);
     } else {
         cache::register_multi_url($url, array($this, 'multi_stats'));
     }
 }
예제 #5
0
파일: reg.php 프로젝트: sunfun/Bagira.CMS
 private static function init()
 {
     if (self::$keys == '') {
         if (!(self::$keys = cache::get('global-settings'))) {
             $sql = 'SELECT SQL_CACHE r_id id, r_section_id section, r_key name, r_value value, r_description description FROM <<register>>;';
             self::$keys = db::q($sql, records);
             if (db::issetError()) {
                 die;
             }
             // Записываем в кэш
             cache::set('global-settings', self::$keys);
         }
     }
 }
예제 #6
0
 public function useResultCache($timeout = 30, $params = null)
 {
     $cachekey = 'TinyORM-' . md5($this->sql);
     if ($params) {
         $cachekey .= md5(serialize($params));
     }
     $cached = cache::get($cachekey);
     if ($cached === false) {
         $query = $this->connection->prepare($this->sql);
         $query->execute($params);
         $cached = $query->fetchAll();
         cache::set($cachekey, $cached, $timeout);
     }
     return $cached;
 }
예제 #7
0
 private function _accessToken()
 {
     require_once 'class.cacheFile.php';
     $cache = new cache();
     $access_token = $cache->get('access_token');
     if ($access_token === NULL) {
         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . AppSecrect;
         $status = $this->_httpRequest($url);
         $status = json_decode($status, true);
         //将对象转为数组
         $access_token = $status['access_token'];
         $cache->set('access_token', $access_token, 7200);
     }
     return $access_token;
 }
예제 #8
0
파일: group.class.php 프로젝트: nanfs/lt
 public function get_group_list()
 {
     global $_M;
     if (!$this->grouplist[$this->lang]) {
         $this->grouplist[$this->lang] = cache::get("user/grouplist_{$this->lang}");
         if (!$this->grouplist[$this->lang]) {
             $query = "SELECT * FROM {$_M['table']['user_group']} WHERE lang='{$this->lang}' order by access ASC";
             $result = DB::query($query);
             while ($list = DB::fetch_array($result)) {
                 $this->grouplist[$this->lang][$list['id']] = $list;
             }
             cache::put("user/grouplist_{$this->lang}", $this->grouplist[$this->lang]);
         }
     }
     return $this->grouplist[$this->lang];
 }
예제 #9
0
    /**
     * Initializing i18n
     *
     * @param array $options
     */
    public static function init($options = [])
    {
        do {
            self::$language_code = $options['language_code'];
            $where = " AND lc_translation_language_code = '{$options['language_code']}'";
            // retrive data from cache
            $cache_id_file = $cache_id = 'numbers_backend_i18n_basic_base_' . $options['language_code'];
            // if we are including js translations
            if (strpos($_SERVER['REQUEST_URI'] ?? '', $cache_id_file . '.js') !== false) {
                $where .= " AND lc_translation_javascript = 1";
                $cache_id .= '_js';
            }
            $cache = new cache();
            $data = $cache->get($cache_id);
            if ($data !== false) {
                self::$data = !empty($data) ? $data : ['ids' => [], 'hashes' => []];
                break;
            }
            // load data from database
            $sql = <<<TTT
\t\t\t\tSELECT
\t\t\t\t\tlc_translation_id id,
\t\t\t\t\tlc_translation_text_sys sys,
\t\t\t\t\tlc_translation_text_new new
\t\t\t\tFROM lc_translations
\t\t\t\tWHERE 1=1
\t\t\t\t\t{$where}
TTT;
            $query_result = factory::model('numbers_backend_i18n_basic_model_translations')->db_object->query($sql);
            foreach ($query_result['rows'] as $k => $v) {
                if (strlen($v['sys']) > 40) {
                    $v['sys'] = sha1($v['sys']);
                }
                self::$data['hashes'][$v['sys']] = $v['new'];
                self::$data['ids'][$v['id']] = $v['sys'];
            }
            // set the cache
            $cache->set($cache_id, self::$data, ['translations']);
        } while (0);
        // load js
        numbers_frontend_media_libraries_jssha_base::add();
        layout::add_js('/numbers/media_submodules/numbers_backend_i18n_basic_media_js_i18n.js', 5001);
        layout::add_js('/numbers/backend/i18n/basic/controller/javascript/_js/' . $cache_id_file . '.js', 50000);
        // load data into cache
        return ['success' => 1, 'error' => []];
    }
예제 #10
0
function tweets($username, $params = array())
{
    $defaults = array('limit' => 10, 'cache' => true, 'refresh' => 60 * 20);
    // add the username to the defaults array
    $defaults['username'] = $username;
    $options = array_merge($defaults, $params);
    // check the cache dir
    $cacheDir = c::get('root.cache') . '/tweets';
    dir::make($cacheDir);
    // disable the cache if adding the cache dir failed
    if (!is_dir($cacheDir) || !is_writable($cacheDir)) {
        $options['cache'] = false;
    }
    // sanitize the limit
    if ($options['limit'] > 200) {
        $options['limit'] = 200;
    }
    // generate a unique cache ID
    $cacheID = 'tweets/tweets.' . md5($options['username']) . '.' . $options['limit'] . '.php';
    if ($options['cache']) {
        $cache = cache::modified($cacheID) < time() - $options['refresh'] ? false : cache::get($cacheID);
    } else {
        $cache = false;
    }
    if (!empty($cache)) {
        return $cache;
    }
    $url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' . $options['username'] . '&count=' . $options['limit'];
    $json = @file_get_contents($url);
    $data = str::parse($json);
    if (!$data) {
        return false;
    }
    $result = array();
    foreach ($data as $tweet) {
        $user = $tweet['user'];
        $result[] = new tweet(array('url' => 'http://twitter.com/' . $options['username'] . '/status/' . $tweet['id_str'], 'text' => $tweet['text'], 'date' => strtotime($tweet['created_at']), 'source' => $tweet['source'], 'user' => new obj(array('name' => $user['name'], 'bio' => $user['description'], 'username' => $user['screen_name'], 'url' => 'http://twitter.com/' . $user['screen_name'], 'image' => 'http://twitter.com/api/users/profile_image/' . $user['screen_name'], 'following' => $user['friends_count'], 'followers' => $user['followers_count']))));
    }
    $result = new obj($result);
    if ($options['cache']) {
        cache::set($cacheID, $result);
    }
    return $result;
}
예제 #11
0
파일: user.php 프로젝트: sunfun/Bagira.CMS
 static function init()
 {
     if (isset($_SESSION['curUser']['name']) && $_SESSION['curUser']['name'] != 'none') {
         self::$isGuest = false;
         self::$isAdmin = $_SESSION['curUser']['isAdmin'];
         $key = 'user' . $_SESSION['curUser']['id'];
         if (!(self::$obj = cache::get($key))) {
             self::$obj = ormObjects::get($_SESSION['curUser']['id']);
             // Записываем в кэш
             cache::set($key, self::$obj);
         }
         /*
                     self::$obj->last_visit = date('Y-m-d H:i:s');
                     self::$obj->last_ip = $_SERVER['REMOTE_ADDR'];
         
                     self::$obj->save();    */
         //проверяем наличие кукисов если есть авторизуем
     } else {
         if (isset($_COOKIE['remember_me']) && $_COOKIE['remember_me'] != '') {
             //разбиваем строку по параметрам: 0 - id, 1 - browser hash, 2 - random hash
             $params = explode('-', $_COOKIE["remember_me"]);
             $user = ormObjects::get($params[0], 'user');
             $confirmIP = strpos($user->last_ip, self::getIP(2)) === false;
             if (!$confirmIP && $params[1] == self::browserHash() && $params[2] == $user->remember_me) {
                 self::$obj = $user;
                 self::getRights();
                 self::$isAdmin = count(self::$right) == 0 ? false : true;
                 self::$isGuest = false;
                 self::updateSession($user->id, $user->login, $user->name, $user->email);
                 self::$obj->last_visit = date('Y-m-d H:i:s');
                 self::$obj->last_ip = self::getIP();
                 self::$obj->error_passw = 0;
                 self::$obj->save();
                 system::log(lang::get('ENTER_USER_WITH_COOKIE'), info);
             }
         }
     }
     if (!isset($_SESSION['curUser']['name'])) {
         self::guestCreate();
     }
 }
예제 #12
0
 /**
  * Get information
  *
  * @param string $ip
  * @return array
  */
 public function get($ip)
 {
     $ip = $ip . '';
     // try to get IP information from cache
     $cache = new cache('db');
     $cache_id = 'misc_ip_ipinfo_' . $ip;
     $data = $cache->get($cache_id);
     if ($data !== false) {
         return ['success' => true, 'error' => [], 'data' => $data];
     }
     // if we need to query ipinfo.io
     $json = file_get_contents("http://ipinfo.io/{$ip}/json");
     $data = json_decode($json, true);
     if (isset($data['country'])) {
         $temp = explode(',', $data['loc']);
         $save = ['ip' => $ip, 'date' => format::now('date'), 'country' => $data['country'], 'region' => $data['region'], 'city' => $data['city'], 'postal' => $data['postal'], 'lat' => format::read_floatval($temp[0]), 'lon' => format::read_floatval($temp[1])];
         $cache->set($cache_id, $save, ['misc_ip_ipinfo'], 604800);
         return ['success' => true, 'error' => [], 'data' => $save];
     } else {
         return ['success' => false, 'error' => ['Could not decode IP address!'], 'data' => ['ip' => $ip]];
     }
 }
예제 #13
0
파일: pages.php 프로젝트: ringtech/infinity
function mod_dashboard()
{
    global $config, $mod;
    $args = array();
    $args['boards'] = listBoards();
    if (hasPermission($config['mod']['noticeboard'])) {
        if (!$config['cache']['enabled'] || !($args['noticeboard'] = cache::get('noticeboard_preview'))) {
            $query = prepare("SELECT ``noticeboard``.*, `username` FROM ``noticeboard`` LEFT JOIN ``mods`` ON ``mods``.`id` = `mod` ORDER BY `id` DESC LIMIT :limit");
            $query->bindValue(':limit', $config['mod']['noticeboard_dashboard'], PDO::PARAM_INT);
            $query->execute() or error(db_error($query));
            $args['noticeboard'] = $query->fetchAll(PDO::FETCH_ASSOC);
            if ($config['cache']['enabled']) {
                cache::set('noticeboard_preview', $args['noticeboard']);
            }
        }
    }
    if (!$config['cache']['enabled'] || ($args['unread_pms'] = cache::get('pm_unreadcount_' . $mod['id'])) === false) {
        $query = prepare('SELECT COUNT(*) FROM ``pms`` WHERE `to` = :id AND `unread` = 1');
        $query->bindValue(':id', $mod['id']);
        $query->execute() or error(db_error($query));
        $args['unread_pms'] = $query->fetchColumn();
        if ($config['cache']['enabled']) {
            cache::set('pm_unreadcount_' . $mod['id'], $args['unread_pms']);
        }
    }
    $query = prepare('SELECT COUNT(*) AS `total_reports` FROM ``reports``' . ($mod["type"] < GLOBALVOLUNTEER ? " WHERE board = :board" : ""));
    if ($mod['type'] < GLOBALVOLUNTEER) {
        $query->bindValue(':board', $mod['boards'][0]);
    } else {
        $query = prepare('SELECT (SELECT COUNT(id) FROM reports WHERE global = 0) AS total_reports, (SELECT COUNT(id) FROM reports WHERE global = 1) AS global_reports');
    }
    $query->execute() or error(db_error($query));
    $row = $query->fetch();
    $args['reports'] = $row['total_reports'];
    $args['global_reports'] = isset($row['global_reports']) ? $row['global_reports'] : false;
    $args['logout_token'] = make_secure_link_token('logout');
    modLog('Looked at dashboard', false);
    mod_page(_('Dashboard'), 'mod/dashboard.html', $args);
}
예제 #14
0
 /**
  * Constructor. Loads the data from the Instagram API.
  * @param string    The access token.
  * @param integer   The number of shots that will be loaded.
  * @param boolean   Chache enabled.
  * @param integer   How many seconds until the cache expires.
  * @param string    The user-id of the user or 'self' for your own account.
  */
 function __construct($_token = '', $_count = 10, $_cache = true, $_cache_expire = 3600, $_user = '******')
 {
     // Init
     $this->images = array();
     $this->user = new stdClass();
     // Check if a token is provided
     if (trim($_token) != '') {
         // Construct the API url…
         // http://instagr.am/developer/endpoints/users/
         $url = "https://api.instagram.com/v1/users/{$_user}/media/recent/?access_token={$_token}&count={$_count}";
         // Create cache directory if it doesn't exist yet
         if ($_cache) {
             dir::make(c::get('root.cache') . '/instagram');
         }
         $images_cache_id = 'instagram/images.' . md5($_token) . '.' . $_count . '.php';
         $images_cache_data = false;
         // Try to fetch data from cache
         if ($_cache) {
             $images_cache_data = cache::modified($images_cache_id) < time() - $_cache_expire ? false : cache::get($images_cache_id);
         }
         // Load data from the API if the cache expired or the cache is empty
         if (empty($images_cache_data)) {
             $data = $this->fetch_data($url);
             $photos = json_decode($data);
             // Set new data for the cache
             if ($_cache) {
                 cache::set($images_cache_id, $photos);
             }
         } else {
             $photos = $images_cache_data;
         }
         // Process the images
         for ($i = 0; $i < $_count; $i++) {
             if (isset($photos->data[$i]) && count($photos->data) > 0) {
                 // Get the user's data from the first image
                 if ($i == 0) {
                     $this->user->username = $photos->data[$i]->user->username;
                     $this->user->full_name = $photos->data[$i]->user->full_name;
                     $this->user->picture = $photos->data[$i]->user->profile_picture;
                 }
                 // create a new object for each image
                 $obj = new stdClass();
                 $obj->link = $photos->data[$i]->link;
                 $obj->comments = @$photos->data[$i]->comments->count;
                 $obj->likes = @$photos->data[$i]->likes->count;
                 $obj->created = $photos->data[$i]->created_time;
                 $obj->thumb = @$photos->data[$i]->images->thumbnail->url;
                 $obj->url = @$photos->data[$i]->images->standard_resolution->url;
                 $obj->image_lowres = @$photos->data[$i]->images->low_resolution->url;
                 $obj->filter = $photos->data[$i]->filter;
                 $obj->location = @$photos->data[$i]->location->name;
                 $obj->latitude = @$photos->data[$i]->location->latitude;
                 $obj->longitude = @$photos->data[$i]->location->longitude;
                 $obj->tags = array();
                 // attach the new object to the array
                 $this->images[$i] = $obj;
                 // Process tags
                 for ($j = 0; $j < count($photos->data[$i]->tags); $j++) {
                     $this->images[$i]->tags[$j] = $photos->data[$i]->tags[$j];
                 }
             }
         }
     } else {
         throw new Exception('$_token MUST be set!');
     }
 }
예제 #15
0
파일: mod.php 프로젝트: niksfish/Tinyboard
 } elseif (preg_match('/^\\/log(\\/(\\d+))?$/', $query, $match)) {
     if (!hasPermission($config['mod']['modlog'])) {
         error($config['error']['noaccess']);
     }
     $page = isset($match[2]) ? $match[2] : 1;
     $query = prepare("SELECT `mod` as `id`, `username`, `ip`, `board`, `time`, `text` FROM `modlogs` LEFT JOIN `mods` ON `mod` = `mods`.`id` ORDER BY `time` DESC LIMIT :offset, :limit");
     $query->bindValue(':limit', $config['mod']['modlog_page'], PDO::PARAM_INT);
     $query->bindValue(':offset', ($page - 1) * $config['mod']['modlog_page'], PDO::PARAM_INT);
     $query->execute() or error(db_error($query));
     if (!$query->rowCount()) {
         $body = '<p class="unimportant" style="text-align:center">(Nothing to display.)</p>';
     } else {
         $body = '<table class="modlog">' . '<tr>' . '<th>' . _('User') . '</th>' . '<th>' . _('IP address') . '</th>' . '<th>' . _('Ago') . '</th>' . '<th>' . _('Board') . '</th>' . '<th>' . _('Action') . '</th>' . '</tr>';
         while ($log = $query->fetch()) {
             $log_id = 'log_' . md5($log['text']);
             if ($config['cache']['enabled'] && ($_log = cache::get($log_id))) {
                 $log['text'] = $_log;
             } else {
                 $log['text'] = utf8tohtml($log['text']);
                 $log['text'] = preg_replace('/(\\d+\\.\\d+\\.\\d+\\.\\d+)/', '<a href="?/IP/$1">$1</a>', $log['text']);
                 if (isset($log['board'])) {
                     if (preg_match('/post #(\\d+)/', $log['text'], $match)) {
                         $post_query = prepare(sprintf("SELECT `thread` FROM `posts_%s` WHERE `id` = :id", $log['board']));
                         $post_query->bindValue(':id', $match[1], PDO::PARAM_INT);
                         $post_query->execute() or error(db_error($query));
                         if ($post = $post_query->fetch()) {
                             $log['text'] = preg_replace('/post (#(\\d+))/', 'post <a href="' . '?/' . sprintf($config['board_path'], $log['board']) . $config['dir']['res'] . ($post['thread'] ? sprintf($config['file_page'], $post['thread']) . '#' . $match[1] : sprintf($config['file_page'], $match[1])) . '">$1</a>', $log['text']);
                         } else {
                             $log['text'] = preg_replace('/post (#(\\d+))/', 'post <s>$1</s>', $log['text']);
                         }
                         if ($config['cache']['enabled']) {
예제 #16
0
 /**
  * Gets the session data.
  *
  * @param bool $force If true the session data will be loaded from the store again.
  * @return array An array of session data.
  */
 protected function get_session_data($force = false)
 {
     if ($this->sessionid === null) {
         $this->sessionid = session_id();
     }
     if (is_array($this->session) && !$force) {
         return $this->session;
     }
     $session = parent::get($this->sessionid);
     if ($session === false) {
         $session = array();
     }
     // We have to write here to ensure that the lastaccess time is recorded.
     // And also in order to ensure the session entry exists as when we save it on __destruct
     // $CFG is likely to have already been destroyed.
     $this->save_session($session);
     return $this->session;
 }
예제 #17
0
function core_getClass($class, $id, $continueOnError = False)
{
    /* this version works only for the "standard" classes with args (id,db,mode) */
    $class = ereg_replace('formform', 'form', $class);
    $cache = new cache('core_getClass');
    if ($cache->wasSet($class, $id)) {
        return $cache->get();
    }
    if ($_GET["mode"] != 'RW') {
        $_GET["mode"] = 'RO';
    }
    if ((int) $id) {
        if (!get_class($GLOBALS["appsDB"])) {
            core_internalError("core_getClass: DB not initialized");
        }
        $svdebug = $GLOBALS["appsDB"]->debug;
        $GLOBALS["appsDB"]->debug = 0;
        if (!($identity = $GLOBALS["identities"][$class])) {
            core_internalError("no identities for {$class}");
        }
        $q = $GLOBALS["appsDB"]->query("SELECT " . $identity["i"] . " AS id FROM " . $identity["t"] . " WHERE " . $identity["i"] . " = {$id}");
        $GLOBALS["appsDB"]->debug = $svdebug;
        if ($GLOBALS["appsDB"]->num_rows($q)) {
            return $cache->set(new $class($id, $GLOBALS["appsDB"], $_GET["mode"]));
        }
        $error = "does not exist in the database";
    } else {
        return new $class($id, $GLOBALS["appsDB"], $_GET["mode"]);
    }
    if (!$continueOnError) {
        core_dbg(redText('core_getClass'), redText("{$class}({$id})"), redText($error), core_getOption('YBhere'));
        core_backtrace();
    }
}
예제 #18
0
function DNS($host)
{
    global $config;
    if ($config['cache']['enabled'] && ($ip_addr = cache::get('dns_' . $host))) {
        return $ip_addr != '?' ? $ip_addr : false;
    }
    if (!$config['dns_system']) {
        $ip_addr = gethostbyname($host);
        if ($ip_addr == $host) {
            $ip_addr = false;
        }
    } else {
        $resp = shell_exec_error('host -W 1 ' . $host);
        if (preg_match('/has address ([^\\s]+)$/', $resp, $m)) {
            $ip_addr = $m[1];
        } else {
            $ip_addr = false;
        }
    }
    if ($config['cache']['enabled']) {
        cache::set('dns_' . $host, $ip_addr !== false ? $ip_addr : '?');
    }
    return $ip_addr;
}
예제 #19
0
 public function actionGetcache()
 {
     $cache = new \cache();
     $cacheKey = 'myframe_k1';
     return $cache->get($cacheKey);
 }
예제 #20
0
        if (is_array($name)) {
            foreach ($name as $n) {
                $this->clean($n);
            }
            return;
        }
        $name = preg_replace('![^a-z0-9_]!i', '_', $name);
        kleeja_unlink(PATH . 'cache/' . $name . '.php');
    }
}
$cache = new cache();
//
//get hooks data from hooks table  ...
//
if (!defined('STOP_HOOKS')) {
    if (!($all_plg_h_p = $cache->get('data_plugins'))) {
        //get all hooks
        $query = array('SELECT' => 'h.hook_id,h.hook_name, h.hook_content, h.plg_id, p.plg_name', 'FROM' => "{$dbprefix}hooks AS h", 'JOINS' => array(array('INNER JOIN' => "{$dbprefix}plugins AS p", 'ON' => 'p.plg_id=h.plg_id')), 'WHERE' => 'p.plg_disabled=0', 'ORDER BY' => 'h.hook_id');
        ($hook = kleeja_run_hook('qr_select_hooks_cache')) ? eval($hook) : null;
        //run hook
        $result = $SQL->build($query);
        while ($row = $SQL->fetch_array($result)) {
            $all_plg_hooks[$row['hook_name']][$row['plg_name']] = $row['hook_content'];
            $all_plg_plugins[$row['plg_name']] = null;
        }
        $SQL->freeresult($result);
        $cache->save('data_plugins', array($all_plg_plugins, $all_plg_hooks));
    }
    list($all_plg_plugins, $all_plg_hooks) = $all_plg_h_p;
}
#plugins is on
예제 #21
0
 function load()
 {
     // initiate the site and make pages and page
     // globally available
     $pages = $this->pages;
     $page = $this->pages->active();
     // check for ssl
     if (c::get('ssl')) {
         // if there's no https in the url
         if (!server::get('https')) {
             go(str_replace('http://', 'https://', $page->url()));
         }
     }
     // check for index.php in rewritten urls and rewrite them
     if (c::get('rewrite') && preg_match('!index.php\\/!i', $this->uri->original)) {
         go($page->url());
     }
     // check for a misconfigured subfolder install
     if ($page->isErrorPage()) {
         // if you want to store subfolders in the homefolder for blog articles i.e. and you
         // want urls like http://yourdomain.com/article-title you can set
         // RedirectMatch 301 ^/home/(.*)$ /$1 in your htaccess file and those
         // next lines will take care of delivering the right pages.
         $uri = c::get('home') . '/' . $this->uri->path();
         if ($redirected = $this->pages()->find($uri)) {
             if ($redirected->uri() == $uri) {
                 $page = $redirected;
                 $this->pages->active = $page;
                 $this->uri = new uri($uri);
             }
         }
         // try to rewrite broken translated urls
         // this will only work for default uris
         if (c::get('lang.support')) {
             $path = $this->uri->path->toArray();
             $obj = $pages;
             $found = false;
             foreach ($path as $p) {
                 // first try to find the page by uid
                 $next = $obj->{'_' . $p};
                 if (!$next) {
                     // go through each translation for each child page
                     // and try to find the url_key or uid there
                     foreach ($obj as $child) {
                         foreach (c::get('lang.available') as $lang) {
                             $c = $child->content($lang);
                             // redirect to the url if a translated url has been found
                             if ($c && $c->url_key() == $p && !$child->isErrorPage()) {
                                 $next = $child;
                             }
                         }
                     }
                     if (!$next) {
                         break;
                     }
                 }
                 $found = $next;
                 $obj = $next->children();
             }
             if ($found && !$found->isErrorPage()) {
                 go($found->url());
             }
         }
     }
     // redirect file urls (file:image.jpg)
     if ($this->uri->param('file')) {
         // get the local file
         $file = $page->files()->find($this->uri->param('file'));
         if ($file) {
             go($file->url());
         }
     }
     // redirect /home to /
     if ($this->uri->path() == c::get('home')) {
         go(url());
     }
     // redirect tinyurls
     if ($this->uri->path(1) == c::get('tinyurl.folder') && c::get('tinyurl.enabled')) {
         $hash = $this->uri->path(2);
         if (!empty($hash)) {
             $resolved = $this->pages->findByHash($hash)->first();
             // redirect to the original page
             if ($resolved) {
                 go(url($resolved->uri));
             }
         }
     }
     // set the global template vars
     tpl::set('site', $this);
     tpl::set('pages', $pages);
     tpl::set('page', $page);
     $cacheID = $this->htmlCacheID();
     $cacheModified = time();
     $cacheData = null;
     if ($this->htmlCacheEnabled) {
         // check if the cache is disabled for some reason
         $this->htmlCacheEnabled = $page->isErrorPage() || in_array($page->uri(), c::get('cache.ignore', array())) ? false : true;
         // check for the last modified date of the cache file
         $cacheModified = cache::modified($cacheID);
         // check if the files have been modified
         // since the last html cache file has been written
         if ($this->htmlCacheEnabled && $cacheModified >= $this->modified) {
             $cacheData = cache::get($cacheID, true);
         }
     }
     // send a 404 header if this is the error page
     if ($page->isErrorPage() && c::get('404.header')) {
         header("HTTP/1.0 404 Not Found");
     }
     if (empty($cacheData)) {
         // load the main template
         $html = tpl::load($page->template(), array(), true);
         if ($this->htmlCacheEnabled) {
             cache::set($cacheID, (string) $html, true);
         }
     } else {
         $html = $cacheData;
     }
     die($html);
 }
예제 #22
0
 /**
  * @return HTML - Дерево комментариев
  * @param int $page_id - ID страницы для которой нужно создать дерево
  * @param string $templ_name - Шаблон оформления дерева
  * @desc МАКРОС: Строит список (дерево) комментариев для указанной страницы
  */
 public function tree($page_id, $templ_name = 'tree')
 {
     $key = 'comments' . $page_id;
     if (!($data = cache::get($key))) {
         $templ_file = '/comments/' . $templ_name . '.tpl';
         $TEMPLATE = page::getTemplate($templ_file);
         if (!is_array($TEMPLATE)) {
             return page::errorNotFound('comments.tree', $templ_file);
         }
         // Получаем список комментариев
         $tree = new comments($page_id);
         $tree->onlyActive(!reg::getKey('/comments/show_noactive'));
         $list = $this->getCommentList($tree, 0, $TEMPLATE);
         page::assign('obj_id', $page_id);
         if (empty($list)) {
             $data = page::parse($TEMPLATE['empty']);
         } else {
             page::assign('list', $list);
             page::assign('count', $tree->getCount());
             $data = page::parse($TEMPLATE['frame']);
         }
         // Записываем в кэш
         cache::set($key, $data);
     }
     return $data;
 }
예제 #23
0
function countarchiveformcategory($catid) {
    $cache_id=md5('countarchiveformtype'.$catid);
    $cache=cache::get($cache_id);
    if (isset($cache))
        $count=$cache;
    else
        $count=archive::countarchiveformcategory($catid);
    if (cache::set($cache_id,$count,60))
        ;
    return $count;
}
예제 #24
0
 /**
  * Constructor. Loads the data from Dribbble when the object is constructed.
  * @param string    $_username The username of the player.
  * @param integer   $_number_of_shots The number of shots that will be loaded.
  * @param boolean   $_fetch_likes If the likes of the user should be fetched in a second call.
  * @param integer   If <code>$_fetch_likes</code> is <code>true</code>, then how many likes should be fetched.
  * @param boolean   $cache Enable/disable caching. Cache is enabled by default
  * @param integer   $refresh Seconds before the cache will be refreshed. Default is in hour (3600 seconds)
  */
 function __construct($_username = "******", $_number_of_shots = 3, $_fetch_likes = false, $_number_of_likes = 3, $cache = true, $refresh = 3600)
 {
     // Init
     $this->username = $_username;
     $this->shots = array();
     $this->likes = array();
     $this->player = null;
     // Build URLs
     $base_url = "http://api.dribbble.com/players/" . $this->username;
     $shots_url = $base_url . "/shots";
     $likes_url = $base_url . "/likes";
     // create the cache directory if not there yet
     if ($cache) {
         dir::make(c::get('root.cache') . '/dribbble');
     }
     // Process the data
     if ($_number_of_shots > 0) {
         // define a cache id
         $shots_cache_id = 'dribbble/shots.' . md5($this->username) . '.' . $_number_of_shots . '.php';
         $shots_cache_data = false;
         // try to fetch the data from cache
         if ($cache) {
             $shots_cache_data = cache::modified($shots_cache_id) < time() - $refresh ? false : cache::get($shots_cache_id);
         }
         // if there's no data in the cache, load shots from the Dribbble API
         if (empty($shots_cache_data)) {
             $all_shots = $this->fetch_data($shots_url);
             $all_shots = json_decode($all_shots);
             $all_shots = $all_shots->shots;
             if ($cache) {
                 cache::set($shots_cache_id, $all_shots);
             }
         } else {
             $all_shots = $shots_cache_data;
         }
         // Only proceed if there is at least one shot.
         // If there's no shot, then player data can't be extracted from this API call
         // and must be extracted via /players/:id/ (maybe I'll implement that later)
         if (count($all_shots) > 0) {
             // Load shots data
             for ($i = 0; $i < $_number_of_shots; $i++) {
                 if (!is_null($all_shots[$i])) {
                     $this->shots[$i]->id = $all_shots[$i]->id;
                     $this->shots[$i]->title = $all_shots[$i]->title;
                     $this->shots[$i]->url = $all_shots[$i]->url;
                     $this->shots[$i]->short_url = $all_shots[$i]->short_url;
                     $this->shots[$i]->image = $all_shots[$i]->image_url;
                     $this->shots[$i]->likes = $all_shots[$i]->likes_count;
                     $this->shots[$i]->views = $all_shots[$i]->views_count;
                     $this->shots[$i]->rebounds = $all_shots[$i]->rebounds_count;
                     $this->shots[$i]->comments = $all_shots[$i]->comments_count;
                     $this->shots[$i]->created = $all_shots[$i]->created_at;
                 }
             }
             // Process player data
             $this->player->id = $all_shots[0]->player->id;
             $this->player->name = $all_shots[0]->player->name;
             $this->player->username = $all_shots[0]->player->username;
             $this->player->url = $all_shots[0]->player->url;
             $this->player->avatar_url = $all_shots[0]->player->avatar_url;
             $this->player->twitter = $all_shots[0]->player->twitter_screen_name;
             $this->player->location = $all_shots[0]->player->location;
             $this->player->followers = $all_shots[0]->player->followers_count;
             $this->player->following = $all_shots[0]->player->following_count;
             $this->player->likes = $all_shots[0]->player->likes_count;
         }
     }
     // Fetch all likes of the user (needs another API call).
     // If you only want to fetch the likes, not the shots, then set <code>$_number_of_shots</code> to <code>0</code>.
     if ($_fetch_likes && $_number_of_likes > 0) {
         // define a cache id
         $likes_cache_id = 'dribbble/likes.' . md5($this->username) . '.' . $_number_of_likes . '.php';
         $likes_cache_data = false;
         // try to fetch the data from cache
         if ($cache) {
             $likes_cache_data = cache::modified($likes_cache_id) < time() - $refresh ? false : cache::get($likes_cache_id);
         }
         // if there's no data in the cache, load likes from the Dribbble API
         if (empty($likes_cache_data)) {
             $all_likes = $this->fetch_data($likes_url);
             $all_likes = json_decode($all_likes);
             $all_likes = $all_likes->shots;
             if ($cache) {
                 cache::set($likes_cache_id, $all_likes);
             }
         } else {
             $all_likes = $likes_cache_data;
         }
         // Process likes
         for ($i = 0; $i < $_number_of_likes; $i++) {
             if (!is_null($all_likes[$i])) {
                 $this->likes[$i]->id = $all_likes[$i]->id;
                 $this->likes[$i]->title = $all_likes[$i]->title;
                 $this->likes[$i]->url = $all_likes[$i]->url;
                 $this->likes[$i]->short_url = $all_likes[$i]->short_url;
                 $this->likes[$i]->image = $all_likes[$i]->image_url;
                 $this->likes[$i]->likes = $all_likes[$i]->likes_count;
                 $this->likes[$i]->views = $all_likes[$i]->views_count;
                 $this->likes[$i]->rebounds = $all_likes[$i]->rebounds_count;
                 $this->likes[$i]->comments = $all_likes[$i]->comments_count;
                 $this->likes[$i]->created = $all_likes[$i]->created_at;
                 // Process the user the like belongs to
                 $this->likes[$i]->player->id = $all_likes[$i]->player->id;
                 $this->likes[$i]->player->name = $all_likes[$i]->player->name;
                 $this->likes[$i]->player->username = $all_likes[$i]->player->username;
                 $this->likes[$i]->player->url = $all_likes[$i]->player->url;
                 $this->likes[$i]->player->avatar_url = $all_likes[$i]->player->avatar_url;
                 $this->likes[$i]->player->twitter = $all_likes[$i]->player->twitter_screen_name;
                 $this->likes[$i]->player->location = $all_likes[$i]->player->location;
                 $this->likes[$i]->player->followers = $all_likes[$i]->player->followers_count;
                 $this->likes[$i]->player->following = $all_likes[$i]->player->following_count;
                 $this->likes[$i]->player->likes = $all_likes[$i]->player->likes_count;
             }
         }
     }
 }
예제 #25
0
 public function get($idService, $params)
 {
     //dd($this->getCacheTimeToServices($idService));
     $cache = new cache();
     $idCache = $idService . var_export($params, true);
     $result = $cache->get($idCache, $this->getCacheTimeToServices($idService));
     if (is_null($result)) {
         $data = array_merge($this->commonData, $params);
         $url = $this->urlService($idService);
         // use key 'http' even if you send the request to https://...
         $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)), 'ssl' => array('verify_peer' => false, 'verify_peer_name' => false));
         $context = stream_context_create($options);
         $result = file_get_contents($url, false, $context);
         //d($url,$data);
         //dd($result);
         if ($result === false) {
             throw new NotResponseRemoteServiceException("The remote service [{$idService}] is not responding. Fail read content {$url}");
         }
         //header('Content-Type: application/json'); echo($result);die();
         $result = json_decode($result, 1);
         switch ($idService) {
             case 'GetEstimatesIncident':
                 /* Parche GetEstimatesIncident cuando en stop/stopLines/data llega un único elemento y no llega como array */
                 if (isset($result['stop']) && is_array($result['stop']['stopLines']['data']) && !isset($result['stop']['stopLines']['data'][0])) {
                     $tmp = $result['stop']['stopLines']['data'];
                     unset($result['stop']['stopLines']['data']);
                     $result['stop']['stopLines']['data'] = array($tmp);
                 }
                 // Llegadas
                 if (isset($result['arrives']) && is_array($result['arrives']['arriveEstimationList']['arrive']) && is_null($result['arrives']['arriveEstimationList']['arrive'][0])) {
                     $tmp = $result['arrives']['arriveEstimationList']['arrive'];
                     unset($result['arrives']['arriveEstimationList']['arrive']);
                     $result['arrives']['arriveEstimationList']['arrive'] = array($tmp);
                 }
                 break;
             case 'GetArriveStop':
                 /* Parche GetArriveStop cuando sólo llega un único elemento y no llega como array, sustituido por GetEstimatesIncident*/
                 if (is_array($result['arrives']) && is_null($result['arrives'][0])) {
                     $tmp = $result['arrives'];
                     unset($result['arrives']);
                     $result['arrives'] = array($tmp);
                 }
                 break;
             case 'getStopsFromXY':
                 /* Parche getStopsFromXY cuando en lines sólo llega un único elemento y no llega como array */
                 if (is_array($result['stop'])) {
                     foreach ($result['stop'] as $key => $stop) {
                         if (!isset($stop['line'][0]['line'])) {
                             $tmp = $stop['line'];
                             unset($result['stop'][$key]['line']);
                             $result['stop'][$key]['line'] = array($tmp);
                         }
                     }
                 }
                 /* Precalcular distancias */
                 if (is_array($result['stop'])) {
                     foreach ($result['stop'] as $key => $stop) {
                         $result['stop'][$key]['distance'] = units::distance($result['latitude'], $result['longitude'], $stop['latitude'], $stop['longitude']);
                     }
                 }
                 # code...
                 break;
         }
         if ($this->getCacheTimeToServices($idService) != 0) {
             // -1 force refresh cache
             $cache->set($idCache, serialize($result));
         }
     } else {
         $result = unserialize($result);
     }
     // Add timestamp info
     $result['timestamp'] = $cache->getTimeStamp();
     //echo (date(DATE_ATOM, $cache->getTimeStamp()));
     //d($result);
     return $result;
 }
예제 #26
0
 public function treemenu()
 {
     $allmenu = array();
     $adminmenu = 'admin_tree_menu';
     if (is_cache($adminmenu, 'admin')) {
         echo cache::get($adminmenu, 'admin');
     } else {
         $menuarr = model('admin_menu')->select()->query();
         foreach ($menuarr as $menu) {
             if ($menu['parentmenuid'] == 0) {
                 $allmenu[$menu['menuid']]['text'] = $menu['menuname'];
                 $allmenu[$menu['menuid']]['id'] = $menu['menuid'];
                 $allmenu[$menu['menuid']]['checked'] = false;
                 $allmenu[$menu['menuid']]['children'] = array();
                 $allmenu[$menu['menuid']]['leaf'] = false;
             } else {
                 $allmenu[$menu['parentmenuid']]['children'][] = array('text' => $menu['menuname'], 'id' => $menu['menuid']);
             }
         }
         $menu = array();
         foreach ($allmenu as $m) {
             $menu[] = $m;
         }
         //print_r($menu);
         echo $menu = json_encode($menu);
     }
 }
예제 #27
0
 /**
  * Retrieves the value for the given key from the cache.
  *
  * @param string|int $key The key for the data being requested.
  * @param int $strictness One of IGNORE_MISSING | MUST_EXIST
  * @return mixed|false The data from the cache or false if the key did not exist within the cache.
  */
 public function get($key, $strictness = IGNORE_MISSING)
 {
     if ($this->requirelockingread && $this->check_lock_state($key) === false) {
         // Read locking required and someone else has the read lock.
         return false;
     }
     return parent::get($key, $strictness);
 }
예제 #28
0
$base_dir = dirname(__FILE__);
ini_set('include_path', $base_dir . '/pear/');
// includes
require_once $base_dir . '/config/settings.php';
require_once $base_dir . '/config/config.php';
require_once $base_dir . '/config/messages.php';
require_once 'common.php';
require_once 'Auth.php';
require_once $base_dir . '/classes/class_db.php';
require_once $base_dir . '/classes/class_form.php';
require_once $base_dir . '/classes/class_logger.php';
require_once $base_dir . '/classes/class_page.php';
require_once $base_dir . '/classes/class_cache.php';
$vars = array('title', 'keywords', 'description', 'padding_top', 'body');
$cache = new cache();
if ($cached = $cache->get()) {
    foreach ($vars as $var) {
        ${$var} = $cached[$var];
    }
} else {
    // initialization
    $db = new db();
    $db->connect($dsn);
    $db->msg = $msg;
    // authentication & and logging
    $auth = new Auth('MDB2', array('dsn' => $db->dsn, 'table' => "sys_user", 'usernamecol' => "user_id", 'passwordcol' => "pass_key"), 'login');
    $auth->start();
    $logger = new logger($db, $auth);
    $logger->log();
    // define mod
    $mods = array('user', 'dictionary', 'glossary', 'home', 'doc', 'proverb', 'abbr', 'dict2');
예제 #29
0
파일: site.php 프로젝트: robeam/kirbycms
 function load()
 {
     // initiate the site and make pages and page
     // globally available
     $pages = $this->pages;
     $page = $this->pages->active();
     // check for ssl
     if (c::get('ssl')) {
         // if there's no https in the url
         if (!server::get('https')) {
             go(str_replace('http://', 'https://', $page->url()));
         }
     }
     // check for a misconfigured subfolder install
     if ($page->isErrorPage()) {
         // get the subfolder in which the site is running
         $subfolder = ltrim(dirname(server::get('script_name')), '/');
         // if it is running in a subfolder and it does not match the config
         // send an error with some explanations how to fix that
         if (!empty($subfolder) && c::get('subfolder') != $subfolder) {
             // this main url
             $url = 'http://' . server::get('http_host') . '/' . $subfolder;
             require_once c::get('root.kirby') . '/modals/subfolder.php';
             exit;
         }
     }
     // redirect file urls (file:image.jpg)
     if ($this->uri->param('file')) {
         // get the local file
         $file = $page->files()->find($this->uri->param('file'));
         if ($file) {
             go($file->url());
         }
     }
     // redirect /home to /
     if ($this->uri->path() == c::get('home')) {
         go(url());
     }
     // redirect tinyurls
     if ($this->uri->path(1) == c::get('tinyurl.folder') && c::get('tinyurl.enabled')) {
         $hash = $this->uri->path(2);
         if (!empty($hash)) {
             $resolved = $this->pages->findByHash($hash)->first();
             // redirect to the original page
             if ($resolved) {
                 go(url($resolved->uri));
             }
         }
     }
     // set the global template vars
     tpl::set('site', $this);
     tpl::set('pages', $pages);
     tpl::set('page', $page);
     $cacheID = $this->uri->toCacheID() . '.php';
     $cacheModified = time();
     $cacheData = null;
     if ($this->htmlCacheEnabled) {
         // check if the cache is disabled for some reason
         $this->htmlCacheEnabled = $page->isErrorPage() || in_array($page->uri(), c::get('cache.ignore', array())) ? false : true;
         // check for the last modified date of the cache file
         $cacheModified = cache::modified($cacheID);
         // check if the files have been modified
         // since the last html cache file has been written
         if ($this->htmlCacheEnabled && $cacheModified >= $this->modified) {
             $cacheData = cache::get($cacheID, true);
         }
     }
     if (empty($cacheData)) {
         // load the main template
         $html = tpl::load($page->template(), false, true);
         if ($this->htmlCacheEnabled) {
             cache::set($cacheID, (string) $html, true);
         }
     } else {
         $html = $cacheData;
     }
     die($html);
 }
예제 #30
0
파일: pages.php 프로젝트: vicentil/vichan
function mod_dashboard()
{
    global $config, $mod;
    $args = array();
    $args['boards'] = listBoards();
    if (hasPermission($config['mod']['noticeboard'])) {
        if (!$config['cache']['enabled'] || !($args['noticeboard'] = cache::get('noticeboard_preview'))) {
            $query = prepare("SELECT ``noticeboard``.*, `username` FROM ``noticeboard`` LEFT JOIN ``mods`` ON ``mods``.`id` = `mod` ORDER BY `id` DESC LIMIT :limit");
            $query->bindValue(':limit', $config['mod']['noticeboard_dashboard'], PDO::PARAM_INT);
            $query->execute() or error(db_error($query));
            $args['noticeboard'] = $query->fetchAll(PDO::FETCH_ASSOC);
            if ($config['cache']['enabled']) {
                cache::set('noticeboard_preview', $args['noticeboard']);
            }
        }
    }
    if (!$config['cache']['enabled'] || ($args['unread_pms'] = cache::get('pm_unreadcount_' . $mod['id'])) === false) {
        $query = prepare('SELECT COUNT(*) FROM ``pms`` WHERE `to` = :id AND `unread` = 1');
        $query->bindValue(':id', $mod['id']);
        $query->execute() or error(db_error($query));
        $args['unread_pms'] = $query->fetchColumn();
        if ($config['cache']['enabled']) {
            cache::set('pm_unreadcount_' . $mod['id'], $args['unread_pms']);
        }
    }
    $query = query('SELECT COUNT(*) FROM ``reports``') or error(db_error($query));
    $args['reports'] = $query->fetchColumn();
    if ($mod['type'] >= ADMIN && $config['check_updates']) {
        if (!$config['version']) {
            error(_('Could not find current version! (Check .installed)'));
        }
        if (isset($_COOKIE['update'])) {
            $latest = unserialize($_COOKIE['update']);
        } else {
            $ctx = stream_context_create(array('http' => array('timeout' => 5)));
            if ($code = @file_get_contents('http://tinyboard.org/version.txt', 0, $ctx)) {
                $ver = strtok($code, "\n");
                if (preg_match('@^// v(\\d+)\\.(\\d+)\\.(\\d+)\\s*?$@', $ver, $matches)) {
                    $latest = array('massive' => $matches[1], 'major' => $matches[2], 'minor' => $matches[3]);
                    if (preg_match('/v(\\d+)\\.(\\d)\\.(\\d+)(-dev.+)?$/', $config['version'], $matches)) {
                        $current = array('massive' => (int) $matches[1], 'major' => (int) $matches[2], 'minor' => (int) $matches[3]);
                        if (isset($m[4])) {
                            // Development versions are always ahead in the versioning numbers
                            $current['minor']--;
                        }
                        // Check if it's newer
                        if (!($latest['massive'] > $current['massive'] || $latest['major'] > $current['major'] || $latest['massive'] == $current['massive'] && $latest['major'] == $current['major'] && $latest['minor'] > $current['minor'])) {
                            $latest = false;
                        }
                    } else {
                        $latest = false;
                    }
                } else {
                    // Couldn't get latest version
                    $latest = false;
                }
            } else {
                // Couldn't get latest version
                $latest = false;
            }
            setcookie('update', serialize($latest), time() + $config['check_updates_time'], $config['cookies']['jail'] ? $config['cookies']['path'] : '/', null, !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off', true);
        }
        if ($latest) {
            $args['newer_release'] = $latest;
        }
    }
    $args['logout_token'] = make_secure_link_token('logout');
    mod_page(_('Dashboard'), 'mod/dashboard.html', $args);
}