PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/inc/core.php

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

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