SHARE
TWEET

Testsite sermon.php copied

a guest Feb 1st, 2013 42 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /*
  3. Plugin Name: Sermon Browser
  4. Plugin URI: http://www.sermonbrowser.com/
  5. Description: Upload sermons to your website, where they can be searched, listened to, and downloaded. Easy to use with comprehensive help and tutorials.
  6. Author: Mark Barnes
  7. Version: 0.45.4
  8. Author URI: http://www.4-14.org.uk/
  9.  
  10. Copyright (c) 2008-2011 Mark Barnes
  11.  
  12. This program is free software: you can redistribute it and/or modify
  13. it under the terms of the GNU General Public License as published by
  14. the Free Software Foundation, either version 3 of the License, or
  15. (at your option) any later version.
  16.  
  17. This program is distributed in the hope that it will be useful,
  18. but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  20. GNU General Public License for more details.
  21.  
  22. You should have received a copy of the GNU General Public License
  23. along with this program.  If not, see <http://www.gnu.org/licenses/>.
  24.  
  25. The structure of this plugin is as follows:
  26. ===========================================
  27. MAIN FILES
  28. ----------
  29. sermon.php     - This file. Contains common functions and initialisation routines.
  30. admin.php      - Functions required in the admin pages.
  31. frontend.php   - Functions required in the frontend (non-admin) pages.
  32.  
  33. OTHER FILES
  34. -----------
  35. ajax.php       - Handles AJAX returns.
  36. dictionary.php - Translates the template tags into php code. Used only when saving a template.
  37. filetypes.php  - User-editable file, which returns the correct mime-type for common file-extensions.
  38. php4compat.php - Small number of functions required for PHP4 compatibility
  39. podcast.php    - Handles the podcast feed
  40. sb-install.php - Used only when installing the plugin for the first time
  41. style.php      - Outputs the custom stylesheet
  42. uninstall.php  - Removes the plugin and its databases tables and rows
  43. upgrade.php    - Runs only when upgrading from earlier versions of SermonBrowser
  44.  
  45. If you want to follow the logic of the code, start with sb_sermon_init, and trace the Wordpress actions and filters.
  46. The frontend output is inserted by sb_shortcode
  47.  
  48. */
  49.  
  50. /**
  51. * Initialisation
  52. *
  53. * Sets version constants and basic Wordpress hooks.
  54. * @package common_functions
  55. */
  56. define('SB_CURRENT_VERSION', '0.45.4');
  57. define('SB_DATABASE_VERSION', '1.7');
  58. sb_define_constants();
  59. add_action ('plugins_loaded', 'sb_hijack');
  60. add_action ('init', 'sb_sermon_init');
  61. add_action ('widgets_init', 'sb_widget_sermon_init');
  62.  
  63. if (version_compare(PHP_VERSION, '5.0.0', '<'))
  64.         require(SB_INCLUDES_DIR.'/php4compat.php');
  65.  
  66. /**
  67. * Display podcast, or download linked files
  68. *
  69. * Intercepts Wordpress at earliest opportunity. Checks whether the following are required before the full framework is loaded:
  70. * Ajax data, stylesheet, file download
  71. */
  72. function sb_hijack() {
  73.  
  74.         global $filetypes, $wpdb, $sermon_domain;
  75.  
  76.         if (function_exists('wp_timezone_supported') && wp_timezone_supported())
  77.                 wp_timezone_override_offset();
  78.  
  79.         if (isset($_POST['sermon']) && $_POST['sermon'] == 1)
  80.                 require(SB_INCLUDES_DIR.'/ajax.php');
  81.         if (stripos($_SERVER['REQUEST_URI'], 'sb-style.css') !== FALSE || isset($_GET['sb-style']))
  82.                 require(SB_INCLUDES_DIR.'/style.php');
  83.  
  84.         //Forces sermon download of local file
  85.         if (isset($_GET['download']) AND isset($_GET['file_name'])) {
  86.                 $file_name = $wpdb->escape(rawurldecode($_GET['file_name']));
  87.                 $file_name = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}sb_stuff WHERE name='{$file_name}'");
  88.                 if (!is_null($file_name)) {
  89.                         header("Pragma: public");
  90.                         header("Expires: 0");
  91.                         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  92.                         header("Content-Type: application/force-download");
  93.                         header("Content-Type: application/octet-stream");
  94.                         header("Content-Type: application/download");
  95.                         header('Content-Disposition: attachment; filename="'.$file_name.'";');
  96.                         header("Content-Transfer-Encoding: binary");
  97.                         sb_increase_download_count ($file_name);
  98.                         $file_name = SB_ABSPATH.sb_get_option('upload_dir').$file_name;
  99.                         $filesize = filesize($file_name);
  100.                         if ($filesize != 0)
  101.                                 header("Content-Length: ".filesize($file_name));
  102.                         output_file($file_name);
  103.                         die();
  104.                 } else
  105.                         wp_die(htmlentities(rawurldecode($_GET['file_name'])).' '.__('not found', $sermon_domain), __('File not found', $sermon_domain), array('response' => 404));
  106.         }
  107.  
  108.         //Forces sermon download of external URL
  109.         if (isset($_REQUEST['download']) AND isset($_REQUEST['url'])) {
  110.                 $url = rawurldecode($_GET['url']);
  111.                 if(ini_get('allow_url_fopen')) {
  112.                         $headers = @get_headers($url, 1);
  113.                         if ($headers === FALSE || (isset($headers[0]) && strstr($headers[0], '404') !== FALSE))
  114.                                 wp_die(htmlentities(rawurldecode($_GET['url'])).' '.__('not found', $sermon_domain), __('URL not found', $sermon_domain), array('response' => 404));
  115.                         $headers = array_change_key_case($headers,CASE_LOWER);
  116.                         if (isset($headers['location'])) {
  117.                                 $location =  $headers['location'];
  118.                                 if (is_array($location))
  119.                                         $location = $location[0];
  120.                                 if ($location && substr($location,0,7) != "http://") {
  121.                                         preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
  122.                                         $location = "http://".$matches[1].'/'.$location;
  123.                                 }
  124.                                 if ($location) {
  125.                                         header('Location: '.site_url().'?download&url='.$location);
  126.                                         die();
  127.                                 }
  128.                         }
  129.                         header("Pragma: public");
  130.                         header("Expires: 0");
  131.                         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  132.                         header("Content-Type: application/force-download");
  133.                         header("Content-Type: application/octet-stream");
  134.                         header("Content-Type: application/download");
  135.                         if (isset($headers['last-modified']))
  136.                                 header('Last-Modified: '.$headers['last-modified']);
  137.                         if (isset($headers['content-length']))
  138.                                 header("Content-Length: ".$headers['content-length']);
  139.                         if (isset($headers['content-disposition']))
  140.                                 header ('Content-Disposition: '.$headers['content-disposition']);
  141.                         else
  142.                                 header('Content-Disposition: attachment; filename="'.basename($url).'";');
  143.                         header("Content-Transfer-Encoding: binary");
  144.                         header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
  145.                         sb_increase_download_count($url);
  146.                         session_write_close();
  147.                         while (@ob_end_clean());
  148.                         output_file($url);
  149.                         die();
  150.                 } else {
  151.                         sb_increase_download_count ($url);
  152.                         header('Location: '.$url);
  153.                         die();
  154.                 }
  155.         }
  156.  
  157.         //Returns local file (doesn't force download)
  158.         if (isset($_GET['show']) AND isset($_GET['file_name'])) {
  159.                 global $filetypes;
  160.                 $file_name = $wpdb->escape(rawurldecode($_GET['file_name']));
  161.                 $file_name = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}sb_stuff WHERE name='{$file_name}'");
  162.                 if (!is_null($file_name)) {
  163.                         $url = sb_get_option('upload_url').$file_name;
  164.                         sb_increase_download_count ($file_name);
  165.                         header("Location: ".$url);
  166.                         die();
  167.                 } else
  168.                         wp_die(htmlentities(rawurldecode($_GET['file_name'])).' '.__('not found', $sermon_domain), __('File not found', $sermon_domain), array('response' => 404));
  169.         }
  170.  
  171.         //Returns contents of external URL(doesn't force download)
  172.         if (isset($_REQUEST['show']) AND isset($_REQUEST['url'])) {
  173.                 $url = rawurldecode($_GET['url']);
  174.                 sb_increase_download_count ($url);
  175.                 header('Location: '.$url);
  176.                 die();
  177.         }
  178. }
  179.  
  180. /**
  181. * Main initialisation function
  182. *
  183. * Sets up most Wordpress hooks and filters, depending on whether request is for front or back end.
  184. */
  185. function sb_sermon_init () {
  186.         global $sermon_domain, $wpdb, $defaultMultiForm, $defaultSingleForm, $defaultStyle;
  187.         $sermon_domain = 'sermon-browser';
  188.         if (IS_MU) {
  189.                         load_plugin_textdomain($sermon_domain, '', 'sb-includes');
  190.         } else {
  191.                         load_plugin_textdomain($sermon_domain, '', 'sermon-browser/sb-includes');
  192.         }
  193.         if (WPLANG != '')
  194.                 setlocale(LC_ALL, WPLANG.'.UTF-8');
  195.  
  196.         //Display the podcast if that's what's requested
  197.         if (isset($_GET['podcast']))
  198.                 require(SB_INCLUDES_DIR.'/podcast.php');
  199.  
  200.         // Register custom CSS and javascript files
  201.         wp_register_script('sb_64', SB_PLUGIN_URL.'/sb-includes/64.js', false, SB_CURRENT_VERSION);
  202.         wp_register_script('sb_datepicker', SB_PLUGIN_URL.'/sb-includes/datePicker.js', array('jquery'), SB_CURRENT_VERSION);
  203.         wp_register_style('sb_datepicker', SB_PLUGIN_URL.'/sb-includes/datepicker.css', false, SB_CURRENT_VERSION);
  204.         if (get_option('permalink_structure') == '')
  205.                 wp_register_style('sb_style', trailingslashit(site_url()).'?sb-style&', false, sb_get_option('style_date_modified'));
  206.         else
  207.                 wp_register_style('sb_style', trailingslashit(site_url()).'sb-style.css', false, sb_get_option('style_date_modified'));
  208.  
  209.         // Register [sermon] shortcode handler
  210.         add_shortcode('sermons', 'sb_shortcode');
  211.         add_shortcode('sermon', 'sb_shortcode');
  212.  
  213.         // Attempt to set php.ini directives
  214.         if (sb_return_kbytes(ini_get('upload_max_filesize'))<15360)
  215.                 ini_set('upload_max_filesize', '15M');
  216.         if (sb_return_kbytes(ini_get('post_max_size'))<15360)
  217.                 ini_set('post_max_size', '15M');
  218.         if (sb_return_kbytes(ini_get('memory_limit'))<49152)
  219.                 ini_set('memory_limit', '48M');
  220.         if (intval(ini_get('max_input_time'))<600)
  221.                 ini_set('max_input_time','600');
  222.         if (intval(ini_get('max_execution_time'))<600)
  223.                 ini_set('max_execution_time', '600');
  224.         if (ini_get('file_uploads')<>'1')
  225.                 ini_set('file_uploads', '1');
  226.  
  227.         // Check whether upgrade required
  228.         if (current_user_can('manage_options') && is_admin()) {
  229.                 if (get_option('sb_sermon_db_version'))
  230.                         $db_version = get_option('sb_sermon_db_version');
  231.                 else
  232.                         $db_version = sb_get_option('db_version');
  233.                 if ($db_version && $db_version != SB_DATABASE_VERSION) {
  234.                         require_once (SB_INCLUDES_DIR.'/upgrade.php');
  235.                         sb_database_upgrade ($db_version);
  236.                 } elseif (!$db_version) {
  237.                         require (SB_INCLUDES_DIR.'/sb-install.php');
  238.                         sb_install();
  239.                 }
  240.                 $sb_version = sb_get_option('code_version');
  241.                 if ($sb_version != SB_CURRENT_VERSION) {
  242.                         require_once (SB_INCLUDES_DIR.'/upgrade.php');
  243.                         sb_version_upgrade ($sb_version, SB_CURRENT_VERSION);
  244.                 }
  245.         }
  246.  
  247.         // Load shared (admin/frontend) features
  248.         add_action ('save_post', 'update_podcast_url');
  249.        
  250.         // Check to see what functions are required, and only load what is needed
  251.         if (stripos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE) {
  252.                 require (SB_INCLUDES_DIR.'/frontend.php');
  253.                 add_action('wp_head', 'sb_add_headers', 0);
  254.                 add_action('wp_head', 'wp_print_styles', 9);
  255.                 add_action('admin_bar_menu', 'sb_admin_bar_menu', 45);
  256.                 add_filter('wp_title', 'sb_page_title');
  257.                 if (defined('SAVEQUERIES') && SAVEQUERIES)
  258.                         add_action ('wp_footer', 'sb_footer_stats');
  259.         } else {
  260.                 require (SB_INCLUDES_DIR.'/admin.php');
  261.                 add_action ('admin_menu', 'sb_add_pages');
  262.                 add_action ('rightnow_end', 'sb_rightnow');
  263.                 add_action('admin_init', 'sb_add_admin_headers');
  264.                 add_filter('contextual_help', 'sb_add_contextual_help');
  265.                 if (defined('SAVEQUERIES') && SAVEQUERIES)
  266.                         add_action('admin_footer', 'sb_footer_stats');
  267.         }
  268. }
  269.  
  270. /**
  271. * Add Sermons menu and sub-menus in admin
  272. */
  273. function sb_add_pages() {
  274.         global $sermon_domain;
  275.         add_menu_page(__('Sermons', $sermon_domain), __('Sermons', $sermon_domain), 'publish_posts', __FILE__, 'sb_manage_sermons', SB_PLUGIN_URL.'/sb-includes/sb-icon.png');
  276.         add_submenu_page(__FILE__, __('Sermons', $sermon_domain), __('Sermons', $sermon_domain), 'publish_posts', __FILE__, 'sb_manage_sermons');
  277.         if (isset($_REQUEST['page']) && $_REQUEST['page'] == 'sermon-browser/new_sermon.php' && isset($_REQUEST['mid'])) {
  278.                 add_submenu_page(__FILE__, __('Edit Sermon', $sermon_domain), __('Edit Sermon', $sermon_domain), 'publish_posts', 'sermon-browser/new_sermon.php', 'sb_new_sermon');
  279.         } else {
  280.                 add_submenu_page(__FILE__, __('Add Sermon', $sermon_domain), __('Add Sermon', $sermon_domain), 'publish_posts', 'sermon-browser/new_sermon.php', 'sb_new_sermon');
  281.         }
  282.         add_submenu_page(__FILE__, __('Files', $sermon_domain), __('Files', $sermon_domain), 'upload_files', 'sermon-browser/files.php', 'sb_files');
  283.         add_submenu_page(__FILE__, __('Preachers', $sermon_domain), __('Preachers', $sermon_domain), 'manage_categories', 'sermon-browser/preachers.php', 'sb_manage_preachers');
  284.         add_submenu_page(__FILE__, __('Series &amp; Services', $sermon_domain), __('Series &amp; Services', $sermon_domain), 'manage_categories', 'sermon-browser/manage.php', 'sb_manage_everything');
  285.         add_submenu_page(__FILE__, __('Options', $sermon_domain), __('Options', $sermon_domain), 'manage_options', 'sermon-browser/options.php', 'sb_options');
  286.         add_submenu_page(__FILE__, __('Templates', $sermon_domain), __('Templates', $sermon_domain), 'manage_options', 'sermon-browser/templates.php', 'sb_templates');
  287.         add_submenu_page(__FILE__, __('Uninstall', $sermon_domain), __('Uninstall', $sermon_domain), 'edit_plugins', 'sermon-browser/uninstall.php', 'sb_uninstall');
  288.         add_submenu_page(__FILE__, __('Help', $sermon_domain), __('Help', $sermon_domain), 'publish_posts', 'sermon-browser/help.php', 'sb_help');
  289.         add_submenu_page(__FILE__, __('Pray for Japan', $sermon_domain), __('Pray for Japan', $sermon_domain), 'publish_posts', 'sermon-browser/japan.php', 'sb_japan');
  290. }
  291.  
  292. /**
  293. * Converts php.ini mega- or giga-byte numbers into kilobytes
  294. *
  295. * @param string $val
  296. * @return integer
  297. */
  298. function sb_return_kbytes($val) {
  299.         $val = trim($val);
  300.         $last = strtolower($val[strlen($val)-1]);
  301.         switch($last) {
  302.                 case 'g':
  303.                         $val *= 1024;
  304.                 case 'm':
  305.                         $val *= 1024;
  306.         }
  307.    return intval($val);
  308. }
  309.  
  310. /**
  311. * Count download stats for sermon
  312. *
  313. * Returns the number of plays for a particular file
  314. *
  315. * @param integer $sermonid
  316. * @return integer
  317. */
  318. function sb_sermon_stats($sermonid) {
  319.         global $wpdb;
  320.         $stats = $wpdb->get_var("SELECT SUM(count) FROM ".$wpdb->prefix."sb_stuff WHERE sermon_id=".$sermonid);
  321.         if ($stats > 0)
  322.                 return $stats;
  323. }
  324.  
  325. /**
  326. * Updates podcast URL in wp_options
  327. *
  328. * Function required if permalinks changed or [sermons] added to a different page
  329. */
  330.  function update_podcast_url () {
  331.         global $wp_rewrite;
  332.         $existing_url = sb_get_option('podcast_url');
  333.         if (substr($existing_url, 0, strlen(site_url())) == site_url()) {
  334.                 if (sb_display_url(TRUE)=="") {
  335.                         sb_update_option('podcast_url', site_url().sb_query_char(false).'podcast');
  336.                 } else {
  337.                         sb_update_option('podcast_url', sb_display_url().sb_query_char(false).'podcast');
  338.                 }
  339.         }
  340. }
  341.  
  342. /**
  343. * Returns occassionally requested default values
  344. *
  345. * Not defined as constants to save memory
  346. * @param string $default_type
  347. * @return mixed
  348. */
  349. function sb_get_default ($default_type) {
  350.         global $sermon_domain;
  351.         switch ($default_type) {
  352.                 case 'sermon_path':
  353.                         $upload_path = wp_upload_dir();
  354.                         $upload_path = $upload_path['basedir'];
  355.                         if (substr($upload_path, 0, strlen(ABSPATH)) == ABSPATH)
  356.                                 $upload_path = substr($upload_path, strlen(ABSPATH));
  357.                         return trailingslashit($upload_path).'sermons/';
  358.                 case 'attachment_url':
  359.                         $upload_dir = wp_upload_dir();
  360.                         $upload_dir = $upload_dir['baseurl'];
  361.                         return trailingslashit($upload_dir).'sermons/';
  362.                 case 'bible_books':
  363.                         return array(__('1. Moos.', $sermon_domain), __('2. Moos.', $sermon_domain), __('3. Moos.', $sermon_domain), __('4. Moos.', $sermon_domain), __('5. Moos.', $sermon_domain), __('Joos.', $sermon_domain), __('Tuom.', $sermon_domain), __('Ruut', $sermon_domain), __('1 Sam.', $sermon_domain), __('2 Sam.', $sermon_domain), __('1 Kun.', $sermon_domain), __('2 Kun.', $sermon_domain), __('1 Aik.', $sermon_domain), __('2 Aik.',$sermon_domain), __('Esra', $sermon_domain), __('Neh.', $sermon_domain), __('Est.', $sermon_domain), __('Job', $sermon_domain), __('Ps.', $sermon_domain), __('Sananl.', $sermon_domain), __('Saarn.', $sermon_domain), __('Laul. l.', $sermon_domain), __('Isaiah', $sermon_domain), __('Jeremiah', $sermon_domain), __('Lamentations', $sermon_domain), __('Ezekiel', $sermon_domain), __('Daniel', $sermon_domain), __('Hosea', $sermon_domain), __('Joel', $sermon_domain), __('Amos', $sermon_domain), __('Obadiah', $sermon_domain), __('Jonah', $sermon_domain), __('Micah', $sermon_domain), __('Nahum', $sermon_domain), __('Habakkuk', $sermon_domain), __('Zephaniah', $sermon_domain), __('Haggai', $sermon_domain), __('Zechariah', $sermon_domain), __('Malachi', $sermon_domain), __('Matthew', $sermon_domain), __('Mark', $sermon_domain), __('Luke', $sermon_domain), __('John', $sermon_domain), __('Acts', $sermon_domain), __('Romans', $sermon_domain), __('1 Corinthians', $sermon_domain), __('2 Corinthians', $sermon_domain), __('Galatians', $sermon_domain), __('Ephesians', $sermon_domain), __('Philippians', $sermon_domain), __('Colossians', $sermon_domain), __('1 Thessalonians', $sermon_domain), __('2 Thessalonians', $sermon_domain), __('1 Timothy', $sermon_domain), __('2 Timothy', $sermon_domain), __('Titus', $sermon_domain), __('Philemon', $sermon_domain), __('Hebrews', $sermon_domain), __('James', $sermon_domain), __('1 Peter', $sermon_domain), __('2 Peter', $sermon_domain), __('1 John', $sermon_domain), __('2 John', $sermon_domain), __('3 John', $sermon_domain), __('Jude', $sermon_domain), __('Revelation', $sermon_domain));
  364.                 case 'eng_bible_books':
  365.                         return array('1. Moos.', '2. Moos.', '3. Moos.', '4. Moos.', '5. Moos.', 'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel', '1 Kings', '2 Kings', '1 Chronicles', '2 Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalm', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremiah', 'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah', 'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah', 'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', '1 Thessalonians', '2 Thessalonians', '1 Timothy', '2 Timothy', 'Titus', 'Philemon', 'Hebrews', 'James', '1 Peter', '2 Peter', '1 John', '2 John', '3 John', 'Jude', 'Revelation');
  366.         }
  367. }
  368.  
  369. /**
  370. * Returns true if sermons are displayed on the current page
  371. *
  372. * @return bool
  373. */
  374. function sb_display_front_end() {
  375.         global $wpdb, $post;
  376.         $pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%[sermon%' AND (post_status = 'publish' OR post_status = 'private') AND ID={$post->ID} AND post_date < NOW();");
  377.         if ($pageid === NULL)
  378.                 return FALSE;
  379.         else
  380.                 return TRUE;
  381. }
  382.  
  383. /**
  384. * Get the page_id of the main sermons page
  385. *
  386. * @return integer
  387. */
  388. function sb_get_page_id() {
  389.         global $wpdb, $post;
  390.         $pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE (post_content LIKE '%[sermons]%' OR post_content LIKE '%[sermon]%') AND (post_status = 'publish' OR post_status = 'private') AND post_date < NOW();");
  391.         if (!$pageid)
  392.                 $pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE (post_content LIKE '%[sermon %' OR post_content LIKE '%[sermons %') AND (post_status = 'publish' OR post_status = 'private') AND post_date < NOW();");
  393.         if (!$pageid)
  394.                 return 0;
  395.         else
  396.                 return intval($pageid);
  397. }
  398.  
  399. /**
  400. * Get the URL of the main sermons page
  401. *
  402. * @return string
  403. */
  404. function sb_display_url() {
  405.         global $wpdb, $post, $sb_display_url;
  406.         if ($sb_display_url == '') {
  407.                 $pageid = sb_get_page_id();
  408.                 if ($pageid == 0)
  409.                         return '';
  410.                 if (defined('SB_AJAX') && SB_AJAX)
  411.                         return site_url().'/?page_id='.$pageid; // Don't use permalinks in Ajax calls
  412.                 else {
  413.                         $sb_display_url = get_permalink($pageid);
  414.                         if ($sb_display_url == site_url() || $sb_display_url == '') // Hack to force true permalink even if page used for front page.
  415.                                 $sb_display_url = site_url().'/?page_id='.$pageid;
  416.                         }
  417.         }
  418.         return $sb_display_url;
  419. }
  420.  
  421. /**
  422. * Fix to ensure AudioPlayer v2 and AudioPlayer v1 both work
  423. */
  424. if (!function_exists('ap_insert_player_widgets') && function_exists('insert_audio_player')) {
  425.         function ap_insert_player_widgets($params) {
  426.                 return insert_audio_player($params);
  427.         }
  428. }
  429.  
  430. /**
  431. * Adds database statistics to the HTML comments
  432. *
  433. * Requires define('SAVEQUERIES', true) in wp-config.php
  434. * Useful for diagnostics
  435. */
  436. function sb_footer_stats() {
  437.         global $wpdb;
  438.         echo '<!-- ';
  439.         echo($wpdb->num_queries.' queries. '.timer_stop().' seconds.');
  440.         echo chr(13);
  441.         print_r($wpdb->queries);
  442.         echo chr(13);
  443.         echo ' -->';
  444. }
  445.  
  446. /**
  447. * Returns the correct string to join the sermonbrowser parameters to the existing URL
  448. *
  449. * @param boolean $return_entity
  450. * @return string (either '?', '&', or '&amp;')
  451. */
  452. function sb_query_char ($return_entity = true) {
  453.         if (strpos(sb_display_url(), '?')===FALSE)
  454.                 return '?';
  455.         else
  456.                 if ($return_entity)
  457.                         return '&amp;';
  458.                 else
  459.                         return '&';
  460. }
  461.  
  462. /**
  463. * Create the shortcode handler
  464. *
  465. * Standard shortcode handler that inserts the sermonbrowser output into the post/page
  466. *
  467. * @param array $atts
  468. * @param string $content
  469. * @return string
  470. */
  471. function sb_shortcode($atts, $content=null) {
  472.         global $wpdb, $record_count, $sermon_domain;
  473.         ob_start();
  474.         $atts = shortcode_atts(array(
  475.                 'filter' => sb_get_option('filter_type'),
  476.                 'filterhide' => sb_get_option('filter_hide'),
  477.                 'id' => isset($_REQUEST['sermon_id']) ? $_REQUEST['sermon_id'] : '',
  478.                 'preacher' => isset($_REQUEST['preacher']) ? $_REQUEST['preacher'] : '',
  479.                 'series' => isset($_REQUEST['series']) ? $_REQUEST['series'] : '',
  480.                 'book' => isset($_REQUEST['book']) ? stripslashes($_REQUEST['book']) : '',
  481.                 'service' => isset($_REQUEST['service']) ? $_REQUEST['service'] : '',
  482.                 'date' => isset($_REQUEST['date']) ? $_REQUEST['date'] : '',
  483.                 'enddate' => isset($_REQUEST['enddate']) ? $_REQUEST['enddate'] : '',
  484.                 'tag' => isset($_REQUEST['stag']) ? stripslashes($_REQUEST['stag']) : '',
  485.                 'title' => isset($_REQUEST['title']) ? stripslashes($_REQUEST['title']) : '',
  486.                 'limit' => '0',
  487.                 'dir' => isset($_REQUEST['dir']) ? stripslashes($_REQUEST['dir']) : '', ),
  488.         $atts);
  489.         if ($atts['id'] != '') {
  490.                 if (strtolower($atts['id']) == 'latest') {
  491.                         $atts['id'] = '';
  492.                         $wpdb->query('SET SQL_BIG_SELECTS=1');
  493.                         $query = $wpdb->get_results(sb_create_multi_sermon_query($atts, array(), 1, 1));
  494.                         $atts['id'] = $query[0]->id;
  495.                 }
  496.                 $sermon = sb_get_single_sermon((int) $atts['id']);
  497.                 if ($sermon)
  498.                         eval('?>'.sb_get_option('single_output'));
  499.                 else {
  500.                         echo "<div class=\"sermon-browser-results\"><span class=\"error\">";
  501.                         _e ('No sermons found.', $sermon_domain);
  502.                         echo "</span></div>";
  503.                 }
  504.         } else {
  505.                 if (isset($_REQUEST['sortby']))
  506.                         $sort_criteria = $wpdb->escape($_REQUEST['sortby']);
  507.                 else
  508.                         $sort_criteria = 'm.datetime';
  509.                 if (!empty($atts['dir']))
  510.                         $dir = $wpdb->escape($atts['dir']);
  511.                 elseif ($sort_criteria == 'm.datetime')
  512.                         $dir = 'desc';
  513.                 else
  514.                         $dir = 'asc';
  515.                 $sort_order = array('by' => $sort_criteria, 'dir' =>  $dir);
  516.                 if (isset($_REQUEST['page']))
  517.                         $page = $_REQUEST['page'];
  518.                 else
  519.                         $page = 1;
  520.                 $hide_empty = sb_get_option('hide_no_attachments');
  521.                 $sermons = sb_get_sermons($atts, $sort_order, $page, (int)$atts['limit'], $hide_empty);
  522.                 $output = '?>'.sb_get_option('search_output');
  523.                 eval($output);
  524.         }
  525.         $content = ob_get_contents();
  526.         ob_end_clean();
  527.         return $content;
  528. }
  529.  
  530. /**
  531. * Registers the Sermon Browser widgets
  532. */
  533. function sb_widget_sermon_init() {
  534.         global $sermon_domain;
  535.         //Sermons Widget
  536.         if (!$options = sb_get_option('sermons_widget_options'))
  537.                 $options = array();
  538.         $widget_ops = array('classname' => 'sermon', 'description' => __('Display a list of recent sermons.', $sermon_domain));
  539.         $control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'sermon');
  540.         $name = __('Sermons', $sermon_domain);
  541.         $registered = false;
  542.         foreach (array_keys($options) as $o) {
  543.                 if (!isset($options[$o]['limit']))
  544.                         continue;
  545.                 $id = "sermon-$o";
  546.                 $registered = true;
  547.                 wp_register_sidebar_widget($id, $name, 'sb_widget_sermon_wrapper', $widget_ops, array('number' => $o));
  548.                 wp_register_widget_control($id, $name, 'sb_widget_sermon_control', $control_ops, array('number' => $o));
  549.         }
  550.         if (!$registered) {
  551.                 wp_register_sidebar_widget('sermon-1', $name, 'sb_widget_sermon_wrapper', $widget_ops, array('number' => -1));
  552.                 wp_register_widget_control('sermon-1', $name, 'sb_widget_sermon_control', $control_ops, array('number' => -1));
  553.         }
  554.         //Tags Widget
  555.         wp_register_sidebar_widget('sermon-browser-tags', __('Sermon Browser tags', $sermon_domain), 'sb_widget_tag_cloud_wrapper');
  556.         //Most popular widget
  557.         $name = __('Most popular sermons', $sermon_domain);
  558.         $description = __('Display a list of the most popular sermons, series or preachers.', $sermon_domain);
  559.         $widget_ops = array('classname' => 'sermon-browser-popular', 'description' => $description);
  560.         $control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'sermon-browser-popular');
  561.         wp_register_sidebar_widget( 'sermon-browser-popular', $name, 'sb_widget_popular_wrapper', $widget_ops);
  562.         wp_register_widget_control( 'sermon-browser-popular', $name, 'sb_widget_popular_control', $control_ops);
  563. }
  564.  
  565. /**
  566. * Wrapper for sb_widget_sermon in frontend.php
  567. *
  568. * Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
  569. * @param array $args
  570. * @param integer $widget_args
  571. */
  572. function sb_widget_sermon_wrapper ($args, $widget_args = 1) {
  573.         require_once (SB_INCLUDES_DIR.'/frontend.php');
  574.         sb_widget_sermon($args, $widget_args);
  575. }
  576.  
  577. /**
  578. * Wrapper for sb_widget_tag_cloud in frontend.php
  579. *
  580. * Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
  581. * @param array $args
  582. */
  583. function sb_widget_tag_cloud_wrapper ($args) {
  584.         require_once (SB_INCLUDES_DIR.'/frontend.php');
  585.         sb_widget_tag_cloud ($args);
  586. }
  587.  
  588. /**
  589. * Wrapper for sb_widget_popular in frontend.php
  590. *
  591. * Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
  592. * @param array $args
  593. */
  594. function sb_widget_popular_wrapper ($args) {
  595.         require_once (SB_INCLUDES_DIR.'/frontend.php');
  596.         sb_widget_popular ($args);
  597. }
  598.  
  599. /**
  600. * Optimised replacement for get_option
  601. *
  602. * Returns any of the sermonbrowser options from one row of the database
  603. * Large options (e.g. the template) are stored on additional rows by this function
  604. * @param string $type
  605. * @return mixed
  606. */
  607. function sb_get_option($type) {
  608.         global $sermonbrowser_options;
  609.         $special_options = sb_special_option_names();
  610.         if (in_array($type, $special_options)) {
  611.                 return stripslashes(base64_decode(get_option("sermonbrowser_{$type}")));
  612.         } else {
  613.                 if (!$sermonbrowser_options) {
  614.                         $options = get_option('sermonbrowser_options');
  615.                         if ($options === FALSE)
  616.                                 return FALSE;
  617.                         $sermonbrowser_options = unserialize(base64_decode($options));
  618.                         if ($sermonbrowser_options === FALSE)
  619.                                 wp_die ('Failed to get SermonBrowser options '.base64_decode(get_option('sermonbrowser_options')));
  620.                 }
  621.                 if (isset($sermonbrowser_options[$type]))
  622.                         return $sermonbrowser_options[$type];
  623.                 else
  624.                         return '';
  625.         }
  626. }
  627.  
  628. /**
  629. * Optimised replacement for update_option
  630. *
  631. * Stores all of sermonbrowser options on one row of the database
  632. * Large options (e.g. the template) are stored on additional rows by this function
  633. * @param string $type
  634. * @param mixed $val
  635. * @return bool
  636. */
  637. function sb_update_option($type, $val) {
  638.         global $sermonbrowser_options;
  639.         $special_options = sb_special_option_names();
  640.         if (in_array($type, $special_options))
  641.                 return update_option ("sermonbrowser_{$type}", base64_encode($val));
  642.         else {
  643.                 if (!$sermonbrowser_options) {
  644.                         $options = get_option('sermonbrowser_options');
  645.                         if ($options !== FALSE) {
  646.                                 $sermonbrowser_options = unserialize(base64_decode($options));
  647.                                 if ($sermonbrowser_options === FALSE)
  648.                                         wp_die ('Failed to get SermonBrowser options '.base64_decode(get_option('sermonbrowser_options')));
  649.                         }
  650.                 }
  651.                 if (!isset($sermonbrowser_options[$type]) || $sermonbrowser_options[$type] !== $val) {
  652.                         $sermonbrowser_options[$type] = $val;
  653.                         return update_option('sermonbrowser_options', base64_encode(serialize($sermonbrowser_options)));
  654.                 } else
  655.                         return false;
  656.         }
  657. }
  658.  
  659. /**
  660. * Returns which options need to be stored in individual base64 format (i.e. potentially large strings)
  661. *
  662. * @return array
  663. */
  664. function sb_special_option_names() {
  665.         return array ('single_template', 'single_output', 'search_template', 'search_output', 'css_style');
  666. }
  667.  
  668. /**
  669. * Recursive mkdir function
  670. *
  671. * @param string $pathname
  672. * @param string $mode
  673. * return bool
  674. */
  675. function sb_mkdir($pathname, $mode=0777) {
  676.         is_dir(dirname($pathname)) || sb_mkdir(dirname($pathname), $mode);
  677.         @mkdir($pathname, $mode);
  678.         return @chmod($pathname, $mode);
  679. }
  680.  
  681. /**
  682. * Defines a number of constants used throughout the plugin
  683. */
  684. function sb_define_constants() {
  685.         $directories = explode(DIRECTORY_SEPARATOR,dirname(__FILE__));
  686.         if ($plugin_dir = $directories[count($directories)-1] == 'mu-plugins' || (function_exists('is_multisite') && is_multisite())) {
  687.                 define('IS_MU', TRUE);
  688.         } else {
  689.                 define('IS_MU', FALSE);
  690.         }
  691.         if ($directories[count($directories)-1] == 'mu-plugins' )
  692.                 define ('SB_PLUGIN_URL', content_url().'/'.$plugin_dir);
  693.         else
  694.                 define ('SB_PLUGIN_URL', rtrim(content_url().'/plugins/'.plugin_basename(dirname(__FILE__)), '/'));
  695.         define ('SB_PLUGIN_DIR', sb_sanitise_path(defined('WP_CONTENT_DIR') ? WP_CONTENT_DIR : ABSPATH.'wp-content').'/plugins');
  696.         define ('SB_WP_CONTENT_DIR', sb_sanitise_path(WP_CONTENT_DIR));
  697.         define ('SB_INCLUDES_DIR', SB_PLUGIN_DIR.'/sermon-browser/sb-includes');
  698.         define ('SB_ABSPATH', sb_sanitise_path(ABSPATH));
  699.         define ('GETID3_INCLUDEPATH', SB_PLUGIN_DIR.'/'.plugin_basename(dirname(__FILE__)).'/sb-includes/getid3/');
  700.         define ('GETID3_HELPERAPPSDIR', GETID3_INCLUDEPATH);
  701. }
  702.  
  703. /**
  704. * Returns list of bible books from the database
  705. *
  706. * @return array
  707. */
  708. function sb_get_bible_books () {
  709.         global $wpdb;
  710.         return $wpdb->get_col("SELECT name FROM {$wpdb->prefix}sb_books order by id");
  711. }
  712.  
  713. /**
  714. * Get multiple sermons from the database
  715. *
  716. * Uses sb_create_multi_sermon_query to general the SQL statement
  717. * @param array $filter
  718. * @param string $order
  719. * @param integer $page
  720. * @param integer $limit
  721. * @global integer record_count
  722. * @return array
  723. */
  724. function sb_get_sermons($filter, $order, $page = 1, $limit = 0, $hide_empty = false) {
  725.         global $wpdb, $record_count;
  726.         if ($limit == 0)
  727.                 $limit = sb_get_option('sermons_per_page');
  728.         $wpdb->query('SET SQL_BIG_SELECTS=1');
  729.         $query = $wpdb->get_results(sb_create_multi_sermon_query($filter, $order, $page, $limit, $hide_empty));
  730.         $record_count = $wpdb->get_var("SELECT FOUND_ROWS()");
  731.         return $query;
  732. }
  733.  
  734. /**
  735. * Create SQL query for returning multiple sermons
  736. *
  737. * @param array $filter
  738. * @param string $order
  739. * @param integer $page
  740. * @param integer $limit
  741. * @return string SQL query
  742. */
  743. function sb_create_multi_sermon_query ($filter, $order, $page = 1, $limit = 0, $hide_empty = false) {
  744.         global $wpdb;
  745.         $default_filter = array(
  746.                 'title' => '',
  747.                 'preacher' => 0,
  748.                 'date' => '',
  749.                 'enddate' => '',
  750.                 'series' => 0,
  751.                 'service' => 0,
  752.                 'book' => '',
  753.                 'tag' => '',
  754.                 'id' => '',
  755.         );
  756.         $default_order = array(
  757.                 'by' => 'm.datetime',
  758.                 'dir' => 'desc',
  759.         );
  760.         $bs = '';
  761.         $filter = array_merge($default_filter, (array)$filter);
  762.         $order = array_merge($default_order, (array)$order);
  763.         $page = (int) $page;
  764.         $cond = '1=1 ';
  765.         if ($filter['title'] != '') {
  766.                 $cond .= "AND (m.title LIKE '%" . $wpdb->escape($filter['title']) . "%' OR m.description LIKE '%" . $wpdb->escape($filter['title']). "%' OR t.name LIKE '%" . $wpdb->escape($filter['title']) . "%') ";
  767.         }
  768.         if ($filter['preacher'] != 0) {
  769.                 $cond .= 'AND m.preacher_id = ' . (int) $filter['preacher'] . ' ';
  770.         }
  771.         if ($filter['date'] != '') {
  772.                 $cond .= 'AND m.datetime >= "' . $wpdb->escape($filter['date']) . '" ';
  773.         }
  774.         if ($filter['enddate'] != '') {
  775.                 $cond .= 'AND m.datetime <= "' . $wpdb->escape($filter['enddate']) . '" ';
  776.         }
  777.         if ($filter['series'] != 0) {
  778.                 $cond .= 'AND m.series_id = ' . (int) $filter['series'] . ' ';
  779.         }
  780.         if ($filter['service'] != 0) {
  781.                 $cond .= 'AND m.service_id = ' . (int) $filter['service'] . ' ';
  782.         }
  783.         if ($filter['book'] != '') {
  784.                 $cond .= 'AND bs.book_name = "' . $wpdb->escape($filter['book']) . '" ';
  785.         } else {
  786.                 $bs = "AND bs.order = 0 AND bs.type= 'start' ";
  787.         }
  788.         if ($filter['tag'] != '') {
  789.                 $cond .= "AND t.name LIKE '%" . $wpdb->escape($filter['tag']) . "%' ";
  790.         }
  791.         if ($filter['id'] != '') {
  792.                 $cond .= "AND m.id LIKE '" . $wpdb->escape($filter['id']) . "' ";
  793.         }
  794.         if ($hide_empty) {
  795.                 $cond .= "AND stuff.name != '' ";
  796.         }
  797.         $offset = $limit * ($page - 1);
  798.         if ($order['by'] == 'b.id' ) {
  799.                 $order['by'] = 'b.id '.$wpdb->escape($order['dir']).', bs.chapter '.$wpdb->escape($order['dir']).', bs.verse';
  800.         }
  801.         return "SELECT SQL_CALC_FOUND_ROWS DISTINCT m.id, m.title, m.description, m.datetime, m.time, m.start, m.end, p.id as pid, p.name as preacher, p.description as preacher_description, p.image, s.id as sid, s.name as service, ss.id as ssid, ss.name as series
  802.                 FROM {$wpdb->prefix}sb_sermons as m
  803.                 LEFT JOIN {$wpdb->prefix}sb_preachers as p ON m.preacher_id = p.id
  804.                 LEFT JOIN {$wpdb->prefix}sb_services as s ON m.service_id = s.id
  805.                 LEFT JOIN {$wpdb->prefix}sb_series as ss ON m.series_id = ss.id
  806.                 LEFT JOIN {$wpdb->prefix}sb_books_sermons as bs ON bs.sermon_id = m.id {$bs}
  807.                 LEFT JOIN {$wpdb->prefix}sb_books as b ON bs.book_name = b.name
  808.                 LEFT JOIN {$wpdb->prefix}sb_sermons_tags as st ON st.sermon_id = m.id
  809.                 LEFT JOIN {$wpdb->prefix}sb_tags as t ON t.id = st.tag_id
  810.                 LEFT JOIN {$wpdb->prefix}sb_stuff as stuff ON stuff.sermon_id = m.id
  811.                 WHERE {$cond} ORDER BY ". $order['by'] . " " . $order['dir'] . " LIMIT " . $offset . ", " . $limit;
  812. }
  813.  
  814. /**
  815. * Returns the default time for a particular service
  816. *
  817. * @param integer $service (id in database)
  818. * @return string (service time)
  819. */
  820. function sb_default_time($service) {
  821.         global $wpdb;
  822.         $sermon_time = $wpdb->get_var("SELECT time FROM {$wpdb->prefix}sb_services WHERE id='{$service}'");
  823.         if (isset($sermon_time)) {
  824.                 return $sermon_time;
  825.         } else {
  826.                 return "00:00";
  827.         }
  828. }
  829.  
  830. /**
  831. * Gets attachments from database
  832. *
  833. * @param integer $sermon (id in database)
  834. * @param boolean $mp3_only (if true will only return MP3 files)
  835. * @return array
  836. */
  837. function sb_get_stuff($sermon, $mp3_only = FALSE) {
  838.         global $wpdb;
  839.         if ($mp3_only) {
  840.                 $stuff = $wpdb->get_results("SELECT f.type, f.name FROM {$wpdb->prefix}sb_stuff as f WHERE sermon_id = $sermon->id AND name LIKE '%.mp3' ORDER BY id desc");
  841.         } else {
  842.                 $stuff = $wpdb->get_results("SELECT f.type, f.name FROM {$wpdb->prefix}sb_stuff as f WHERE sermon_id = $sermon->id ORDER BY id desc");
  843.         }
  844.         $file = $url = $code = array();
  845.         foreach ($stuff as $cur)
  846.                 ${$cur->type}[] = $cur->name;
  847.         return array(
  848.                 'Files' => $file,
  849.                 'URLs' => $url,
  850.                 'Code' => $code,
  851.         );
  852. }
  853.  
  854. /**
  855. * Increases the download count for file attachments
  856. *
  857. * Increases the download count for the file $stuff_name
  858. *
  859. * @param string $stuff_name
  860. */
  861. function sb_increase_download_count ($stuff_name) {
  862.         if (function_exists('current_user_can')&&!(current_user_can('edit_posts')|current_user_can('publish_posts'))) {
  863.                 global $wpdb;
  864.                 $wpdb->query("UPDATE ".$wpdb->prefix."sb_stuff SET COUNT=COUNT+1 WHERE name='".$wpdb->escape($stuff_name)."'");
  865.         }
  866. }
  867.  
  868. /**
  869. * Outputs a remote or local file
  870. *
  871. * @param string $filename
  872. * @return bool success or failure
  873. */
  874. function output_file($filename) {
  875.         $handle = fopen($filename, 'rb');
  876.         if ($handle === false)
  877.                 return false;
  878.         if (ob_get_level() == 0)
  879.                 ob_start();
  880.         while (!feof($handle)) {
  881.                 set_time_limit(ini_get('max_execution_time'));
  882.                 $buffer = fread($handle, 1048576);
  883.                 echo $buffer;
  884.                 ob_flush();
  885.                 flush();
  886.         }
  887.         return fclose($handle);
  888. }
  889.  
  890. /**
  891. * Sanitizes Windows paths
  892. */
  893. function sb_sanitise_path ($path) {
  894.         $path = str_replace('\\','/',$path);
  895.         $path = preg_replace('|/+|','/', $path);
  896.         return $path;
  897. }
  898. ?>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top