PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/inc/core.php

https://github.com/dshafik/wp-lifestream
PHP | 2783 lines | 2311 code | 250 blank | 222 comment | 257 complexity | 777786d487d841862154389770d25cb5 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. if (!class_exists('SimplePie'))
  3. {
  4. require_once(LIFESTREAM_PATH . '/lib/simplepie.inc.php');
  5. }
  6. global $wpdb, $userdata, $lifestream;
  7. function lifestream_path_join()
  8. {
  9. $bits = func_get_args();
  10. $sep = (in_array(PHP_OS, array("WIN32", "WINNT")) ? '\\' : '/');
  11. foreach ($bits as $key=>$value) {
  12. $bits[$key] = rtrim($value, $sep);
  13. }
  14. return implode($sep, $bits);
  15. }
  16. function lifestream_array_key_pop($array, $key)
  17. {
  18. $value = @$array[$key];
  19. unset($array[$key]);
  20. return $value;
  21. }
  22. // Returns the utf string corresponding to the unicode value (from php.net, courtesy - romans@void.lv)
  23. function lifestream_code2utf($num)
  24. {
  25. if ($num < 128) return chr($num);
  26. if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  27. if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  28. if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  29. return '';
  30. }
  31. function lifestream_str_startswith($string, $chunk)
  32. {
  33. return substr($string, 0, strlen($chunk)) == $chunk;
  34. }
  35. function lifestream_str_endswith($string, $chunk)
  36. {
  37. return substr($string, strlen($chunk)*-1) == $chunk;
  38. }
  39. function lifestream_get_class_constant($class, $const)
  40. {
  41. return constant(sprintf('%s::%s', $class, $const));
  42. }
  43. class Lifestream_Error extends Exception { }
  44. class Lifestream_ValidationError extends Exception { }
  45. class Lifestream_FeedFetchError extends Lifestream_Error { }
  46. class Lifestream_Event
  47. {
  48. /**
  49. * Represents a single event in the database.
  50. */
  51. function __construct(&$lifestream, $row)
  52. {
  53. $this->lifestream = $lifestream;
  54. $this->date = $row->timestamp;
  55. $this->data = array(unserialize($row->data));
  56. $this->id = $row->id;
  57. $this->timestamp = $row->timestamp;
  58. $this->total = 1;
  59. $this->is_grouped = false;
  60. $this->key = $row->key;
  61. $this->owner = $row->owner;
  62. $this->owner_id = $row->owner_id;
  63. $this->visible = $row->visible;
  64. $this->link = @(!empty($this->data['link']) ? $this->data['link'] : $row->link);
  65. $cls = $this->lifestream->get_feed($row->feed);
  66. $this->feed = new $cls($this->lifestream, unserialize($row->options), $row->feed_id);
  67. }
  68. function __toString()
  69. {
  70. return $this->data[0]['title'];
  71. }
  72. function get_event_display()
  73. {
  74. return $this->feed->get_event_display($this, $this->data[0]);
  75. }
  76. function get_event_link()
  77. {
  78. return $this->feed->get_event_link($this, $this->data[0]);
  79. }
  80. function get_timesince()
  81. {
  82. return $this->lifestream->timesince($this->timestamp);
  83. }
  84. function get_date()
  85. {
  86. return $this->date + LIFESTREAM_DATE_OFFSET;
  87. }
  88. /**
  89. * Returns an HTML-ready string.
  90. */
  91. function render($options=array())
  92. {
  93. return $this->feed->render($this, $options);
  94. }
  95. function get_label_instance($options=array())
  96. {
  97. if (!isset($this->_label_instance))
  98. {
  99. $this->_label_instance = $this->feed->get_label($this, $options);
  100. }
  101. return $this->_label_instance;
  102. }
  103. function get_label($options=array())
  104. {
  105. $label_inst = $this->get_label_instance($options);
  106. if (count($this->data) > 1)
  107. {
  108. if (@$options['show_owners'] || $this->lifestream->get_option('show_owners'))
  109. {
  110. $label = $label_inst->get_label_plural_user();
  111. }
  112. else
  113. {
  114. $label = $label_inst->get_label_plural();
  115. }
  116. }
  117. else
  118. {
  119. if (@$options['show_owners'] || $this->lifestream->get_option('show_owners'))
  120. {
  121. $label = $label_inst->get_label_single_user();
  122. }
  123. else
  124. {
  125. $label = $label_inst->get_label_single();
  126. }
  127. }
  128. return $label;
  129. }
  130. function get_feed_label($options=array())
  131. {
  132. $label_inst = $this->get_label_instance($options);
  133. return $label_inst->get_feed_label();
  134. }
  135. function get_url()
  136. {
  137. if (count($this->data) > 1)
  138. {
  139. // return the public url if it's grouped
  140. $url = $this->feed->get_public_url();
  141. if ($url) return $url;
  142. }
  143. else
  144. {
  145. $url = $this->data[0]['link'];
  146. if ($url) return $url;
  147. }
  148. return '#';
  149. }
  150. }
  151. class Lifestream_EventGroup extends Lifestream_Event
  152. {
  153. /**
  154. * Represents a grouped event in the database.
  155. */
  156. function __construct(&$lifestream, $row)
  157. {
  158. parent::__construct($lifestream, $row);
  159. $this->total = $row->total ? $row->total : 1;
  160. $this->data = unserialize($row->data);
  161. $this->is_grouped = true;
  162. }
  163. function get_event_display($bit)
  164. {
  165. return $this->feed->get_event_display($this, $bit);
  166. }
  167. function get_event_link($bit)
  168. {
  169. return $this->feed->get_event_link($this, $bit);
  170. }
  171. }
  172. class Lifestream
  173. {
  174. // stores all registered feeds
  175. public $feeds = array();
  176. // stores file locations to feed classes
  177. public $paths = array();
  178. // stores theme information
  179. public $themes = array();
  180. // stores icon folder names
  181. public $icons = array();
  182. // current theme
  183. public $theme = 'default';
  184. protected $paging_key = 'ls_p';
  185. protected $valid_image_types = array('image/gif' => 'gif',
  186. 'image/jpeg' => 'jpeg',
  187. 'image/png' => 'png',
  188. 'image/gif' => 'gif',
  189. 'image/x-icon' => 'ico',
  190. 'image/bmp' => 'bmp',
  191. 'image/vnd.microsoft.icon' => 'ico'
  192. );
  193. protected $valid_image_extensions = array(
  194. 'gif', 'jpg', 'jpeg', 'gif', 'png', 'ico'
  195. );
  196. function html_entity_decode($string)
  197. {
  198. static $trans_tbl;
  199. // replace numeric entities
  200. $string = preg_replace('~&#x([0-9a-f]+);~ei', 'lifestream_code2utf(hexdec("\\1"))', $string);
  201. $string = preg_replace('~&#([0-9]+);~e', 'lifestream_code2utf(\\1)', $string);
  202. // replace literal entities
  203. if (!isset($trans_tbl))
  204. {
  205. $trans_tbl = array();
  206. foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
  207. $trans_tbl[$key] = utf8_encode($val);
  208. }
  209. return strtr($string, $trans_tbl);
  210. }
  211. // function html_entity_decode($string)
  212. // {
  213. // $string = html_entity_decode($string, ENT_QUOTES, 'utf-8');
  214. //
  215. // $string = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
  216. // $string = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $string);
  217. //
  218. // return $string;
  219. // }
  220. function parse_nfo_file($file)
  221. {
  222. $data = array();
  223. if (!is_file($file)) return $data;
  224. $fp = file($file);
  225. foreach ($fp as $line)
  226. {
  227. if (lifestream_str_startswith('#', $line)) continue;
  228. list($key, $value) = explode(':', $line, 2);
  229. $data[strtolower($key)] = trim($value);
  230. }
  231. return $data;
  232. }
  233. function get_icon_paths()
  234. {
  235. $directories = array(
  236. lifestream_path_join(LIFESTREAM_PATH, 'icons')
  237. );
  238. if ($this->get_option('icon_dir') && $this->get_option('icon_dir') != $directories[0]) {
  239. $directories[] = $this->get_option('icon_dir');
  240. }
  241. return $directories;
  242. }
  243. function get_rss_feed_url()
  244. {
  245. $permalink = get_option('permalink_structure');
  246. if (!empty($permalink))
  247. {
  248. $url = trailingslashit(get_bloginfo('rss2_url')) . 'lifestream-feed';
  249. }
  250. else {
  251. $url = trailingslashit(get_bloginfo('url')) . 'wp-rss2.php?feed=lifestream-feed';
  252. }
  253. return $url;
  254. }
  255. /**
  256. * Find each icons/name/generic.png file.
  257. */
  258. function detect_icons()
  259. {
  260. $directories = $this->get_icon_paths();
  261. foreach ($directories as $base_dir)
  262. {
  263. if (!is_dir($base_dir)) continue;
  264. $handler = opendir($base_dir);
  265. while ($file = readdir($handler))
  266. {
  267. // ignore hidden files
  268. if (lifestream_str_startswith($file, '.')) continue;
  269. // if its not a directory we dont care
  270. $path = lifestream_path_join($base_dir, $file);
  271. if (!is_dir($path)) continue;
  272. $ext_file = lifestream_path_join($path, 'generic.png');
  273. if (is_file($ext_file))
  274. {
  275. $data = $this->parse_nfo_file(lifestream_path_join($path, 'icons.txt'));
  276. if (!$data['name']) $data['name'] = $file;
  277. $data['__path'] = $path;
  278. $data['__url'] =
  279. $this->icons[$file] = $data;
  280. }
  281. }
  282. }
  283. }
  284. function get_extension_paths()
  285. {
  286. $directories = array(
  287. lifestream_path_join(LIFESTREAM_PATH, 'extensions')
  288. );
  289. if ($this->get_option('extension_dir') && $this->get_option('extension_dir') != $directories[0]) {
  290. $directories[] = $this->get_option('extension_dir');
  291. }
  292. return $directories;
  293. }
  294. /**
  295. * Find each extension/name/extension.inc.php file.
  296. */
  297. function detect_extensions()
  298. {
  299. $lifestream =& $this;
  300. $directories = $this->get_extension_paths();
  301. foreach ($directories as $base_dir)
  302. {
  303. if (!is_dir($base_dir)) continue;
  304. $handler = opendir($base_dir);
  305. while ($file = readdir($handler))
  306. {
  307. // ignore hidden files
  308. if (lifestream_str_startswith($file, '.')) continue;
  309. $path = lifestream_path_join($base_dir, $file);
  310. // if its not a directory we dont care
  311. if (!is_dir($path)) continue;
  312. // check for extension.inc.php
  313. $ext_file = lifestream_path_join($path, 'extension.inc.php');
  314. if (is_file($ext_file))
  315. {
  316. include($ext_file);
  317. }
  318. }
  319. }
  320. }
  321. function get_theme_paths()
  322. {
  323. $directories = array(
  324. lifestream_path_join(LIFESTREAM_PATH, 'themes')
  325. );
  326. if ($this->get_option('theme_dir') && $this->get_option('theme_dir') != $directories[0]) {
  327. $directories[] = $this->get_option('theme_dir');
  328. }
  329. return $directories;
  330. }
  331. /**
  332. * Find each themes/name/theme.txt file.
  333. */
  334. function detect_themes()
  335. {
  336. $directories = $this->get_theme_paths();
  337. foreach ($directories as $base_dir)
  338. {
  339. if (!is_dir($base_dir)) continue;
  340. $handler = opendir($base_dir);
  341. while ($file = readdir($handler))
  342. {
  343. // ignore hidden files
  344. if (lifestream_str_startswith($file, '.')) continue;
  345. // if its not a directory we dont care
  346. $path = lifestream_path_join($base_dir, $file);
  347. if (!is_dir($path)) continue;
  348. // check for main.inc.php
  349. $ext_file = lifestream_path_join($path, 'theme.txt');
  350. if (is_file($ext_file))
  351. {
  352. $theme = array();
  353. $theme = $this->parse_nfo_file($ext_file);
  354. $theme['__path'] = $path;
  355. if (!array_key_exists('name', $theme)) continue;
  356. $this->themes[$file] = $theme;
  357. }
  358. }
  359. }
  360. }
  361. function get_media_url_for_icon($filename='generic.png', $iconpack='default')
  362. {
  363. $path = lifestream_path_join($this->icons[$iconpack]['__path'], $filename);
  364. if (!is_file($path))
  365. {
  366. $filename = 'generic.png';
  367. $path = lifestream_path_join(LIFESTREAM_PATH, 'icons', 'default', $filename);
  368. }
  369. return $this->get_absolute_media_url($path);
  370. }
  371. function get_icon_media_url($filename)
  372. {
  373. return $this->get_media_url_for_icon($filename, $this->get_option('icons', 'default'));
  374. }
  375. function get_theme_media_url($filename)
  376. {
  377. return $this->get_media_url_for_theme($filename, $this->get_option('theme', 'default'));
  378. }
  379. function get_media_url_for_theme($filename, $theme='default')
  380. {
  381. // base dir is now $theme['__path'] so we must abstract the web dir
  382. $path = lifestream_path_join($this->themes[$theme]['__path'], 'media', $filename);
  383. if (!is_file($path))
  384. {
  385. $path = lifestream_path_join(LIFESTREAM_PATH, 'themes', 'default', 'media', $filename);
  386. }
  387. return $this->get_absolute_media_url($path);
  388. }
  389. function get_absolute_media_url($path)
  390. {
  391. // XXX: This will fail if you're symlinking the lifestream directory in
  392. $path = str_replace(trailingslashit(WP_CONTENT_DIR), '', $path);
  393. return str_replace('\\', '/', trailingslashit(WP_CONTENT_URL).$path);
  394. }
  395. function get_theme_filepath($filename)
  396. {
  397. $path = $this->get_filepath_for_theme($filename, $this->get_option('theme', 'default'));
  398. if (!is_file($path))
  399. {
  400. $path = $this->get_filepath_for_theme($filename, 'default');
  401. }
  402. return $path;
  403. }
  404. function get_filepath_for_theme($filename, $theme='default')
  405. {
  406. if (!array_key_exists($theme, $this->themes))
  407. {
  408. throw new Exception('Theme is not valid.');
  409. }
  410. return lifestream_path_join($this->themes[$theme]['__path'], $filename);
  411. }
  412. function validate_image($url)
  413. {
  414. // // Check the extension
  415. // $bits = explode('.', basename($url));
  416. // if (count($bits) > 1)
  417. // {
  418. // $ext = $bits[count($bits)-1];
  419. // return (in_array($ext, $this->valid_image_extensions));
  420. // }
  421. $handler = $this->get_option('url_handler');
  422. $use_fsock = true;
  423. if (($handler == 'auto' && function_exists('curl_init')) || $handler == 'curl')
  424. {
  425. $use_fsock = false;
  426. }
  427. $file = new SimplePie_File($url, 10, 5, null, SIMPLEPIE_USERAGENT, $use_fsock);
  428. if (!$file->success)
  429. {
  430. return false;
  431. }
  432. // Attempt to check content type
  433. if (!empty($file->headers['content-type']))
  434. {
  435. return (in_array($file->headers['content-type'], $this->valid_image_types));
  436. }
  437. // Use GD if we can
  438. if (function_exists('imagecreatefromstring'))
  439. {
  440. return (imagecreatefromstring($file->body) !== false);
  441. }
  442. // Everything has failed, we'll just let it pass
  443. return true;
  444. }
  445. // options and their default values
  446. protected $_options = array(
  447. 'day_format' => 'F jS',
  448. 'hour_format' => 'g:ia',
  449. 'number_of_items' => '50',
  450. 'date_interval' => '1 month',
  451. 'digest_title' => 'Daily Digest for %s',
  452. 'digest_body' => '%1$s',
  453. 'digest_category' => '1',
  454. 'digest_author' => '1',
  455. 'daily_digest' => '0',
  456. 'digest_interval' => 'daily',
  457. 'digest_time' => '0',
  458. 'update_interval' => '15',
  459. 'show_owners' => '0',
  460. 'use_ibox' => '1',
  461. 'show_credits' => '1',
  462. 'hide_details_default' => '1',
  463. 'url_handler' => 'auto',
  464. 'feed_items' => '10',
  465. 'truncate_length' => '128',
  466. 'theme' => 'default',
  467. 'icons' => 'default',
  468. 'extension_dir' => '',
  469. 'theme_dir' => '',
  470. 'icon_dir' => '',
  471. 'links_new_windows' => '0',
  472. 'truncate_interval' => '0',
  473. );
  474. function __construct()
  475. {
  476. $this->path = WP_CONTENT_URL . '/plugins/lifestream';
  477. $this->_optioncache = null;
  478. add_action('admin_menu', array(&$this, 'options_menu'));
  479. add_action('wp_head', array(&$this, 'header'));
  480. add_filter('the_content', array(&$this, 'embed_callback'));
  481. add_action('init', array(&$this, 'init'));
  482. add_filter('cron_schedules', array(&$this, 'get_cron_schedules'));
  483. add_action('lifestream_digest_cron', array(&$this, 'digest_update'));
  484. add_action('lifestream_cron', array(&$this, 'update'));
  485. add_action('lifestream_cleanup', array(&$this, 'cleanup_history'));
  486. register_activation_hook(LIFESTREAM_PLUGIN_FILE, array(&$this, 'activate'));
  487. register_deactivation_hook(LIFESTREAM_PLUGIN_FILE, array(&$this, 'deactivate'));
  488. }
  489. function truncate($string, $length=128)
  490. {
  491. if (!($length > 0)) return $string;
  492. if (strlen($string) > $length)
  493. {
  494. $string = substr($string, 0, $length-3).'...';
  495. }
  496. return $string;
  497. }
  498. // To be quite honest, WordPress should be doing this kind of magic itself.
  499. function _populate_option_cache()
  500. {
  501. if (!$this->_optioncache)
  502. {
  503. $this->_optioncache = (array)get_option('lifestream_options');
  504. if (!$this->_optioncache) $this->_optioncache = (array)$this->_options;
  505. }
  506. }
  507. /**
  508. * Fetches the value of an option. Returns `null` if the option is not set.
  509. */
  510. function get_option($option, $default=null)
  511. {
  512. $this->_populate_option_cache();
  513. if (!isset($this->_optioncache[$option])) $value = $default;
  514. else
  515. {
  516. $value = $this->_optioncache[$option];
  517. }
  518. if (empty($value)) $value = $default;
  519. return $value;
  520. }
  521. /**
  522. * Removes an option.
  523. */
  524. function delete_option($option)
  525. {
  526. $this->_populate_option_cache();
  527. unset($this->_optioncache[$option]);
  528. update_option('lifestream_options', $this->_optioncache);
  529. }
  530. /**
  531. * Updates the value of an option.
  532. */
  533. function update_option($option, $value)
  534. {
  535. $this->_populate_option_cache();
  536. $this->_optioncache[$option] = $value;
  537. update_option('lifestream_options', $this->_optioncache);
  538. }
  539. /**
  540. * Sets an option if it doesn't exist.
  541. */
  542. function add_option($option, $value)
  543. {
  544. $this->_populate_option_cache();
  545. if (!array_key_exists($option, $this->_optioncache) || $this->_optioncache[$option] === '')
  546. {
  547. $this->_optioncache[$option] = $value;
  548. update_option('lifestream_options', $this->_optioncache);
  549. }
  550. }
  551. function __($text, $params=null)
  552. {
  553. if (!is_array($params))
  554. {
  555. $params = func_get_args();
  556. $params = array_slice($params, 1);
  557. }
  558. return vsprintf(__($text, 'lifestream'), $params);
  559. }
  560. function _e($text, $params=null)
  561. {
  562. if (!is_array($params))
  563. {
  564. $params = func_get_args();
  565. $params = array_slice($params, 1);
  566. }
  567. echo vsprintf(__($text, 'lifestream'), $params);
  568. }
  569. function init()
  570. {
  571. global $wpdb;
  572. $offset = get_option('gmt_offset') * 3600;
  573. define('LIFESTREAM_DATE_OFFSET', $offset);
  574. load_plugin_textdomain('lifestream', false, 'lifestream/locales');
  575. $page = (isset($_GET['page']) ? $_GET['page'] : null);
  576. if (is_admin() && lifestream_str_startswith($page, 'lifestream'))
  577. {
  578. wp_enqueue_script('jquery');
  579. wp_enqueue_script('admin-forms');
  580. }
  581. add_feed('lifestream-feed', 'lifestream_rss_feed');
  582. $this->is_buddypress = (function_exists('bp_is_blog_page') ? true : false);
  583. // If this is an update we need to force reactivation
  584. if (LIFESTREAM_VERSION != $this->get_option('_version'))
  585. {
  586. $this->get_option('_version');
  587. $this->deactivate();
  588. $this->activate();
  589. }
  590. }
  591. function log_error($message, $feed_id=null)
  592. {
  593. global $wpdb;
  594. if ($feed_id)
  595. {
  596. $result = $wpdb->query($wpdb->prepare("INSERT INTO `".$wpdb->prefix."lifestream_error_log` (`feed_id`, `message`, `timestamp`) VALUES (%s, %s, %d)", $wpdb->escape($feed_id), $wpdb->escape($message), time()));
  597. }
  598. else
  599. {
  600. $result = $wpdb->query($wpdb->prepare("INSERT INTO `".$wpdb->prefix."lifestream_error_log` (`feed_id`, `message`, `timestamp`) VALUES (NULL, %s, %d)", $wpdb->escape($message), time()));
  601. }
  602. }
  603. function get_anchor_html($label, $href, $attrs=array())
  604. {
  605. // TODO: this might need to be optimized as string management is typically slow
  606. if ($this->get_option('links_new_windows') && empty($attrs['target']))
  607. {
  608. $attrs['target'] = '_blank';
  609. }
  610. $attrs['href'] = $href;
  611. $html = '<a';
  612. foreach ($attrs as $key=>$value)
  613. {
  614. $html .= ' '.$key.'="'.$value.'"';
  615. }
  616. $html .= '>'.$label.'</a>';
  617. return $html;
  618. }
  619. function get_digest_interval()
  620. {
  621. $interval = $this->get_option('digest_interval');
  622. switch ($interval)
  623. {
  624. case 'weekly':
  625. return 3600*24*7;
  626. case 'daily':
  627. return 3600*24;
  628. case 'hourly':
  629. return 3600;
  630. }
  631. }
  632. function get_cron_schedules($cron)
  633. {
  634. $interval = (int)$this->get_option('update_interval', 15);
  635. if (!($interval > 0)) $interval = 15;
  636. $cron['lifestream'] = array(
  637. 'interval' => $interval * 60,
  638. 'display' => $this->__('On Lifestream update')
  639. );
  640. $cron['lifestream_digest'] = array(
  641. 'interval' => (int)$this->get_digest_interval(),
  642. 'display' => $this->__('On Lifestream daily digest update')
  643. );
  644. return $cron;
  645. }
  646. function get_single_event($feed_type)
  647. {
  648. $events = $this->get_events(array('feed_types'=>array($feed_type), 'limit'=>1, 'break_groups'=>true));
  649. $event = $events[0];
  650. return $event;
  651. }
  652. function generate_unique_id()
  653. {
  654. return uniqid('ls_', true);
  655. }
  656. function digest_update()
  657. {
  658. global $wpdb;
  659. if ($this->get_option('daily_digest') != '1') return;
  660. $interval = $this->get_digest_interval();
  661. $options = array(
  662. 'id' => $this->generate_unique_id(),
  663. );
  664. $now = time();
  665. // If there was a previous digest, we show only events since it
  666. $from = $this->get_option('_last_digest');
  667. // Otherwise we show events within the interval period
  668. if (!$from) $from = $now - $interval;
  669. // make sure the post doesn't exist
  670. $results = $wpdb->get_results($wpdb->prepare("SELECT `post_id` FROM `".$wpdb->prefix."postmeta` WHERE `meta_key` = '_lifestream_digest_date' AND `meta_value` = %d LIMIT 0, 1", $now));
  671. if ($results) continue;
  672. $sql = $wpdb->prepare("SELECT t1.*, t2.`options` FROM `".$wpdb->prefix."lifestream_event_group` as `t1` INNER JOIN `".$wpdb->prefix."lifestream_feeds` as t2 ON t1.`feed_id` = t2.`id` WHERE t1.`timestamp` > %s AND t1.`timestamp` < %s ORDER BY t1.`timestamp` ASC", $from, $now);
  673. $results =& $wpdb->get_results($sql);
  674. $events = array();
  675. foreach ($results as &$result)
  676. {
  677. $events[] = new Lifestream_EventGroup($this, $result);
  678. }
  679. if (count($events))
  680. {
  681. ob_start();
  682. if (!include($this->get_theme_filepath('digest.inc.php'))) return;
  683. $content = sprintf($this->get_option('digest_body'), ob_get_clean(), date($this->get_option('day_format'), $now), count($events));
  684. $data = array(
  685. 'post_content' => $wpdb->escape($content),
  686. 'post_title' => $wpdb->escape(sprintf($this->get_option('digest_title'), date($this->get_option('day_format'), $now), date($this->get_option('hour_format'), $now))),
  687. 'post_date' => date('Y-m-d H:i:s', $now),
  688. 'post_category' => array($this->get_option('digest_category')),
  689. 'post_status' => 'publish',
  690. 'post_author' => $wpdb->escape($this->get_option('digest_author')),
  691. );
  692. $post_id = wp_insert_post($data);
  693. add_post_meta($post_id, '_lifestream_digest_date', $now, true);
  694. }
  695. $this->update_option('_last_digest', $now);
  696. }
  697. // page output
  698. function options_menu()
  699. {
  700. global $wpdb;
  701. wp_enqueue_script('postbox');
  702. if (function_exists('add_menu_page'))
  703. {
  704. $basename = basename(LIFESTREAM_PLUGIN_FILE);
  705. $results =& $wpdb->get_results("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_error_log` WHERE has_viewed = 0");
  706. $errors = $results[0]->count;
  707. add_menu_page('Lifestream', 'Lifestream', 'edit_posts', $basename, array(&$this, 'options_page'));
  708. add_submenu_page($basename, $this->__('Lifestream Feeds'), $this->__('Feeds'), 'level_1', $basename, array(&$this, 'options_page'));
  709. add_submenu_page($basename, $this->__('Lifestream Events'), $this->__('Events'), 'edit_posts', 'lifestream-events.php', array(&$this, 'options_page'));
  710. add_submenu_page($basename, $this->__('Lifestream Settings'), $this->__('Settings'), 'manage_options', 'lifestream-settings.php', array(&$this, 'options_page'));
  711. add_submenu_page($basename, $this->__('Lifestream Change Log'), $this->__('Change Log'), 'edit_posts', 'lifestream-changelog.php', array(&$this, 'options_page'));
  712. add_submenu_page($basename, $this->__('Lifestream Errors'), $this->__('Errors (%d)', $errors), 'edit_posts', 'lifestream-errors.php', array(&$this, 'options_page'));
  713. add_submenu_page($basename, $this->__('Lifestream Maintenance'), $this->__('Maintenance / Debug', $errors), 'manage_options', 'lifestream-maintenance.php', array(&$this, 'options_page'));
  714. add_submenu_page($basename, $this->__('Lifestream Support Forums'), $this->__('Support Forums'), 'edit_posts', 'lifestream-forums.php', array(&$this, 'options_page'));
  715. }
  716. }
  717. function header()
  718. {
  719. echo '<script type="text/javascript" src="'.$this->path.'/lifestream.js"></script>';
  720. echo '<link rel="stylesheet" type="text/css" media="screen" href="'.$this->get_theme_media_url('lifestream.css').'"/>';
  721. }
  722. function options_page()
  723. {
  724. global $wpdb, $userdata;
  725. $wpdb->show_errors();
  726. $this->install();
  727. get_currentuserinfo();
  728. $date_format = sprintf('%s @ %s', $this->get_option('day_format'), $this->get_option('hour_format'));
  729. $basename = basename(LIFESTREAM_PLUGIN_FILE);
  730. $errors = array();
  731. $message = null;
  732. switch ($_GET['page'])
  733. {
  734. case 'lifestream-maintenance.php':
  735. if ($_POST['resetcron'])
  736. {
  737. $this->reschedule_cron();
  738. $message = $this->__('Cron timers have been reset.');
  739. }
  740. elseif ($_POST['restore'])
  741. {
  742. $this->restore_options();
  743. $message = $this->__('Default options have been restored.');
  744. }
  745. elseif ($_POST['restoredb'])
  746. {
  747. $this->restore_database();
  748. $message = $this->__('Default database has been restored.');
  749. }
  750. break;
  751. case 'lifestream-events.php':
  752. switch ((isset($_REQUEST['op']) ? strtolower($_REQUEST['op']) : null))
  753. {
  754. case 'delete':
  755. if (!($ids = $_REQUEST['id'])) break;
  756. if (!is_array($ids)) $ids = array($ids);
  757. foreach ($ids as $id)
  758. {
  759. $result =& $wpdb->get_results($wpdb->prepare("SELECT `id`, `feed_id`, `timestamp`, `owner_id` FROM `".$wpdb->prefix."lifestream_event` WHERE `id` = %d", $id));
  760. if (!$result)
  761. {
  762. $errors[] = $this->__('The selected feed was not found.');
  763. }
  764. elseif (!current_user_can('manage_options') && $result[0]->owner_id != $userdata->ID)
  765. {
  766. $errors[] = $this->__('You do not have permission to do that.');
  767. }
  768. else
  769. {
  770. $result =& $result[0];
  771. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_event` SET `visible` = 0 WHERE `id` = %d", $result->id));
  772. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_event_group` SET `visible` = 0 WHERE `event_id` = %d", $result->id));
  773. // Now we have to update the batch if it exists.
  774. $group =& $wpdb->get_results($wpdb->prepare("SELECT `id` FROM `".$wpdb->prefix."lifestream_event_group` WHERE `event_id` IS NULL AND DATE(FROM_UNIXTIME(`timestamp`)) = DATE(FROM_UNIXTIME(%d)) AND `feed_id` = %d LIMIT 0, 1", $result->timestamp, $result->feed_id));
  775. if (count($group) == 1)
  776. {
  777. $group =& $group[0];
  778. $results =& $wpdb->get_results($wpdb->prepare("SELECT `data`, `link` FROM `".$wpdb->prefix."lifestream_event` WHERE `feed_id` = %d AND `visible` = 1 AND DATE(FROM_UNIXTIME(`timestamp`)) = DATE(FROM_UNIXTIME(%d))", $result->feed_id, $result->timestamp));
  779. if (count($results))
  780. {
  781. $events = array();
  782. foreach ($results as &$result)
  783. {
  784. $result->data = unserialize($result->data);
  785. $result->data['link'] = $result->link;
  786. $events[] = $result->data;
  787. }
  788. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_event_group` SET `data` = %s, `total` = %d, `updated` = 1 WHERE `id` = %d", $wpdb->escape(serialize($events)), count($events), $group->id));
  789. }
  790. else
  791. {
  792. $wpdb->query($wpdb->prepare("DELETE FROM `".$wpdb->prefix."lifestream_event_group` WHERE `id` = %d", $group->id));
  793. }
  794. }
  795. else
  796. {
  797. $wpdb->query($wpdb->prepare("DELETE FROM `".$wpdb->prefix."lifestream_event_group` WHERE `event_id` = %d", $result->id));
  798. }
  799. }
  800. $message = $this->__('The selected events were hidden.');
  801. }
  802. break;
  803. }
  804. break;
  805. case 'lifestream-settings.php':
  806. if (!empty($_POST['save']))
  807. {
  808. foreach (array_keys($this->_options) as $value)
  809. {
  810. $this->update_option($value, (isset($_POST['lifestream_'.$value]) ? stripslashes($_POST['lifestream_'.$value]) : '0'));
  811. }
  812. // We need to make sure the cron runs now
  813. $this->reschedule_cron();
  814. }
  815. break;
  816. default:
  817. $feedmsgs = array();
  818. switch ((isset($_REQUEST['op']) ? strtolower($_REQUEST['op']) : null))
  819. {
  820. case 'refreshall':
  821. $results = $this->update_all($userdata->ID);
  822. foreach ($results as $id=>$result)
  823. {
  824. if (is_int($result)) $feedmsgs[$id] = $result;
  825. else $errors[] = $this->__('There was an error refreshing the selected feed: ID %s', $id);
  826. }
  827. $message = $this->__('All of your feeds have been refreshed.');
  828. break;
  829. case 'refresh':
  830. if (!$_REQUEST['id']) break;
  831. foreach ($_REQUEST['id'] as $id)
  832. {
  833. $result =& $wpdb->get_results($wpdb->prepare("SELECT * FROM `".$wpdb->prefix."lifestream_feeds` WHERE `id` = %d LIMIT 0, 1", $id));
  834. if (!$result)
  835. {
  836. $errors[] = $this->__('The selected feed was not found.');
  837. }
  838. elseif (!current_user_can('manage_options') && $result[0]->owner_id != $userdata->ID)
  839. {
  840. $errors[] = $this->__('You do not have permission to do that.');
  841. }
  842. else
  843. {
  844. $instance = Lifestream_Feed::construct_from_query_result($this, $result[0]);
  845. $msg_arr = $instance->refresh();
  846. if ($msg_arr[0] !== false)
  847. {
  848. $message = $this->__('The selected feeds and their events have been refreshed.');
  849. $feedmsgs[$instance->id] = $msg_arr[1];
  850. }
  851. else
  852. {
  853. $errors[] = $this->__('There was an error refreshing the selected feed: ID %s', $instance->id);
  854. }
  855. }
  856. }
  857. break;
  858. case 'pause':
  859. if (!$_REQUEST['id']) break;
  860. $ids = array();
  861. foreach ($_REQUEST['id'] as $id)
  862. {
  863. $ids[] = (int)$id;
  864. }
  865. if (!empty($ids))
  866. {
  867. if (current_user_can('manage_options'))
  868. {
  869. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_feeds` SET `active` = 0 WHERE `id` IN ('%s')", implode("','", $ids)));
  870. }
  871. else
  872. {
  873. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_feeds` SET `active` = 1 WHERE `id` IN ('%s') AND `owner_id` = %s", implode("','", $ids), $userdata->ID));
  874. }
  875. $message = $this->__('The selected feeds have been paused, and events will not be refreshed.');
  876. }
  877. break;
  878. case 'unpause':
  879. if (!$_REQUEST['id']) break;
  880. $ids = array();
  881. foreach ($_REQUEST['id'] as $id)
  882. {
  883. $ids[] = (int)$id;
  884. }
  885. if (!empty($ids))
  886. {
  887. if (current_user_can('manage_options'))
  888. {
  889. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_feeds` SET `active` = 1 WHERE `id` IN ('%s')", implode("','", $ids)));
  890. }
  891. else
  892. {
  893. $wpdb->query($wpdb->prepare("UPDATE `".$wpdb->prefix."lifestream_feeds` SET `active` = 0 WHERE `id` IN ('%s') AND `owner_id` = %s", implode("','", $ids), $userdata->ID));
  894. }
  895. $message = $this->__('The selected feeds have been unpaused, and events will now be refreshed.');
  896. }
  897. break;
  898. case 'delete':
  899. if (!$_REQUEST['id']) break;
  900. foreach ($_REQUEST['id'] as $id)
  901. {
  902. $result =& $wpdb->get_results($wpdb->prepare("SELECT * FROM `".$wpdb->prefix."lifestream_feeds` WHERE `id` = %d LIMIT 0, 1", $id));
  903. if (!$result)
  904. {
  905. $errors[] = $this->__('The selected feed was not found.');
  906. }
  907. elseif (!current_user_can('manage_options') && $result[0]->owner_id != $userdata->ID)
  908. {
  909. $errors[] = $this->__('You do not have permission to do that.');
  910. }
  911. else
  912. {
  913. $instance = Lifestream_Feed::construct_from_query_result($this, $result[0]);
  914. $instance->delete();
  915. $message = $this->__('The selected feeds and all related events has been removed.');
  916. }
  917. }
  918. break;
  919. case 'edit':
  920. $result =& $wpdb->get_results($wpdb->prepare("SELECT * FROM `".$wpdb->prefix."lifestream_feeds` WHERE `id` = %d LIMIT 0, 1", $_GET['id']));
  921. if (!$result)
  922. {
  923. $errors[] = $this->__('The selected feed was not found.');
  924. }
  925. elseif (!current_user_can('manage_options') && $result[0]->owner_id != $userdata->ID)
  926. {
  927. $errors[] = $this->__('You do not have permission to do that.');
  928. }
  929. else
  930. {
  931. $instance = Lifestream_Feed::construct_from_query_result($this, $result[0]);
  932. $options = $instance->get_options();
  933. if (@$_POST['save'])
  934. {
  935. $values = array();
  936. foreach ($options as $option=>$option_meta)
  937. {
  938. if ($option_meta[1] && !$_POST[$option])
  939. {
  940. $errors[] = $option_meta[0].' is required.';
  941. }
  942. else
  943. {
  944. $values[$option] = stripslashes($_POST[$option]);
  945. }
  946. }
  947. if ($instance->get_constant('MUST_GROUP'))
  948. {
  949. $values['grouped'] = 1;
  950. }
  951. elseif ($instance->get_constant('CAN_GROUP'))
  952. {
  953. $values['grouped'] = $_POST['grouped'];
  954. }
  955. if ($instance->get_constant('HAS_EXCERPTS'))
  956. {
  957. $values['excerpt'] = $_POST['excerpt'];
  958. }
  959. $values['feed_label'] = $_POST['feed_label'];
  960. $values['icon_url'] = $_POST['icon_url'];
  961. $values['auto_icon'] = $_POST['auto_icon'];
  962. if ($_POST['owner'] != $instance->owner_id && current_user_can('manage_options'))
  963. {
  964. $usero = new WP_User($_POST['owner']);
  965. $owner = $usero->data;
  966. $instance->owner_id = $_POST['owner'];
  967. $instance->owner = $owner->display_name;
  968. }
  969. if (!count($errors))
  970. {
  971. $instance->options = $values;
  972. $instance->save();
  973. unset($_POST);
  974. }
  975. }
  976. elseif (@$_POST['truncate'])
  977. {
  978. $instance->truncate();
  979. $instance->refresh();
  980. }
  981. }
  982. break;
  983. case 'add':
  984. if ($_POST)
  985. {
  986. $class_name = $this->get_feed($_GET['feed']);
  987. if (!$class_name) break;
  988. $feed = new $class_name($this);
  989. $values = array();
  990. $options = $feed->get_options();
  991. foreach ($options as $option=>$option_meta)
  992. {
  993. if ($option_meta[1] && !$_POST[$option])
  994. {
  995. $errors[] = $option_meta[0].' is required.';
  996. }
  997. else
  998. {
  999. $values[$option] = stripslashes($_POST[$option]);
  1000. }
  1001. }
  1002. if ($feed->get_constant('MUST_GROUP'))
  1003. {
  1004. $values['grouped'] = 1;
  1005. }
  1006. elseif ($feed->get_constant('CAN_GROUP'))
  1007. {
  1008. $values['grouped'] = $_POST['grouped'];
  1009. }
  1010. if ($feed->get_constant('HAS_EXCERPTS'))
  1011. {
  1012. $values['excerpt'] = $_POST['excerpt'];
  1013. }
  1014. $values['feed_label'] = $_POST['feed_label'];
  1015. $values['icon_url'] = $_POST['icon_url'];
  1016. $values['auto_icon'] = @$_POST['auto_icon'];
  1017. if (current_user_can('manage_options'))
  1018. {
  1019. $feed->owner_id = $_POST['owner'];
  1020. $usero = new WP_User($feed->owner_id);
  1021. $owner = $usero->data;
  1022. $feed->owner = $owner->display_name;
  1023. }
  1024. else
  1025. {
  1026. $feed->owner_id = $userdata->ID;
  1027. $feed->owner = $userdata->display_name;
  1028. }
  1029. $feed->options = $values;
  1030. if (!count($errors))
  1031. {
  1032. if (!($error = $feed->test()))
  1033. {
  1034. $result = $feed->save();
  1035. if ($result !== false)
  1036. {
  1037. unset($_POST);
  1038. unset($_REQUEST['op']);
  1039. $msg_arr = $feed->refresh(null, true);
  1040. if ($msg_arr[0] !== false)
  1041. {
  1042. $message = $this->__('A new %s feed was added to your Lifestream.', $feed->get_constant('NAME'));
  1043. $feedmsgs[$feed->id] = $msg_arr[1];
  1044. }
  1045. }
  1046. }
  1047. else
  1048. {
  1049. $errors[] = $error;
  1050. }
  1051. }
  1052. }
  1053. break;
  1054. }
  1055. break;
  1056. }
  1057. $lifestream = &$this;
  1058. ob_start();
  1059. ?>
  1060. <style type="text/css">
  1061. .feedlist { margin: 0; padding: 0; }
  1062. .feedlist li { list-style: none; display: inline; }
  1063. .feedlist li a { float: left; display: block; padding: 2px; margin: 1px; width: 23%; text-decoration: none; }
  1064. .feedlist li a:hover { background-color: #e9e9e9; }
  1065. .success { color: #397D33; background-color: #D1FBCA; }
  1066. .error { border-color: #E25F53; color: #E25F53; }
  1067. td.icon { padding: 7px 0 9px 10px; }
  1068. </style>
  1069. <br />
  1070. <?php
  1071. if (count($errors)) { ?>
  1072. <div id="message" class="error"><p><strong><?php $this->_e('There were errors with your request:') ?></strong></p><ul>
  1073. <?php foreach ($errors as $error) { ?>
  1074. <li><?php echo nl2br(Lifestream_Feed::parse_urls(htmlspecialchars($error))); ?></li>
  1075. <?php } ?>
  1076. </ul></div>
  1077. <?php } elseif ($message) { ?>
  1078. <div id="message" class="updated fade"><p><strong><?php echo $message; ?></strong></p></div>
  1079. <?php } ?>
  1080. <div class="wrap">
  1081. <?php
  1082. switch ($_GET['page'])
  1083. {
  1084. case 'lifestream-errors.php':
  1085. $page = (!empty($_GET['paged']) ? $_GET['paged'] : 1);
  1086. switch ((isset($_REQUEST['op']) ? strtolower($_REQUEST['op']) : null))
  1087. {
  1088. case 'clear':
  1089. $wpdb->query("DELETE FROM `".$wpdb->prefix."lifestream_error_log`");
  1090. break;
  1091. }
  1092. $start = ($page-1)*LIFESTREAM_ERRORS_PER_PAGE;
  1093. $end = $page*LIFESTREAM_ERRORS_PER_PAGE;
  1094. $wpdb->query("UPDATE `".$wpdb->prefix."lifestream_error_log` SET has_viewed = 1");
  1095. $results =& $wpdb->get_results("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_error_log`");
  1096. $number_of_pages = ceil($results[0]->count/LIFESTREAM_EVENTS_PER_PAGE);
  1097. $results =& $wpdb->get_results($wpdb->prepare("SELECT t1.*, t2.`feed`, t2.`options` FROM `".$wpdb->prefix."lifestream_error_log` as t1 LEFT JOIN `".$wpdb->prefix."lifestream_feeds` as t2 ON t1.`feed_id` = t2.`id` ORDER BY t1.`timestamp` DESC LIMIT %d, %d", $start, $end));
  1098. include(LIFESTREAM_PATH . '/pages/errors.inc.php');
  1099. break;
  1100. case 'lifestream-maintenance.php':
  1101. include(LIFESTREAM_PATH . '/pages/maintenance.inc.php');
  1102. break;
  1103. case 'lifestream-changelog.php':
  1104. include(LIFESTREAM_PATH . '/pages/changelog.inc.php');
  1105. break;
  1106. case 'lifestream-forums.php':
  1107. include(LIFESTREAM_PATH . '/pages/forums.inc.php');
  1108. break;
  1109. case 'lifestream-settings.php':
  1110. $lifestream_digest_intervals = array(
  1111. 'weekly' => $this->__('Weekly'),
  1112. 'daily' => $this->__('Daily'),
  1113. 'hourly' => $this->__('Hourly'),
  1114. );
  1115. include(LIFESTREAM_PATH . '/pages/settings.inc.php');
  1116. break;
  1117. case 'lifestream-events.php':
  1118. $page = (!empty($_GET['paged']) ? $_GET['paged'] : 1);
  1119. $start = ($page-1)*LIFESTREAM_EVENTS_PER_PAGE;
  1120. $end = $page*LIFESTREAM_EVENTS_PER_PAGE;
  1121. if (!current_user_can('manage_options'))
  1122. {
  1123. $rows =& $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_event` WHERE `owner_id` = %d", $userdata->ID));
  1124. $number_of_pages = ceil($rows->count/LIFESTREAM_EVENTS_PER_PAGE);
  1125. $rows =& $wpdb->get_results($wpdb->prepare("SELECT t1.*, t2.`feed`, t2.`options` FROM `".$wpdb->prefix."lifestream_event` as t1 JOIN `".$wpdb->prefix."lifestream_feeds` as t2 ON t1.`feed_id` = t2.`id` WHERE t1.`owner_id` = %d ORDER BY t1.`timestamp` DESC LIMIT %d, %d", $userdata->ID, $start, $end));
  1126. }
  1127. else
  1128. {
  1129. $rows =& $wpdb->get_row("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_event`");
  1130. $number_of_pages = ceil($rows->count/LIFESTREAM_EVENTS_PER_PAGE);
  1131. $rows =& $wpdb->get_results($wpdb->prepare("SELECT t1.*, t2.`feed`, t2.`options` FROM `".$wpdb->prefix."lifestream_event` as t1 JOIN `".$wpdb->prefix."lifestream_feeds` as t2 ON t1.`feed_id` = t2.`id` ORDER BY t1.`timestamp` DESC LIMIT %d, %d", $start, $end));
  1132. }
  1133. $results = array();
  1134. foreach ($rows as $result)
  1135. {
  1136. $results[] = new Lifestream_Event($lifestream, $result);
  1137. }
  1138. unset($rows);
  1139. include(LIFESTREAM_PATH . '/pages/events.inc.php');
  1140. break;
  1141. default:
  1142. switch ((isset($_REQUEST['op']) ? strtolower($_REQUEST['op']) : null))
  1143. {
  1144. case 'edit':
  1145. include(LIFESTREAM_PATH . '/pages/edit-feed.inc.php');
  1146. break;
  1147. case 'add':
  1148. $identifier = $_GET['feed'];
  1149. $class_name = $this->get_feed($identifier);
  1150. if (!$class_name) break;
  1151. $feed = new $class_name($this);
  1152. $options = $feed->get_options();
  1153. include(LIFESTREAM_PATH . '/pages/add-feed.inc.php');
  1154. break;
  1155. default:
  1156. $page = (!empty($_GET['paged']) ? $_GET['paged'] : 1);
  1157. $start = ($page-1)*LIFESTREAM_FEEDS_PER_PAGE;
  1158. $end = $page*LIFESTREAM_FEEDS_PER_PAGE;
  1159. if (!current_user_can('manage_options'))
  1160. {
  1161. $rows =& $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_feeds` WHERE `owner_id` = %d", $userdata->ID));
  1162. $number_of_pages = ceil($rows->count/LIFESTREAM_FEEDS_PER_PAGE);
  1163. $rows =& $wpdb->get_results($wpdb->prepare("SELECT t1.*, (SELECT COUNT(1) FROM `".$wpdb->prefix."lifestream_event` WHERE `feed_id` = t1.`id`) as `events` FROM `".$wpdb->prefix."lifestream_feeds` as t1 WHERE t1.`owner_id` = %d ORDER BY `id` LIMIT %d, %d", $userdata->ID, $start, $end));
  1164. }
  1165. else
  1166. {
  1167. $rows =& $wpdb->get_row("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_feeds`");
  1168. $number_of_pages = ceil($rows->count/LIFESTREAM_FEEDS_PER_PAGE);
  1169. $rows =& $wpdb->get_results($wpdb->prepare("SELECT t1.*, (SELECT COUNT(1) FROM `".$wpdb->prefix."lifestream_event` WHERE `feed_id` = t1.`id`) as `events` FROM `".$wpdb->prefix."lifestream_feeds` as t1 ORDER BY `id` LIMIT %d, %d", $start, $end));
  1170. }
  1171. $results = array();
  1172. foreach ($rows as $result)
  1173. {
  1174. $results[] = Lifestream_Feed::construct_from_query_result($this, $result);
  1175. }
  1176. if ($results !== false)
  1177. {
  1178. include(LIFESTREAM_PATH . '/pages/feeds.inc.php');
  1179. }
  1180. break;
  1181. }
  1182. break;
  1183. }
  1184. ?>
  1185. </div>
  1186. <?php
  1187. ob_end_flush();
  1188. }
  1189. /**
  1190. * Cleans up old entries based on the `truncate_interval` setting.
  1191. */
  1192. function cleanup_history()
  1193. {
  1194. $int = $this->get_option('truncate_interval');
  1195. if (!(int)$int) return;
  1196. // the value is in days
  1197. $ts = time()-(int)$int*3600*24;
  1198. $result = $wpdb->query($wpdb->prepare("DELETE FROM `".$wpdb->prefix."lifestream_event` WHERE `timestamp` < %s", $wpdb->escape($ts)));
  1199. $result = $wpdb->query($wpdb->prepare("DELETE FROM `".$wpdb->prefix."lifestream_event_group` WHERE `timestamp` < %s", $wpdb->escape($ts)));
  1200. $result = $wpdb->query($wpdb->prepare("DELETE FROM `".$wpdb->prefix."lifestream_error_log` WHERE `timestamp` < %s", $wpdb->escape($ts)));
  1201. }
  1202. /**
  1203. * Attempts to update all feeds
  1204. */
  1205. function update($user_id=null)
  1206. {
  1207. $event_arr = $this->update_all($user_id);
  1208. $events = 0;
  1209. foreach ($event_arr as $instance=>$result)
  1210. {
  1211. if (is_int($result)) $events += $result;
  1212. }
  1213. return $events;
  1214. }
  1215. function update_all($user_id=null)
  1216. {
  1217. // $user_id is not implemented yet
  1218. global $wpdb;
  1219. $this->update_option('_last_update', time());
  1220. $events = array();
  1221. $results =& $wpdb->get_results("SELECT * FROM `".$wpdb->prefix."lifestream_feeds` WHERE `active` = 1");
  1222. foreach ($results as $result)
  1223. {
  1224. $instance = Lifestream_Feed::construct_from_query_result($this, $result);
  1225. try
  1226. {
  1227. $feed_msg = $instance->refresh();
  1228. $events[$instance->id] = $feed_msg[1];
  1229. }
  1230. catch (Lifestream_FeedFetchError $ex)
  1231. {
  1232. $this->log_error($ex, $instance->id);
  1233. $events[$instance->id] = $ex;
  1234. }
  1235. }
  1236. return $events;
  1237. }
  1238. /**
  1239. * Registers a feed class with Lifestream.
  1240. * @param $class_name {Class} Should extend Lifestream_Extension.
  1241. */
  1242. function register_feed($class_name)
  1243. {
  1244. $this->feeds[lifestream_get_class_constant($class_name, 'ID')] = $class_name;
  1245. // this may be the ugliest thing ever written in PHP, thank you developers!
  1246. $rcl = new ReflectionClass($class_name);
  1247. $this->paths[$class_name] = dirname($rcl->getFileName());
  1248. unset($rcl);
  1249. }
  1250. function get_feed($class_name)
  1251. {
  1252. return $this->feeds[$class_name];
  1253. }
  1254. /**
  1255. * Similar to file_get_contents but will use curl by default.
  1256. */
  1257. function file_get_contents($url)
  1258. {
  1259. $handler = $this->get_option('url_handler');
  1260. $use_fsock = true;
  1261. if (($handler == 'auto' && function_exists('curl_init')) || $handler == 'curl')
  1262. {
  1263. $use_fsock = false;
  1264. }
  1265. $file = new SimplePie_File($url, 10, 5, null, SIMPLEPIE_USERAGENT, $use_fsock);
  1266. if (!$file->success)
  1267. {
  1268. throw new Lifestream_FeedFetchError('Failed to open url: '.$url .' ('.$file->error.')');
  1269. }
  1270. return $file->body;
  1271. }
  1272. /*
  1273. * This is a wrapper function which initiates the callback for the custom tag embedding.
  1274. */
  1275. function embed_callback($content)
  1276. {
  1277. return preg_replace_callback("|\[lifestream(?:\s+([^\]]+))?\]|i", array(&$this, 'embed_handler'), $content);
  1278. return preg_replace_callback("|<\[]lifestream(?:\s+([^>\]+]))?/?[>\]]|i", array(&$this, 'embed_handler'), $content);
  1279. }
  1280. /*
  1281. * This function handles the real meat by handing off the work to helper functions.
  1282. */
  1283. function embed_handler($matches)
  1284. {
  1285. $args = array();
  1286. if (count($matches) > 1)
  1287. {
  1288. preg_match_all("|(?:([a-z_]+)=[\"']?([a-z0-9_-\s]+)[\"']?)\s*|i", $matches[1], $options);
  1289. for ($i=0; $i<count($options[1]); $i++)
  1290. {
  1291. if ($options[$i]) $args[$options[1][$i]] = $options[2][$i];
  1292. }
  1293. }
  1294. ob_start();
  1295. if (!empty($args['feed_ids'])) $args['feed_ids'] = explode(',', $args['feed_ids']);
  1296. if (!empty($args['user_ids'])) $args['user_ids'] = explode(',', $args['user_ids']);
  1297. if (!empty($args['feed_types'])) $args['feed_types'] = explode(',', $args['feed_types']);
  1298. lifestream($args);
  1299. return ob_get_clean();
  1300. }
  1301. /**
  1302. * Returns the duration from now until timestamp.
  1303. * @param $timestamp {Integer}
  1304. * @param $granularity {Integer}
  1305. * @param $format {String} Date format.
  1306. * @return {String}
  1307. */
  1308. function timesince($timestamp, $granularity=1, $format='Y-m-d H:i:s')
  1309. {
  1310. $difference = time() - $timestamp;
  1311. if ($difference < 0) return 'just now';
  1312. elseif ($difference < 86400*2)
  1313. {
  1314. return $this->duration($difference, $granularity) . ' ago';
  1315. }
  1316. else
  1317. {
  1318. return date($this->get_option('day_format'), $timestamp);
  1319. }
  1320. }
  1321. /**
  1322. * Returns the duration from a difference.
  1323. * @param $difference {Integer}
  1324. * @param $granularity {Integer}
  1325. * @return {String}
  1326. */
  1327. function duration($difference, $granularity=2)
  1328. {
  1329. { // if difference is over 10 days show normal time form
  1330. $periods = array(
  1331. $this->__('w') => 604800,
  1332. $this->__('d') => 86400,
  1333. $this->__('h') => 3600,
  1334. $this->__('m') => 60,
  1335. $this->__('s') => 1
  1336. );
  1337. $output = '';
  1338. foreach ($periods as $key => $value)
  1339. {
  1340. if ($difference >= $value)
  1341. {
  1342. $time = round($difference / $value);
  1343. $difference %= $value;
  1344. $output .= ($output ? ' ' : '').$time.$key;
  1345. //$output .= (($time > 1 && ($key == 'week' || $key == 'day')) ? $key.'s' : $key);
  1346. $granularity--;
  1347. }
  1348. if ($granularity == 0) break;
  1349. }
  1350. return ($output ? $output : '0 seconds');
  1351. }
  1352. }
  1353. function get_cron_task_description($name)
  1354. {
  1355. switch ($name)
  1356. {
  1357. case 'lifestream_cleanup':
  1358. return 'Cleans up old events and error messages.';
  1359. break;
  1360. case 'lifestream_cron':
  1361. return 'Updates all active feeds.';
  1362. break;
  1363. case 'lifestream_digest_cron':
  1364. return 'Creates a daily digest post if enabled.';
  1365. break;
  1366. }
  1367. }
  1368. function restore_options()
  1369. {
  1370. // default options and their values
  1371. foreach ($this->_options as $key=>$value)
  1372. {
  1373. $this->update_option($key, $value);
  1374. }
  1375. $this->update_option('extension_dir', WP_CONTENT_DIR.'/wp-lifestream/extensions/');
  1376. $this->update_option('theme_dir', WP_CONTENT_DIR.'/wp-lifestream/themes/');
  1377. $this->update_option('icon_dir', WP_CONTENT_DIR.'/wp-lifestream/icons/');
  1378. }
  1379. function restore_database()
  1380. {
  1381. global $wpdb;
  1382. $this->safe_query("DROP TABLE `".$wpdb->prefix."lifestream_event`;");
  1383. $this->safe_query("DROP TABLE `".$wpdb->prefix."lifestream_event_group`;");
  1384. $this->safe_query("DROP TABLE `".$wpdb->prefix."lifestream_feeds`;");
  1385. $this->safe_query("DROP TABLE `".$wpdb->prefix."lifestream_error_log`;");
  1386. $this->install_database();
  1387. }
  1388. function reschedule_cron()
  1389. {
  1390. wp_clear_scheduled_hook('lifestream_cron');
  1391. wp_clear_scheduled_hook('lifestream_cleanup');
  1392. wp_clear_scheduled_hook('lifestream_digest_cron');
  1393. wp_schedule_event(time()+60, 'daily', 'lifestream_cleanup');
  1394. // First lifestream cron should not happen instantly, incase we need to reschedule
  1395. wp_schedule_event(time()+60, 'lifestream', 'lifestream_cron');
  1396. // We have to calculate the time for the first digest
  1397. $digest_time = $this->get_option('digest_time');
  1398. $digest_interval = $this->get_option('digest_interval');
  1399. $time = time();
  1400. if ($digest_interval == 'hourly')
  1401. {
  1402. // Start at the next hour
  1403. $time = strtotime(date('Y-m-d H:00:00', strtotime('+1 hour', $time)));
  1404. }
  1405. else
  1406. {
  1407. // If time has already passed for today, set it for tomorrow
  1408. if (date('H') > $digest_time)
  1409. {
  1410. $time = strtotime('+1 day', $time);
  1411. }
  1412. else
  1413. {
  1414. $time = strtotime(date('Y-m-d '.$digest_time.':00:00', $time));
  1415. }
  1416. }
  1417. wp_schedule_event($time, 'lifestream_digest', 'lifestream_digest_cron');
  1418. }
  1419. function deactivate()
  1420. {
  1421. wp_clear_scheduled_hook('lifestream_cron');
  1422. wp_clear_scheduled_hook('lifestream_cleanup');
  1423. wp_clear_scheduled_hook('lifestream_digest_cron');
  1424. }
  1425. /**
  1426. * Initializes the plug-in upon activation.
  1427. */
  1428. function activate()
  1429. {
  1430. global $wpdb, $userdata;
  1431. get_currentuserinfo();
  1432. // Options/database install
  1433. $this->install();
  1434. // Add a feed for this blog
  1435. $results =& $wpdb->get_results("SELECT COUNT(*) as `count` FROM `".$wpdb->prefix."lifestream_feeds`");
  1436. if (!$results[0]->count)
  1437. {
  1438. $rss_url = get_bloginfo('rss2_url');
  1439. $options = array('url' => $rss_url);
  1440. $feed = new Lifestream_BlogFeed($this, $options);
  1441. $feed->owner = $userdata->display_name;
  1442. $feed->owner_id = $userdata->ID;
  1443. $feed->save(false);
  1444. }
  1445. // Cron job for the update
  1446. $this->reschedule_cron();
  1447. }
  1448. function credits()
  1449. {
  1450. return 'Powered by <a href="http://www.enthropia.com/labs/wp-lifestream/">Lifestream</a>.';
  1451. }
  1452. /**
  1453. * Adds/updates the options on plug-in activation.
  1454. */
  1455. function install($allow_database_install=true)
  1456. {
  1457. $version = (string)$this->get_option('_version', 0);
  1458. if ($allow_database_install)
  1459. {
  1460. $this->install_database($version);
  1461. }
  1462. if (version_compare($version, '0.95', '<'))
  1463. {
  1464. foreach ($this->_options as $key=>$value)
  1465. {
  1466. $ovalue = get_option('lifestream_' . $key);
  1467. if (!$ovalue)
  1468. {
  1469. $value = $value;
  1470. }
  1471. else
  1472. {
  1473. delete_option('lifestream_' . $key);
  1474. }
  1475. $this->add_option($key, $value);
  1476. }
  1477. }
  1478. // default options and their values
  1479. foreach ($this->_options as $key=>$value)
  1480. {
  1481. $this->add_option($key, $value);
  1482. }
  1483. // because these are based off of the WP_CONTENT_DIR they cannot be included in $_options
  1484. $this->add_option('extension_dir', WP_CONTENT_DIR.'/wp-lifestream/extensions/');
  1485. $this->add_option('theme_dir', WP_CONTENT_DIR.'/wp-lifestream/themes/');
  1486. $this->add_option('icon_dir', WP_CONTENT_DIR.'/wp-lifestream/icons/');
  1487. if (version_compare($version, LIFESTREAM_VERSION, '=')) return;
  1488. $this->update_option('_version', LIFESTREAM_VERSION);
  1489. }
  1490. /**
  1491. * Executes a MySQL query with exception handling.
  1492. */
  1493. function safe_query($sql)
  1494. {
  1495. global $wpdb;
  1496. $result = $wpdb->query($sql);
  1497. if ($result === false)
  1498. {
  1499. if ($wpdb->error)
  1500. {
  1501. $reason = $wpdb->error->get_error_m

Large files files are truncated, but you can click here to view the full file