/** * Constructor * * @param mixed $source * @param array $params */ public function __construct($source, $params = array()) { $this->source = $this->result = is_a($source, 'Media') ? $source : new Media($source); $this->options = array_merge(static::$defaults, $this->params($params)); $this->destination = $this->destination(); // don't create the thumbnail if it's not necessary if ($this->isObsolete()) { return; } // don't create the thumbnail if it exists if (!$this->isThere()) { // try to create the thumb folder if it is not there yet dir::make(dirname($this->destination->root)); // check for a valid image if (!$this->source->exists() || $this->source->type() != 'image') { throw new Error('The given image is invalid', static::ERROR_INVALID_IMAGE); } // check for a valid driver if (!array_key_exists($this->options['driver'], static::$drivers)) { throw new Error('Invalid thumbnail driver', static::ERROR_INVALID_DRIVER); } // create the thumbnail $this->create(); // check if creating the thumbnail failed if (!file_exists($this->destination->root)) { return; } } // create the result object $this->result = new Media($this->destination->root, $this->destination->url); }
protected function checkAvatars() { $root = kirby()->roots()->avatars(); // try to create the avatars folder dir::make($root); return is_writable($root); }
protected function setUp() { // create the test root dir::make($this->root); // set up a new library $this->library(); }
public function testSize() { dir::make($this->tmpDir); f::write($this->tmpDir . DS . 'testfile-1.txt', str::random(5)); f::write($this->tmpDir . DS . 'testfile-2.txt', str::random(5)); f::write($this->tmpDir . DS . 'testfile-3.txt', str::random(5)); $this->assertEquals(15, dir::size($this->tmpDir)); $this->assertEquals('15 b', dir::niceSize($this->tmpDir)); dir::remove($this->tmpDir); }
/** * Creates a new file * * <code> * * f::write('test.txt', 'hello'); * // creates a new text file with hello as content * * // create a new file * f::write('text.txt', array('test' => 'hello')); * // creates a new file and encodes the array as json * * </code> * * @param string $file The path for the new file * @param mixed $content Either a string, an object or an array. Arrays and objects will be serialized. * @param boolean $append true: append the content to an exisiting file if available. false: overwrite. * @return boolean */ public static function write($file, $content, $append = false) { if (is_array($content) or is_object($content)) { $content = serialize($content); } $mode = $append ? FILE_APPEND | LOCK_EX : LOCK_EX; // if the parent directory does not exist, create it if (!is_dir(dirname($file))) { if (!dir::make(dirname($file))) { return false; } } return @file_put_contents($file, $content, $mode) !== false ? true : false; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; if (!$this->isInstalled()) { throw new RuntimeException('Invalid Kirby installation'); } $this->bootstrap(); // check if the thing already exists if ($this->exists()) { throw new RuntimeException('The ' . $this->what . ' exists and cannot be overwritten'); } // make sure the directory exists dir::make($this->dest()); $this->copy(); $this->info(); }
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; }
public function __construct() { $roots = array('tests' => dirname(__DIR__), 'panel' => dirname(dirname(__DIR__)), 'index' => dirname(dirname(dirname(__DIR__))), 'kirby' => dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'kirby', 'dummy' => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'dummy'); // load kirby require_once $roots['kirby'] . DIRECTORY_SEPARATOR . 'bootstrap.php'; // make sure to start a session s::start(); // create the dummy content directory dir::make($roots['dummy'] . DS . 'content'); // create the roots object $this->roots = new Obj($roots); // load the panel require_once $roots['panel'] . DS . 'app' . DS . 'bootstrap.php'; // initiate kirby $this->kirby = new Kirby(); $this->kirby->roots->content = $this->roots->dummy . DS . 'content'; $this->kirby->roots->site = $this->roots->dummy . DS . 'site'; // initiate the panel $this->panel = new Panel($this->kirby, $this->roots->panel); // store the site instance $this->site = $this->panel->site(); }
function flickrbadge($params = array()) { $defaults = array('key' => false, 'username' => false, 'limit' => 10, 'format' => 'square', 'cache' => true, 'refresh' => 60 * 60 * 2); $options = array_merge($defaults, $params); // check the cache dir $cacheDir = c::get('root.cache') . '/flickrbadge'; dir::make($cacheDir); // disable the cache if adding the cache dir failed if (!is_dir($cacheDir) || !is_writable($cacheDir)) { $options['cache'] = false; } if (!$options['key']) { return false; } if (!$options['username']) { return false; } $cacheID = 'flickrbadge/data.' . md5(serialize($options)) . '.php'; if ($options['cache']) { $cache = cache::modified($cacheID) < time() - $options['refresh'] ? false : cache::get($cacheID); } else { $cache = false; } if (!empty($cache)) { return $cache; } $flickr = new phpFlickr($options['key']); $userCacheID = 'flickrbadge/user.' . md5($options['username']) . '.php'; $userCache = $options['cache'] ? cache::get($userCacheID) : false; $user = false; $url = false; if (!empty($userCache)) { $user = a::get($userCache, 'user'); $url = a::get($userCache, 'url'); } if (!$user || !$url) { $user = $flickr->people_findByUsername($options['username']); $url = $flickr->urls_getUserPhotos($user['id']); if ($options['cache']) { cache::set($userCacheID, array('user' => $user, 'url' => $url)); } } $photos = $flickr->people_getPublicPhotos($user['id'], NULL, NULL, $options['limit']); $result = array(); foreach ($photos['photos']['photo'] as $photo) { $photoCacheID = 'flickrbadge/photo.' . $photo['id'] . '.php'; $info = $options['cache'] ? cache::get($photoCacheID) : false; if (empty($info)) { $info = $flickr->photos_getInfo($photo['id']); if ($options['cache']) { cache::set($photoCacheID, $info); } } $info = a::get($info, 'photo', array()); $dates = a::get($info, 'dates', array()); $tags = array(); foreach ((array) $info['tags']['tag'] as $t) { if (!empty($t['raw']) && !$t['machine_tag']) { $tags[] = $t['raw']; } } $result[] = new obj(array('url' => $url . $photo['id'], 'title' => a::get($info, 'title', $photo['title']), 'description' => @$info['description'], 'src' => $flickr->buildPhotoURL($photo, $options['format']), 'taken' => isset($dates['taken']) ? strtotime($dates['taken']) : false, 'posted' => isset($dates['posted']) ? $dates['posted'] : false, 'lastupdate' => isset($dates['lastupdate']) ? $dates['lastupdate'] : false, 'views' => a::get($info, 'views', 0), 'comments' => a::get($info, 'comments', 0), 'tags' => $tags)); } $result = new obj($result); if ($options['cache']) { cache::set($cacheID, $result); } return $result; }
public function hasSessionResultsFolder() { //if results' folder in session folder exists or is succesfully created if (dir::make($this->resultsFolderPath)) { //return true return true; } else { //add error: session doesn't have a results folder, nor it was possible to create it $this->addError('session.fail.update'); } //return false return false; }
/** * 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!'); } }
// page or site kirby()->site()->visit(); if (strlen($path) !== 0) { $page = kirby()->site()->find($path); } else { $page = kirby()->site(); } if ($page && ($image = $page->file($filename . $extension))) { $modified = substr(md5($image->modified()), 0, 12); if ($modified === $hash) { // thumb root $path = str_replace('/', DS, $page->id()); $root = kirby()->roots()->index() . DS . 'thumbs' . DS . $path; // create directories if necessary if (!f::exists($root)) { dir::make($root, true); } // thumb url $url = kirby()->urls()->index() . '/thumbs/' . $page->id(); // create thumb $thumb = thumb($image, array('destination' => true, 'width' => $width, 'filename' => '{safeName}-{width}-' . $modified . '.{extension}', 'root' => $root, 'url' => $url)); // send headers header::type($image->mime()); header('Cache-control: max-age=' . 60 * 60 * 24 * 365); header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365)); // read file function readFileChunked($filename, $retbytes = true) { $chunkSize = 8192; $buffer = ''; $cnt = 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; } } } }
if (empty($post['title']) || empty($post['slug'])) { $errors[] = $post; continue; } $output[] = 'title: ' . $post['title']; $output[] = 'date: ' . date($dateformat, $post['date']); $output[] = 'text: ' . "\n\n" . trim($post['text']); $output[] = 'tags: ' . $post['tags']; $output[] = 'categories: ' . $post['cats']; $name = pad($n, $len) . '-' . f::safe_name($post['slug']); $dir = $root . '/' . $name; if (is_dir($dir)) { $skipped[] = basename($dir); continue; } dir::make($dir); $content = implode("\n\n" . '----' . "\n\n", $output); $file = $dir . '/' . $template; f::write($file, $content); } putmessage('Exported ' . $n . ' articles to ' . $root . '<br /><br />'); if (!empty($errors)) { putmessage(count($errors) . ' article(s) could not be imported<br /><br />'); } if (!empty($skipped)) { putmessage('The following folders have been skipped, because they already existed:' . a::show($skipped, false)); } /** * IXR - The Inutio XML-RPC Library * * @package IXR
function tweets($username, $params = array()) { $defaults = array('limit' => 10, 'cache' => true, 'hiderep' => false, '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; } // Encode the key and secret from the Twitter config. $twitterKey = urlencode(c::get('twitter.key')); $twitterSecret = urlencode(c::get('twitter.secret')); // combine and base64 encode the key and secret with a colon seperator $twitterCode = base64_encode($twitterKey . ':' . $twitterSecret); // obtain a bearer token from the api, by building a request //url to use $url = 'https://api.twitter.com/oauth2/token'; //create header $header = array('http' => array('method' => "POST", 'header' => "Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n" . "Authorization: Basic " . $twitterCode . "\r\n", 'content' => "grant_type=client_credentials")); //send the request $context = stream_context_create($header); $bearer = file_get_contents($url, false, $context); // decode the json response $bearer = json_decode($bearer); // send the rquest for tweets $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $options['username'] . '&count=' . $options['limit'] . '&include_rts=true' . '&exclude_replies=' . $options['hiderep']; $header = array('http' => array('method' => "GET", 'header' => "Authorization: Bearer " . $bearer->access_token . "\r\n")); $context = stream_context_create($header); $json = file_get_contents($url, false, $context); $data = json_decode($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; }
/** * Private method to create a page directory */ protected static function createDirectory($uri) { $uid = str::slug(basename($uri)); $parentURI = dirname($uri); $parent = ($parentURI == '.' or empty($parentURI) or $parentURI == DS) ? site() : page($parentURI); if (!$parent) { throw new Exception('The parent does not exist'); } // check for an entered sorting number if (preg_match('!^(\\d+)\\-(.*)!', $uid, $matches)) { $num = $matches[1]; $uid = $matches[2]; $dir = $num . '-' . $uid; } else { $num = false; $dir = $uid; } // make sure to check a fresh page $parent->reset(); if ($parent->children()->findBy('uid', $uid)) { throw new Exception('The page UID exists'); } if (!dir::make($parent->root() . DS . $dir)) { throw new Exception('The directory could not be created'); } // make sure the new directory is available everywhere $parent->reset(); return $parent->id() . '/' . $uid; }
static function addContent() { global $page, $pages, $site; $uid = get('uid'); $title = get('title'); $tpl = get('template', 'default'); $data = self::fetchData($tpl, array('title' => $title)); if (empty($title)) { return array('status' => 'error', 'msg' => l::get('pages.add.errors.title')); } // build a urlified uid if (empty($uid)) { $uid = str::urlify($title); } if (empty($uid)) { return array('status' => 'error', 'msg' => l::get('pages.add.errors.url')); } if (!preg_match('!^[a-z0-9-_]+$!i', $uid)) { return array('status' => 'error', 'msg' => l::get('pages.add.errors.characters')); } $check = self::childByUID($uid); if ($check) { return array('status' => 'error', 'msg' => l::get('pages.add.errors.exists') . ': ' . $uid); } if (!$site->uri->path(1)) { $dir = c::get('root.content') . '/' . $uid; $url = url($uid); } else { $dir = $page->root() . '/' . $uid; $url = $page->url() . '/' . $uid; } if (!dir::make($dir)) { return array('status' => 'error', 'msg' => l::get('pages.add.errors.permissions')); } if (c::get('lang.support')) { foreach (c::get('lang.available') as $lang) { $file = $dir . '/' . $tpl . '.' . $lang . '.txt'; $write = data::write($file, $data); if (error($write)) { return $write; } } } else { // write the default file $file = $dir . '/' . $tpl . '.txt'; $write = data::write($file, $data); if (error($write)) { return $write; } } self::killCache(); return array('status' => 'success', 'msg' => l::get('pages.add.success'), 'url' => $url); }
protected function prepare() { // check for an existing field with the same name if (!$this->sourceExists()) { throw new RuntimeException('The correct source for the plugin is missing'); } dir::make(dirname($this->destination())); }
protected function relocate() { if ($this->old['created'] == $this->data['created']) { return; } $old = clone $this; $old->created = $this->old['created']; if (!$old->exists()) { return; } if (!dir::make($this->root())) { throw new Exception('The new directory could not be created'); } if (!dir::move($old->root(), $this->root())) { throw new Exception('The directory could not be moved'); } $this->library->clean($old->root('day')); }
/** * Creates the directory if it does not exist yet * * @param boolean $recursive * @return boolean */ public function make($recursive = true) { return dir::make($this->root, $recursive); }
function tweets($username, $params = array()) { $defaults = array('limit' => 10, 'cache' => true, 'hiderep' => false, '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'; /** * Below is Studio Dumbar's take on the Cache functionality * Implemented because we want to bypass the global Kirby caching system */ // Check is the caching option is set if ($options['cache']) { // Get cache file and modified times $cacheFile = c::get('root.cache') . '/' . $cacheID; $cacheModTime = filemtime($cacheFile); $timeago = time() - $options["refresh"]; if ($cacheModTime < $timeago) { // File is too old, set a refresh flag $updateCache = true; } else { // File is within cache time limit, set don't update cache flag $updateCache = false; // Get the cache string from the file, using Kirby toolkit file method $cache = @unserialize(f::read($cacheFile)); } } else { $cache = false; } // If cache variable is not empty, return the cache! if (!empty($cache)) { return $cache; } // Encode the key and secret from the Twitter config. $twitterKey = urlencode(c::get('twitter.key')); $twitterSecret = urlencode(c::get('twitter.secret')); // combine and base64 encode the key and secret with a colon seperator $twitterCode = base64_encode($twitterKey . ':' . $twitterSecret); // obtain a bearer token from the api, by building a request //url to use $url = 'https://api.twitter.com/oauth2/token'; //create header $header = array('http' => array('method' => "POST", 'header' => "Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n" . "Authorization: Basic " . $twitterCode . "\r\n", 'content' => "grant_type=client_credentials")); //send the request $context = stream_context_create($header); $bearer = file_get_contents($url, false, $context); // decode the json response $bearer = json_decode($bearer); // send the rquest for tweets $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $options['username'] . '&count=' . $options['limit'] . '&include_rts=true' . '&exclude_replies=' . $options['hiderep']; $header = array('http' => array('method' => "GET", 'header' => "Authorization: Bearer " . $bearer->access_token . "\r\n")); $context = stream_context_create($header); $json = file_get_contents($url, false, $context); $data = json_decode($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); /** * Below is Studio Dumbar's take on writing new cache * Implemented because we want to bypass the global Kirby caching system */ // If the cache option is set, and the flag to update cache is set if ($options['cache'] && $updateCache) { // Open the cacheFile $fp = fopen($cacheFile, 'w'); // Check if file isn't locked if (flock($fp, LOCK_EX)) { // Write the serialized $result object into the fi;e fwrite($fp, @serialize($result)); // Unlock file flock($fp, LOCK_EX); } // Close the cacheFile fclose($fp); } return $result; }