set() public méthode

public set ( $key, $data )
Exemple #1
0
 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);
         }
     }
 }
Exemple #2
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;
 }
Exemple #3
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;
 }
Exemple #4
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' => []];
    }
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;
}
Exemple #6
0
 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();
     }
 }
Exemple #7
0
 public static function proccessMessageEvent($_message)
 {
     switch ($_message->messageSchemeIdentifier()) {
         case 'sensor.basic':
             require_once dirname(__FILE__) . '/schema/sensor.basic.class.php';
             $list_event = basicSensor::parserMessage($_message);
             break;
         default:
             break;
     }
     if (is_array($list_event)) {
         foreach ($list_event as $event) {
             $cmd = xPLCmd::byId($event['cmd_id']);
             if ($cmd->getType() == 'info') {
                 cache::set('xpl' . $cmd->getId(), $event['value']);
             }
             $cmd->event($event['value']);
         }
     }
     return;
 }
Exemple #8
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]];
     }
 }
Exemple #9
0
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);
}
Exemple #10
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;
}
Exemple #11
0
 public static function getUsbMapping($_name = '', $_getGPIO = false)
 {
     $cache = cache::byKey('jeedom::usbMapping');
     if (!is_json($cache->getValue()) || $_name == '') {
         $usbMapping = array();
         foreach (ls('/dev/', 'ttyUSB*') as $usb) {
             $vendor = '';
             $model = '';
             foreach (explode("\n", shell_exec('/sbin/udevadm info --name=/dev/' . $usb . ' --query=all')) as $line) {
                 if (strpos($line, 'E: ID_MODEL=') !== false) {
                     $model = trim(str_replace(array('E: ID_MODEL=', '"'), '', $line));
                 }
                 if (strpos($line, 'E: ID_VENDOR=') !== false) {
                     $vendor = trim(str_replace(array('E: ID_VENDOR=', '"'), '', $line));
                 }
             }
             if ($vendor == '' && $model == '') {
                 $usbMapping['/dev/' . $usb] = '/dev/' . $usb;
             } else {
                 $name = trim($vendor . ' ' . $model);
                 $number = 2;
                 while (isset($usbMapping[$name])) {
                     $name = trim($vendor . ' ' . $model . ' ' . $number);
                     $number++;
                 }
                 $usbMapping[$name] = '/dev/' . $usb;
             }
         }
         if ($_getGPIO) {
             if (file_exists('/dev/ttyAMA0')) {
                 $usbMapping['Raspberry pi'] = '/dev/ttyAMA0';
             }
             if (file_exists('/dev/ttymxc0')) {
                 $usbMapping['Jeedom board'] = '/dev/ttymxc0';
             }
             if (file_exists('/dev/S2')) {
                 $usbMapping['Banana PI'] = '/dev/S2';
             }
             if (file_exists('/dev/ttyS2')) {
                 $usbMapping['Banana PI (2)'] = '/dev/ttyS2';
             }
             if (file_exists('/dev/ttyS0')) {
                 $usbMapping['Cubiboard'] = '/dev/ttyS0';
             }
             foreach (ls('/dev/', 'ttyACM*') as $value) {
                 $usbMapping['/dev/' . $value] = '/dev/' . $value;
             }
         }
         cache::set('jeedom::usbMapping', json_encode($usbMapping), 0);
     } else {
         $usbMapping = json_decode($cache->getValue(), true);
     }
     if ($_name != '') {
         if (isset($usbMapping[$_name])) {
             return $usbMapping[$_name];
         }
         $usbMapping = self::getUsbMapping('', $_getGPIO);
         if (isset($usbMapping[$_name])) {
             return $usbMapping[$_name];
         }
         if (file_exists($_name)) {
             return $_name;
         }
         return '';
     }
     return $usbMapping;
 }
	private static function _clientStyles()
	{
		$styles=array();
		$dir=FLEX_APP_DIR_TPL."/".self::$config["template"]."/".self::$class;
		$file=FLEX_APP_DIR."/".$dir."/styles/".self::$class.".css";
		$found=@file_exists($file);
		if(FLEX_APP_DIR_SRC && !$found)
		{
			$file=FLEX_APP_DIR_SRC.".core/".$file;
			$tplDir=FLEX_APP_DIR_ROOT."?feh-rsc-get=auto&path=/".FLEX_APP_DIR."/".$dir."/";
			$found=@file_exists($file);
		}
		else
		{
			$tplDir=FLEX_APP_DIR_ROOT.FLEX_APP_DIR."/".$dir."/";
		}
		$styles[]=array("class"=>self::$class,"ext"=>false,"file"=>$file,"found"=>$found,"name"=>self::$class,"tplDir"=>$tplDir);//ext - external script
		$len=count(self::$clStyles);
		for($cnt=0;$cnt<$len;$cnt++)
		{
			$item=array();
			if(self::$clStyles[$cnt]["http"])continue;
			$item["class"]=self::$clStyles[$cnt]["class"];
			if(self::$clStyles[$cnt]["link"])
			{
				$path=explode("/",self::$clStyles[$cnt]["name"]);
				if(count($path))$name=array_pop($path);
				else $name=self::$clStyles[$cnt]["name"];
				$item["ext"]=false;
				$item["file"]=self::$clStyles[$cnt]["name"];
				$item["found"]=@file_exists($item["file"]);
				$item["name"]=$name;
				$item["tplDir"]=FLEX_APP_DIR_ROOT.implode("/",$path)."/";
			}
			else
			{
				$tpl=(isset(self::$clStyles[$cnt]["tpl"])?self::$clStyles[$cnt]["tpl"]:self::$c->template());
				$core=(isset(self::$clStyles[$cnt]["core"]) && self::$clStyles[$cnt]["core"]);
				$corePath=$core?(FLEX_APP_DIR."/"):"";
				$dir=FLEX_APP_DIR_TPL."/".$tpl."/".self::$clStyles[$cnt]["class"].self::$clStyles[$cnt]["admin"];
				$file=$dir."/styles/".self::$clStyles[$cnt]["name"].".css";
				$found=@file_exists($corePath.$file);
				if(FLEX_APP_DIR_SRC && !$found)
				{
					$file=FLEX_APP_DIR_SRC.($core?(".core/".FLEX_APP_DIR):(".classes/.".self::$clStyles[$cnt]["class"]))."/".$file;
					$tplDir=FLEX_APP_DIR_ROOT."?feh-rsc-get=auto&path=/".$corePath.$dir."/";
					$found=@file_exists($file);
				}
				else
				{
					$tplDir=FLEX_APP_DIR_ROOT.$corePath.$dir."/";
				}
				$item["ext"]=false;
				$item["file"]=$file;
				$item["found"]=$found;
				$item["name"]=self::$clStyles[$cnt]["name"];
				$item["tplDir"]=$tplDir;
			}
			$styles[]=$item;
		}
		$dir=FLEX_APP_DIR_TPL."/".self::$config["template"]."/".self::$class;
		$file=FLEX_APP_DIR."/".$dir."/styles/ender.css";
		$found=@file_exists($file);
		if(FLEX_APP_DIR_SRC && !$found)
		{
			$file=FLEX_APP_DIR_SRC.".core/".$file;
			$tplDir=FLEX_APP_DIR_ROOT."?feh-rsc-get=auto&path=/".FLEX_APP_DIR."/".$dir."/";
			$found=@file_exists($file);
		}
		else
		{
			$tplDir=FLEX_APP_DIR_ROOT.FLEX_APP_DIR."/".$dir."/";
		}
		$styles[]=array("class"=>self::$class,"ext"=>false,"file"=>$file,"found"=>$found,"name"=>"ender","tplDir"=>$tplDir);//ext - external script
		//сохраняем список для css.php
		$md=md5(serialize($styles));
		$url=cache::check(self::$class,$md,self::$config["cacheEvalCss"],"css");
		if(!$url)
		{
			$cont=self::_buildStyleSheet($styles);
			if(!$cont)die("CSS render error.");
			$url=cache::set(self::$class,$md,self::$config["cacheEvalCss"],$cont,false,"css");
			if(!$url)die("CSS render error.");
		}
?>
	<link type="text/css" href="<?php 
echo FLEX_APP_DIR_ROOT . $url;
?>
" media="all" rel="stylesheet" />
<?
		for($cnt=0;$cnt<$len;$cnt++)
		{
			if(self::$clStyles[$cnt]["http"])
			{
?>
	<link type="text/css" href="<?php 
echo self::$clStyles[$cnt]["name"];
?>
" media="all" rel="stylesheet" />
<?
			}
		}
	}
Exemple #13
0
 public function setCollect($collect)
 {
     if ($collect == 1) {
         cache::set('collect' . $this->getId(), $this->getId());
     } else {
         cache::deleteBySearch('collect' . $this->getId());
     }
 }
 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);
 }
 public function getWeatherFromYahooXml()
 {
     if ($this->getConfiguration('city') == '') {
         return false;
     }
     $cache = cache::byKey('yahooWeatherXml' . $this->getConfiguration('city'));
     if ($cache->getValue() === '' || $cache->getValue() == 'false') {
         $request = new com_http('http://weather.yahooapis.com/forecastrss?w=' . urlencode($this->getConfiguration('city')) . '&u=c');
         $xmlMeteo = $request->exec(5000, 0);
         cache::set('yahooWeatherXml' . $this->getConfiguration('city'), $xmlMeteo, 7200);
     } else {
         $xmlMeteo = $cache->getValue();
     }
     return self::parseXmlWeather($xmlMeteo);
 }
Exemple #16
0
         $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']) {
                     cache::set($log_id, $log['text']);
                 }
             }
         }
     }
     $body .= '<tr>' . '<td class="minimal">' . ($log['username'] ? '<a href="?/new_PM/' . $log['id'] . '">' . $log['username'] . '</a>' : '<em>' . ($log['id'] < 0 ? 'system' : 'deleted?') . '</em>') . '</td>' . '<td class="minimal">' . ($log['id'] < 0 ? '&ndash;' : '<a href="?/IP/' . $log['ip'] . '">' . $log['ip'] . '</a>') . '</td>' . '<td class="minimal">' . ago($log['time']) . '</td>' . '<td class="minimal">' . ($log['board'] ? '<a href="?/' . sprintf($config['board_path'], $log['board']) . $config['file_index'] . '">' . sprintf($config['board_abbreviation'], $log['board']) . '</a></td>' : '-') . '<td>' . $log['text'] . '</td>' . '</tr>';
 }
 $body .= '</table>';
 $query = prepare("SELECT COUNT(*) AS `count` FROM `modlogs`");
 $query->execute() or error(db_error($query));
 $count = $query->fetch();
 $body .= '<p class="unimportant" style="text-align:center;word-wrap:break-word">';
 for ($x = 0; $x < $count['count'] / $config['mod']['modlog_page']; $x++) {
     $body .= '<a href="?/log/' . ($x + 1) . '">[' . ($x + 1) . ']</a> ';
 }
 $body .= '</p>';
 /**
  * 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!');
     }
 }
 /**
  * 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;
             }
         }
     }
 }
Exemple #19
0
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;
}
 public function headnav($roleid)
 {
     $adminheav = 'admin_heav' . '_' . $roleid;
     if (is_cache($adminheav, 'admin/admin_heav')) {
         echo cache::get($adminheav, 'admin/admin_heav');
     } else {
         $markarr = model('admin_menu')->where('roleid', $roleid)->leftjoin('admin_role_priv', 'admin_menu.menuid', 'admin_role_priv.menuid')->select('markname')->group('markname')->query();
         if ($roleid == 1) {
             $markarr = model('admin_menu')->leftjoin('admin_role_priv', 'admin_menu.menuid', 'admin_role_priv.menuid')->select('markname')->group('markname')->query();
         } else {
             $markarr = model('admin_menu')->where('roleid', $roleid)->leftjoin('admin_role_priv', 'admin_menu.menuid', 'admin_role_priv.menuid')->select('markname')->group('markname')->query();
         }
         $nav = array();
         foreach ($markarr as $mark) {
             //print_r($mark);
             if ($mark['markname'] == 'index') {
                 $nav[$mark['markname']] = '<li class="nav-item dl-selected"><div class="nav-item-inner nav-home">我的面板</div></li>';
             }
             if ($mark['markname'] == 'content') {
                 $nav[$mark['markname']] = '<li class="nav-item"><div class="nav-item-inner nav-order">内容管理</div></li>';
             }
             //                if ($mark['markname'] == 'module')
             //                    $nav[$mark['markname']] = '<li class="nav-item"><div class="nav-item-inner nav-package">模块管理</div></li>';
             if ($mark['markname'] == 'package') {
                 $nav[$mark['markname']] = '<li class="nav-item"><div class="nav-item-inner nav-inventory">拓展管理</div></li>';
             }
             if ($mark['markname'] == 'member') {
                 $nav[$mark['markname']] = '<li class="nav-item"><div class="nav-item-inner nav-user">用户管理</div></li>';
             }
         }
         //print_r($nav);
         $headnav = '';
         $headnav .= isset($nav['index']) ? $nav['index'] : '';
         $headnav .= isset($nav['content']) ? $nav['content'] : '';
         //     $headnav .= isset($nav['module']) ? $nav['module'] : '';  //隐藏掉
         //   $headnav .= isset($nav['member']) ? $nav['member'] : '';
         $headnav .= isset($nav['package']) ? $nav['package'] : '';
         echo $headnav;
         cache::set($adminheav, $headnav, 'admin/admin_heav');
     }
 }
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;
}
Exemple #22
0
 public function toHtml($_version)
 {
     if (!$this->hasRight('r')) {
         return '';
     }
     $sql = 'SELECT `value` FROM cache
 WHERE `key`="scenarioHtml' . $_version . $this->getId() . '"';
     $result = DB::Prepare($sql, array(), DB::FETCH_TYPE_ROW);
     if ($result['value'] != '') {
         return $result['value'];
     }
     $_version = jeedom::versionAlias($_version);
     $replace = array('#id#' => $this->getId(), '#state#' => $this->getState(), '#isActive#' => $this->getIsActive(), '#name#' => $this->getDisplay('name') != '' ? $this->getDisplay('name') : $this->getHumanName(), '#icon#' => $this->getIcon(), '#lastLaunch#' => $this->getLastLaunch(), '#scenarioLink#' => $this->getLinkToConfiguration());
     if (!isset(self::$_templateArray)) {
         self::$_templateArray = array();
     }
     if (!isset(self::$_templateArray[$_version])) {
         self::$_templateArray[$_version] = getTemplate('core', $_version, 'scenario');
     }
     $html = template_replace($replace, self::$_templateArray[$_version]);
     cache::set('scenarioHtml' . $_version . $this->getId(), $html, 0);
     return $html;
 }
Exemple #23
0
 public function actionSetcache()
 {
     $cache = new \cache();
     $cacheKey = 'myframe_k1';
     return $cache->set($cacheKey, 'xuyonglin', 30);
 }
Exemple #24
0
    if (!$page->title && $mod != 'home') {
        if ($msg[$mod]) {
            $page->title = $msg[$mod];
        }
        if ($_GET['phrase']) {
            $page->title = $_GET['phrase'] . ' ~ ' . $page->title;
        }
    }
    $title = $page->title ? $page->title . ' ~ ' . $title : $title;
    $keywords = $page->get_keywords();
    $description = $page->get_description();
    $padding_top = $mod == 'home' ? 70 : 50;
    foreach ($vars as $var) {
        $cachedData[$var] = ${$var};
    }
    $cache->set($cachedData);
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php 
echo $title;
?>
</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="google-site-verification" content="zmQCyhcE8Z9CoamZld4k96jVIhDONOmLkiQeFJWjK-w" />
<?php 
if ($keywords) {
Exemple #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;
 }
Exemple #26
0
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);
}
 /**
  * Sends a key => value pair to the cache.
  *
  * <code>
  * // This code will add four entries to the cache, one for each url.
  * $cache->set('main', 'http://moodle.org');
  * $cache->set('docs', 'http://docs.moodle.org');
  * $cache->set('tracker', 'http://tracker.moodle.org');
  * $cache->set('qa', 'http://qa.moodle.net');
  * </code>
  *
  * @param string|int $key The key for the data being requested.
  * @param mixed $data The data to set against the key.
  * @return bool True on success, false otherwise.
  */
 public function set($key, $data)
 {
     if ($this->requirelockingwrite && !$this->acquire_lock($key)) {
         return false;
     }
     $result = parent::set($key, $data);
     if ($this->requirelockingwrite && !$this->release_lock($key)) {
         debugging('Failed to release cache lock on set operation... this should not happen.', DEBUG_DEVELOPER);
     }
     return $result;
 }
Exemple #28
0
function core_getLink($text, $action = False, $img = False, $resetCount = False, $returnButtonOnly = False)
{
    global $core_getLinkCount;
    if ($_GET["modal"] == 'yes') {
        return '';
    }
    $cache = new cache();
    $cache->ignoreKey = True;
    if ($resetCount) {
        $core_getLinkCount = 0;
        $cache->reset('core_getLink');
    }
    $cache->wasSet('core_getLink', $text);
    $cache->set($action);
    $core_getLinkCount++;
    if ($action) {
        if (file_exists("../{$action}") && !file_exists("{$action}")) {
            $action = "../{$action}";
        }
    }
    $button = "[&nbsp;" . ($img ? "<img src='{$img}' border='0' alt='' valign='botton'>" : "") . eregi_replace(" ", "&nbsp;", "{$text} ] ");
    if ($returnButtonOnly) {
        return "&nbsp;" . $button;
    } else {
        return x("span class='only_online'", "    &nbsp;" . x("a class='core_a' href='" . eregi_replace("'", '"', $action) . "'", $button));
    }
}
Exemple #29
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 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);
 }
Exemple #30
0
 /**
  * Saves the session data.
  *
  * This function also updates the last access time.
  *
  * @param array $session
  * @return bool
  */
 protected function save_session(array $session)
 {
     $session['lastaccess'] = time();
     $this->session = $session;
     return parent::set($this->sessionid, $this->session);
 }