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