PageRenderTime 77ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/pi.tweetline.php

https://bitbucket.org/codesly/tweetline
PHP | 289 lines | 216 code | 25 blank | 48 comment | 24 complexity | 0ff5f99d9a18a095c814a09955ad4e62 MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /*
  3. ========================================================
  4. Plugin TweetLine Version 2.3
  5. --------------------------------------------------------
  6. Copyright: David Dexter (Brilliant2.com)
  7. License: Absolutely Freeware - Use It and Abuse It....
  8. http://www.brilliant2.com
  9. --------------------------------------------------------
  10. This addon may be used free of charge. Should you have
  11. the opportunity to use it for commercial projects then
  12. I applaud you!
  13. ========================================================
  14. File: pi.tweetline.php
  15. --------------------------------------------------------
  16. Purpose: Grab a feed from twitter for a give user
  17. ========================================================
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
  19. ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
  20. LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  21. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
  22. EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  23. FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  24. AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  26. OR OTHER DEALINGS IN THE SOFTWARE.
  27. ========================================================
  28. */
  29. $plugin_info = array( 'pi_name' => 'TweetLine',
  30. 'pi_version' => '2.3',
  31. 'pi_author' => 'David Dexter',
  32. 'pi_author_url' => 'http://www.brilliant2.com',
  33. 'pi_description' => 'TweetLine returns a set of status tweets for a given user. Developed for EE 2.0+ (Requires Curl on the server)',
  34. 'pi_usage' => tweetline::usage());
  35. class Tweetline
  36. {
  37. var $return_data;
  38. var $cache = '';
  39. function tweetline()
  40. {
  41. $this->EE =& get_instance();
  42. // Cache path
  43. $this->cache = rtrim(APPPATH,"/").'/cache/tweetline/';
  44. if(!file_exists($this->cache)){
  45. mkdir($this->cache);
  46. }
  47. // Get the username
  48. $username = ( ! $this->EE->TMPL->fetch_param('username')) ? 'brilliant2' : strtolower($this->EE->TMPL->fetch_param('username'));
  49. if($username == ''){
  50. $username = 'brilliantretail';
  51. }
  52. // Show retweets and mentions?
  53. $retweets = ( ! $this->EE->TMPL->fetch_param('retweets')) ? 'yes' : strtolower($this->EE->TMPL->fetch_param('retweets'));
  54. $mentions = ( ! $this->EE->TMPL->fetch_param('mentions')) ? 'yes' : strtolower($this->EE->TMPL->fetch_param('mentions'));
  55. // Automatically format linsk?
  56. $auto_format = ( ! $this->EE->TMPL->fetch_param('format')) ? 'no' : strtolower($this->EE->TMPL->fetch_param('format'));
  57. // What's the limit?
  58. $limit = ( ! $this->EE->TMPL->fetch_param('limit')) ? 5 : $this->EE->TMPL->fetch_param('limit');
  59. // What is the cache time in minutes
  60. // The value can't be less than 3 due to
  61. // Twitters restriction on API calls per hour
  62. $cache_time = ( ! $this->EE->TMPL->fetch_param('cache')) ? 10 : $this->EE->TMPL->fetch_param('cache');
  63. if($cache_time < 3){
  64. $cache_time = 3;
  65. }
  66. // Lets check the cache
  67. $content = $this->_check_cache($this->cache.'tweetline.'.$username.'.cache');
  68. $content = @unserialize($content);
  69. if($content !== false){
  70. $tm = (time() - $content["cachestamp"]) / 60;
  71. if($tm <= $cache_time){
  72. unset($content["cachestamp"]);
  73. $xml = $content;
  74. }
  75. }
  76. if(!isset($xml)){
  77. // Get the rss feed from twitter rest api
  78. // I used the rss format so that RT's are
  79. // not stripped out.
  80. $url = 'http://api.twitter.com/1/statuses/user_timeline/'.$username.'.rss';
  81. $curl = curl_init();
  82. curl_setopt ($curl, CURLOPT_URL, $url);
  83. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  84. $result = curl_exec($curl);
  85. curl_close($curl);
  86. $xml = $this->simpleXMLToArray(simplexml_load_string($result));
  87. // Save the results to cache
  88. $this->_save_cache($this->cache.'tweetline.'.$username.'.cache',$xml);
  89. }
  90. // Set an empty $variables array just in case there
  91. // is an issue with Twitter
  92. if(isset($xml["error"])){
  93. $variables[0] = array(
  94. 'post' => '',
  95. 'link' => '',
  96. 'date' => '',
  97. 'rel_date' => ''
  98. );
  99. }else{
  100. // Build the parse variables
  101. $i = 1;
  102. foreach($xml["channel"]["item"] as $items){
  103. $show = true;
  104. $post = substr($items["title"],strlen($username)+2);
  105. if(substr($post,0,1) == '@'){
  106. if($mentions != 'yes'){
  107. $show = false;
  108. }
  109. }else if(substr($post,0,2) == 'RT'){
  110. if($retweets != 'yes'){
  111. $show = false;
  112. }
  113. }
  114. if($show == true){
  115. if($i <= $limit){
  116. $link = (array)$items["link"];
  117. $post = substr($items["title"],strlen($username)+2);
  118. if($auto_format == 'yes'){
  119. $post = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $post);
  120. $post = preg_replace("/@(\w+)/", '<a href="http://www.twitter.com/\1" target="_blank">@\\1</a>', $post);
  121. $post = preg_replace("/#(\w+)/", '<a href="http://search.twitter.com/search?q=\1" target="_blank">#\\1</a>', $post);
  122. }
  123. $variables[] = array(
  124. 'post' => $post,
  125. 'link' => $link[0],
  126. 'date' => date("U",strtotime($items["pubDate"])),
  127. 'rel_date' => $this->_build_relative_time(date("U",strtotime($items["pubDate"])))
  128. );
  129. }
  130. $i++;
  131. }
  132. }
  133. }
  134. // Parse the goodness
  135. $output = $this->EE->TMPL->parse_variables($this->EE->TMPL->tagdata, $variables);
  136. $this->return_data = $output;
  137. }
  138. function _check_cache($fl){
  139. if(file_exists($fl)){
  140. $fh = fopen($fl,'r');
  141. $content = fread($fh, filesize($fl));
  142. return $content;
  143. }else{
  144. return false;
  145. }
  146. }
  147. function _save_cache($fl,$vars){
  148. $vars['cachestamp'] = time();
  149. $fh = fopen($fl, 'w') or die("can't open tweetline cache file");
  150. $str = serialize($vars);
  151. fwrite($fh, $str);
  152. fclose($fh);
  153. return true;
  154. }
  155. function _build_relative_time($time){
  156. $diff = time() - $time;
  157. if ($diff < 60) {
  158. return 'less than a minute ago';
  159. }else if($diff < 120) {
  160. return 'about a minute ago';
  161. }else if($diff < (60*60)) {
  162. return round($diff / 60,0) . ' minutes ago';
  163. }else if($diff < (120*60)) {
  164. return 'about an hour ago';
  165. } else if($diff < (24*60*60)) {
  166. return 'about ' + round($diff / 3600,0) . ' hours ago';
  167. } else if($diff < (48*60*60)) {
  168. return '1 day ago';
  169. } else {
  170. return round($diff / 86400,0) . ' days ago';
  171. }
  172. }
  173. function simpleXMLToArray($xml,
  174. $flattenValues=true,
  175. $flattenAttributes = true,
  176. $flattenChildren=true,
  177. $valueKey='@value',
  178. $attributesKey='@attributes',
  179. $childrenKey='@children'){
  180. $return = array();
  181. if(!($xml instanceof SimpleXMLElement)){return $return;}
  182. $name = $xml->getName();
  183. $_value = trim((string)$xml);
  184. if(strlen($_value)==0){$_value = null;};
  185. if($_value!==null){
  186. if(!$flattenValues){$return[$valueKey] = $_value;}
  187. else{$return = $_value;}
  188. }
  189. $children = array();
  190. $first = true;
  191. foreach($xml->children() as $elementName => $child){
  192. $value = $this->simpleXMLToArray($child, $flattenValues, $flattenAttributes, $flattenChildren, $valueKey, $attributesKey, $childrenKey);
  193. if(isset($children[$elementName])){
  194. if($first){
  195. $temp = $children[$elementName];
  196. unset($children[$elementName]);
  197. $children[$elementName][] = $temp;
  198. $first=false;
  199. }
  200. $children[$elementName][] = $value;
  201. }
  202. else{
  203. $children[$elementName] = $value;
  204. }
  205. }
  206. if(count($children)>0){
  207. if(!$flattenChildren){$return[$childrenKey] = $children;}
  208. else{$return = array_merge($return,$children);}
  209. }
  210. $attributes = array();
  211. foreach($xml->attributes() as $name=>$value){
  212. $attributes[$name] = trim($value);
  213. }
  214. if(count($attributes)>0){
  215. if(!$flattenAttributes){$return[$attributesKey] = $attributes;}
  216. else{$return = array_merge($return, $attributes);}
  217. }
  218. return $return;
  219. }
  220. function usage(){
  221. ob_start();
  222. ?>
  223. Example:
  224. ----------------
  225. {exp:tweetline username="brilliant2" limit="5" mentions="false" retweets="false"}
  226. <p>
  227. <a href="{link}" target="_blank">{post}</a><br />
  228. {date format="%M %d, %Y %g:%i%a"} {rel_date}
  229. </p>
  230. {/exp:tweetline}
  231. Parameters:
  232. ----------------
  233. username: Twitter username.
  234. limit: The maximum number of tweets to pull
  235. format (Default "no") - If yes then auto link pounds(#), ats (@), and http
  236. retweets: (Default "yes") - If false then retweets (RT) will be removed
  237. mentions: (Default "yes") - If false then mentions (@'s) will be removed
  238. Cache: (Default 10) How long to store the cache API request in minutes. The minimum value is 3 due to API restrictions at Twitter.
  239. Tags:
  240. ----------------
  241. link: Link to post on twitter
  242. post: Title of the post
  243. date: Date the post was added (accepts format parameter)
  244. rel_date: Returns the data in a relative format (i.e. '1 day ago', 'about an hour ago')
  245. count / total_results / switch are available by system default
  246. <?php
  247. $buffer = ob_get_contents();
  248. ob_end_clean();
  249. return $buffer;
  250. }
  251. /* END */
  252. }
  253. /* END Class */
  254. /* End of file pi.tweetline.php */
  255. /* Location: ./system/expressionengine/third_party/tweetline/pi.tweetline.php */