Created
November 7, 2010 21:03
-
-
Save evansd/666788 to your computer and use it in GitHub Desktop.
WordPress plugin for embedding gists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| Plugin Name: Gist Embed | |
| Description: Embed Gists from Github with robust caching | |
| Author: David Evans | |
| Version: 0.1 | |
| */ | |
| function robust_cache($callback, $args, $key, $success_retry, $failure_retry, $expire) | |
| { | |
| $data = get_transient($key); | |
| if ($data) | |
| { | |
| // If the last result is still valid just return it | |
| if (isset($data['next_attempt']) AND $data['next_attempt'] > time()) | |
| { | |
| return $data['result']; | |
| } | |
| } | |
| // If there's no cached result, initialize | |
| else | |
| { | |
| $data = array('result' => FALSE); | |
| } | |
| $result = call_user_func_array($callback, (array) $args); | |
| if ($result !== FALSE) | |
| { | |
| $data['next_attempt'] = time() + $success_retry; | |
| $data['result'] = $result; | |
| } | |
| else | |
| { | |
| $data['next_attempt'] = time() + $failure_retry; | |
| } | |
| set_transient($key, $data, $expires); | |
| return $data['result']; | |
| } | |
| function gist_embed_fetch_html($id) | |
| { | |
| $context = stream_context_create(array('http' => array | |
| ( | |
| 'timeout' => 2 | |
| ))); | |
| $response = @file_get_contents("http://gist.github.com/$id.json", 0, $context); | |
| if ($response) | |
| { | |
| $response = @json_decode($response); | |
| return empty($response->div) ? FALSE : $response->div; | |
| } | |
| return FALSE; | |
| } | |
| function gist_embed_shortcode($atts) | |
| { | |
| if (empty($atts['id'])) return NULL; | |
| return robust_cache | |
| ( | |
| 'gist_embed_fetch_html', | |
| $atts['id'], | |
| 'gist_embed_'.$atts['id'], | |
| // Retry 24 hours after success | |
| 24 * 60 * 60, | |
| // Retry 1 hour after failure | |
| 60 * 60, | |
| // Expire cache if it's not touched for 120 days | |
| 120 * 24 * 60 * 60 | |
| ); | |
| } | |
| add_shortcode('gist', 'gist_embed_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment