forked from markbarnes/sermon-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsermon.php
More file actions
1988 lines (1783 loc) · 50 KB
/
sermon.php
File metadata and controls
1988 lines (1783 loc) · 50 KB
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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.8.0
Author URI: https://www.markbarnes.net/
Requires at least: 6.0
Requires PHP: 8.0
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/>.
Architecture (PSR-4)
====================
sermon.php - Entry point. Bootstraps autoloader, defines constants, registers hooks.
src/ - All PHP classes organized by namespace (SermonBrowser\*)
Admin/ - Admin pages, assets, notices, dashboard widgets
Ajax/ - AJAX handlers (AjaxRegistry, LegacyAjaxHandler)
Config/ - Constants, FileTypes configuration
Facades/ - Static facades for repositories (Sermon, Preacher, Series, etc.)
Frontend/ - Frontend rendering, widgets, URL building, pagination
Install/ - Installer, Upgrader, Uninstaller, DefaultTemplates
Podcast/ - Podcast feed generation (PodcastFeed, PodcastHelper)
Repositories/ - Database access layer (AbstractRepository + entity repositories)
Templates/ - Template engine (TemplateEngine, TagParser, TagRenderer)
Utilities/ - Helper functions, Container
Widgets/ - WordPress widgets (SermonsWidget, TagCloudWidget, PopularWidget)
Entry points:
- sb_sermon_init() - Main initialization, registers actions/filters
- sb_hijack() - Early request interception (downloads, AJAX, CSS)
- sb_shortcode() - Frontend shortcode output
*/
use SermonBrowser\Facades\Sermon;
use SermonBrowser\Facades\Preacher;
use SermonBrowser\Facades\Series;
use SermonBrowser\Facades\Service;
use SermonBrowser\Facades\File;
use SermonBrowser\Facades\Tag;
use SermonBrowser\Admin\Ajax\AjaxRegistry;
use SermonBrowser\Templates\TemplateEngine;
use SermonBrowser\Utilities\HelperFunctions;
use SermonBrowser\Ajax\LegacyAjaxHandler;
use SermonBrowser\Frontend\StyleOutput;
use SermonBrowser\Podcast\PodcastFeed;
use SermonBrowser\Podcast\PodcastHelper;
use SermonBrowser\Install\Upgrader;
use SermonBrowser\Install\Installer;
use SermonBrowser\Install\DefaultTemplates;
use SermonBrowser\Http\RequestInterceptor;
// Frontend classes
use SermonBrowser\Frontend\Widgets\PopularWidget;
use SermonBrowser\Frontend\Widgets\SermonWidget;
use SermonBrowser\Frontend\Widgets\TagCloudWidget;
use SermonBrowser\Frontend\BibleText;
use SermonBrowser\Frontend\TemplateHelper;
use SermonBrowser\Frontend\UrlBuilder;
use SermonBrowser\Frontend\AssetLoader;
use SermonBrowser\Frontend\FileDisplay;
use SermonBrowser\Frontend\Pagination;
use SermonBrowser\Frontend\PageTitle;
use SermonBrowser\Frontend\FilterRenderer;
// Admin classes
use SermonBrowser\Admin\Pages\FilesPage;
use SermonBrowser\Admin\Pages\HelpPage;
use SermonBrowser\Admin\Pages\OptionsPage;
use SermonBrowser\Admin\Pages\PreachersPage;
use SermonBrowser\Admin\Pages\SeriesServicesPage;
use SermonBrowser\Admin\Pages\SermonEditorPage;
use SermonBrowser\Admin\Pages\SermonsPage;
use SermonBrowser\Admin\Pages\TemplatesPage;
use SermonBrowser\Admin\Pages\UninstallPage;
use SermonBrowser\Admin\FileSync;
use SermonBrowser\Admin\FormHelpers;
use SermonBrowser\Admin\HelpTabs;
use SermonBrowser\Admin\TagCleanup;
use SermonBrowser\Admin\UploadHelper;
use SermonBrowser\Admin\AdminAssets;
use SermonBrowser\Admin\AdminNotices;
use SermonBrowser\Admin\DashboardWidget;
use SermonBrowser\Admin\AdminBarMenu;
use SermonBrowser\Config\OptionsManager;
use SermonBrowser\Config\Defaults;
use SermonBrowser\Constants;
use SermonBrowser\Frontend\PageResolver;
/**
* Initialisation
*
* Sets version constants and basic Wordpress hooks.
* @package common_functions
*/
define('SB_CURRENT_VERSION', '0.7.0');
define('SB_DATABASE_VERSION', '1.7');
// Load Composer autoloader for modern PSR-4 classes.
// Must be loaded before sb_define_constants() which uses HelperFunctions.
require_once __DIR__ . '/vendor/autoload.php';
sb_define_constants();
add_action('plugins_loaded', 'sb_hijack');
add_action('init', 'sb_sermon_init');
add_action('widgets_init', 'sb_widget_sermon_init');
// Register modern AJAX handlers (Phase 3: Ajax Modularization).
add_action('init', function () {
if (defined('DOING_AJAX') && DOING_AJAX) {
AjaxRegistry::getInstance()->register();
}
});
// Register REST API routes for Gutenberg blocks (Phase 5).
add_action('plugins_loaded', function () {
$registry = \SermonBrowser\REST\RestApiRegistry::getInstance();
$registry->addController(new \SermonBrowser\REST\Endpoints\SermonsController());
$registry->addController(new \SermonBrowser\REST\Endpoints\TagsController());
$registry->addController(new \SermonBrowser\REST\Endpoints\PreachersController());
$registry->addController(new \SermonBrowser\REST\Endpoints\SeriesController());
$registry->addController(new \SermonBrowser\REST\Endpoints\ServicesController());
$registry->addController(new \SermonBrowser\REST\Endpoints\FilesController());
$registry->addController(new \SermonBrowser\REST\Endpoints\SearchController());
$registry->init();
}, 15);
// Register Gutenberg blocks (Phase 5).
add_action('plugins_loaded', function () {
$registry = \SermonBrowser\Blocks\BlockRegistry::getInstance();
$registry->addBlock('tag-cloud');
$registry->addBlock('single-sermon');
$registry->addBlock('sermon-list');
$registry->addBlock('preacher-list');
$registry->addBlock('series-grid');
$registry->addBlock('sermon-player');
$registry->addBlock('recent-sermons');
$registry->addBlock('popular-sermons');
$registry->addBlock('sermon-grid');
$registry->addBlock('profile-block');
$registry->addBlock('sermon-media');
$registry->addBlock('sermon-filters');
$registry->init();
}, 20);
// Register block patterns (Phase 4).
require_once __DIR__ . '/src/Blocks/patterns/index.php';
// Register FSE (Full Site Editing) support (Phase 6).
add_action('plugins_loaded', function () {
\SermonBrowser\Blocks\FSESupport::getInstance()->init();
}, 25);
// Phase 6: Template migration on plugin activation.
register_activation_hook(__FILE__, function () {
$migrator = new \SermonBrowser\Templates\TemplateMigrator();
$result = $migrator->migrate();
set_transient('sb_migration_result', $result, HOUR_IN_SECONDS);
});
// Phase 6: Display template migration result as admin notice.
add_action('admin_notices', function () {
$result = get_transient('sb_migration_result');
if (!$result) {
return;
}
if ($result->isSuccess()) {
echo '<div class="notice notice-success is-dismissible">';
echo '<p>' . esc_html($result->getMessage()) . '</p>';
echo '</div>';
} elseif ($result->hasWarnings()) {
echo '<div class="notice notice-warning is-dismissible">';
echo '<p>' . esc_html($result->getMessage()) . '</p>';
echo '</div>';
}
delete_transient('sb_migration_result');
});
/**
* 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()
{
RequestInterceptor::intercept();
}
/**
* 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 $defaultMultiForm, $defaultSingleForm, $defaultStyle;
// Load translations
$textdomain_path = IS_MU ? 'languages' : 'sermon-browser/languages';
load_plugin_textdomain('sermon-browser', '', $textdomain_path);
// Set locale if available
$locale_string = sb_get_locale_string();
if (!empty($locale_string)) {
setlocale(LC_ALL, $locale_string);
}
// Display the podcast if requested
if (isset($_GET['podcast'])) {
PodcastFeed::render();
}
// Register stylesheet
sb_register_styles();
// Register [sermon] shortcode handler
add_shortcode('sermons', 'sb_shortcode');
add_shortcode('sermon', 'sb_shortcode');
// Configure PHP limits
sb_configure_php_ini();
// Check for upgrades (admin only)
sb_check_admin_upgrades();
// Load shared (admin/frontend) features
add_action('save_post', 'sb_update_podcast_url');
// Register context-specific hooks
if (!is_admin()) {
sb_register_frontend_hooks();
} else {
sb_register_admin_hooks();
}
}
/**
* Register the SermonBrowser stylesheet.
*/
function sb_register_styles()
{
$style_version = sb_get_option('style_date_modified');
$base_url = trailingslashit(home_url());
$style_url = (get_option('permalink_structure') == '')
? $base_url . '?sb-style&'
: $base_url . 'sb-style.css';
wp_register_style('sb_style', $style_url, false, $style_version);
}
/**
* Configure PHP ini directives for file uploads.
*/
function sb_configure_php_ini()
{
if (strpos(ini_get('disable_functions'), 'ini_set') !== false) {
return;
}
$settings = [
'upload_max_filesize' => ['threshold' => 15360, 'value' => '15M', 'type' => 'kbytes'],
'post_max_size' => ['threshold' => 15360, 'value' => '15M', 'type' => 'kbytes'],
'memory_limit' => ['threshold' => 49152, 'value' => '48M', 'type' => 'kbytes'],
'max_input_time' => ['threshold' => 600, 'value' => '600', 'type' => 'int'],
'max_execution_time' => ['threshold' => 600, 'value' => '600', 'type' => 'int'],
'file_uploads' => ['threshold' => '1', 'value' => '1', 'type' => 'string'],
];
foreach ($settings as $key => $config) {
$current = ini_get($key);
$below_threshold = match ($config['type']) {
'kbytes' => sb_return_kbytes($current) < $config['threshold'],
'int' => intval($current) < $config['threshold'],
'string' => $current != $config['threshold'],
};
if ($below_threshold) {
ini_set($key, $config['value']);
}
}
}
/**
* Check and run admin upgrades if needed.
*/
function sb_check_admin_upgrades()
{
if (!current_user_can('manage_options') || !is_admin()) {
return;
}
// Check database version
$db_version = get_option('sb_sermon_db_version') ?: sb_get_option('db_version');
if ($db_version && $db_version != SB_DATABASE_VERSION) {
Upgrader::databaseUpgrade($db_version);
} elseif (!$db_version) {
Installer::run();
}
// Check code version
$sb_version = sb_get_option('code_version');
if ($sb_version != SB_CURRENT_VERSION) {
Upgrader::versionUpgrade($sb_version, SB_CURRENT_VERSION);
}
// Check template version (Phase 6 migration)
$template_version = sb_get_option('template_version') ?: '0';
if (version_compare($template_version, '0.6.0', '<')) {
$migrator = new \SermonBrowser\Templates\TemplateMigrator();
$result = $migrator->migrate();
set_transient('sb_migration_result', $result, HOUR_IN_SECONDS);
sb_update_option('template_version', '0.6.0');
}
}
/**
* Register frontend-specific WordPress hooks.
*/
function sb_register_frontend_hooks()
{
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');
}
}
/**
* Register admin-specific WordPress hooks.
*/
function sb_register_admin_hooks()
{
add_action('admin_menu', 'sb_add_pages');
add_filter('dashboard_glance_items', 'sb_dashboard_glance');
add_action('admin_enqueue_scripts', 'sb_add_admin_headers');
add_action('current_screen', 'sb_add_help_tabs');
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 . '/assets/images/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'] == Constants::NEW_SERMON_PAGE && isset($_REQUEST['mid'])) {
add_submenu_page(__FILE__, __('Edit Sermon', 'sermon-browser'), __('Edit Sermon', 'sermon-browser'), 'publish_posts', Constants::NEW_SERMON_PAGE, 'sb_new_sermon');
} else {
add_submenu_page(__FILE__, __('Add Sermon', 'sermon-browser'), __('Add Sermon', 'sermon-browser'), 'publish_posts', Constants::NEW_SERMON_PAGE, '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 Value like '15M' or '1G'.
* @return int Value in kilobytes.
*/
function sb_return_kbytes($val)
{
return HelperFunctions::returnKbytes((string) $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)
{
$stats = File::getTotalDownloadsBySermon((int) $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() == "") {
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');
}
}
}
/**
* Get default values for SermonBrowser.
*
* @param string $default_type The type of default.
* @return mixed The default value.
*/
function sb_get_default($default_type)
{
return Defaults::get($default_type);
}
/**
* Returns true if sermons are displayed on the current page.
*
* @return bool
*/
function sb_display_front_end()
{
return PageResolver::displaysFrontEnd();
}
/**
* Get the page_id of the main sermons page.
*
* @return int
*/
function sb_get_page_id()
{
return PageResolver::getPageId();
}
/**
* Get the URL of the main sermons page.
*
* @return string
*/
function sb_display_url()
{
return PageResolver::getDisplayUrl();
}
/**
* 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 bool $return_entity Whether to return HTML entity.
* @return string Either '?', '&', or '&'.
*/
function sb_query_char($return_entity = true)
{
return PageResolver::getQueryChar($return_entity);
}
/**
* Create the shortcode handler
*
* Standard shortcode handler that inserts the sermonbrowser output into the post/page
*
* @param array $atts
* @return string
*/
function sb_shortcode($atts)
{
ob_start();
$atts = shortcode_atts(sb_get_shortcode_defaults(), $atts);
if ($atts['id'] != '') {
sb_render_single_sermon($atts);
} else {
sb_render_sermon_list($atts);
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
/**
* Get default shortcode attributes with request parameter fallbacks.
*
* @return array Default attribute values.
*/
function sb_get_shortcode_defaults()
{
return [
'filter' => sb_get_option('filter_type'),
'filterhide' => sb_get_option('filter_hide'),
'id' => sb_get_request_int('sermon_id'),
'preacher' => sb_get_request_int('preacher'),
'series' => sb_get_request_int('series'),
'book' => sb_get_request_text('book'),
'service' => sb_get_request_int('service'),
'date' => sb_get_request_text('date'),
'enddate' => sb_get_request_text('enddate'),
'tag' => sb_get_request_text('stag'),
'title' => sb_get_request_text('title'),
'limit' => '0',
'dir' => sb_get_request_text('dir'),
];
}
/**
* Get an integer value from $_REQUEST or return empty string.
*
* @param string $key Request parameter name.
* @return int|string Integer value or empty string.
*/
function sb_get_request_int($key)
{
return isset($_REQUEST[$key]) ? (int) $_REQUEST[$key] : '';
}
/**
* Get a sanitized text value from $_REQUEST or return empty string.
*
* @param string $key Request parameter name.
* @return string Sanitized value or empty string.
*/
function sb_get_request_text($key)
{
return isset($_REQUEST[$key]) ? sanitize_text_field($_REQUEST[$key]) : '';
}
/**
* Render a single sermon view.
*
* @param array $atts Shortcode attributes.
*/
function sb_render_single_sermon($atts)
{
// Handle 'latest' shorthand
$sermon_id = $atts['id'];
if (strtolower($sermon_id) == 'latest') {
$atts['id'] = '';
$query = sb_get_sermons($atts, [], 1, 1);
$sermon_id = $query[0]->id;
}
$sermon = sb_get_single_sermon((int) $sermon_id);
if (!$sermon) {
echo '<div class="sermon-browser-results"><span class="error">';
_e('No sermons found.', 'sermon-browser');
echo '</span></div>';
return;
}
sb_render_template('single', [
'Sermon' => $sermon['Sermon'],
'Files' => $sermon['Files'] ?? [],
'Code' => $sermon['Code'] ?? [],
'Tags' => $sermon['Tags'] ?? [],
]);
}
/**
* Render a sermon list view.
*
* @param array $atts Shortcode attributes.
*/
function sb_render_sermon_list($atts)
{
global $record_count;
$sort_order = sb_resolve_sort_order($atts);
$page = isset($_REQUEST['pagenum']) ? (int) $_REQUEST['pagenum'] : 1;
$hide_empty = sb_get_option('hide_no_attachments');
$sermons = sb_get_sermons($atts, $sort_order, $page, (int) $atts['limit'], $hide_empty);
sb_render_template('search', [
'sermons' => $sermons,
'record_count' => $record_count,
'atts' => $atts,
]);
}
/**
* Resolve sort order from request and attributes.
*
* Validates sort column against whitelist to prevent SQL injection.
* Column names cannot be parameterized in ORDER BY clauses, so
* whitelist validation is required (esc_sql is insufficient).
*
* @param array $atts Shortcode attributes.
* @return array Sort order with 'by' and 'dir' keys.
*/
function sb_resolve_sort_order($atts)
{
// Whitelist of valid sort columns (must match SermonRepository::findForFrontendListing)
$valid_sort_columns = [
'm.id', 'm.title', 'm.datetime', 'm.start', 'm.end',
'p.id', 'p.name', 's.id', 's.name', 'ss.id', 'ss.name',
];
// Validate sortby against whitelist
$sort_criteria = 'm.datetime';
if (isset($_REQUEST['sortby'])) {
$requested_sort = sanitize_text_field(wp_unslash($_REQUEST['sortby']));
if (in_array($requested_sort, $valid_sort_columns, true)) {
$sort_criteria = $requested_sort;
}
}
// Validate direction - only allow 'asc' or 'desc'
$dir = ($sort_criteria === 'm.datetime') ? 'desc' : 'asc';
if (!empty($atts['dir'])) {
$requested_dir = strtolower(sanitize_text_field($atts['dir']));
if ($requested_dir === 'asc' || $requested_dir === 'desc') {
$dir = $requested_dir;
}
}
return ['by' => $sort_criteria, 'dir' => $dir];
}
/**
* Render a template with error handling.
*
* @param string $template Template name ('single' or 'search').
* @param array $data Template data.
*/
function sb_render_template($template, $data)
{
try {
$engine = new TemplateEngine();
echo $engine->render($template, $data);
} catch (\Exception $e) {
echo '<div class="sermon-browser-error">' .
esc_html__('Template error', 'sermon-browser') . '</div>';
if (defined('WP_DEBUG') && WP_DEBUG) {
echo '<!-- Template error: ' . esc_html($e->getMessage()) . ' -->';
}
}
}
/**
* Registers the Sermon Browser widgets using modern WP_Widget API
*
* @since 0.46.0 - Converted from deprecated wp_register_sidebar_widget()
*/
function sb_widget_sermon_init()
{
// Register modern WP_Widget classes (PSR-4 namespaced)
register_widget(\SermonBrowser\Widgets\SermonsWidget::class);
register_widget(\SermonBrowser\Widgets\TagCloudWidget::class);
register_widget(\SermonBrowser\Widgets\PopularWidget::class);
}
/**
* Migrate widget settings from old format to new WP_Widget format
*
* This function preserves existing widget configurations when upgrading
* from the deprecated widget API to WP_Widget classes.
*
* @since 0.46.0
*/
function sb_migrate_widget_settings()
{
if (get_option('sb_widget_migration_v046')) {
return;
}
sb_migrate_sermon_widget();
sb_migrate_popular_widget();
update_option('sb_widget_migration_v046', true);
}
add_action('admin_init', 'sb_migrate_widget_settings');
/**
* Migrate sermon widget settings from old format.
*/
function sb_migrate_sermon_widget()
{
$old_opts = get_option('sb_widget_sermon');
if (!$old_opts || get_option('widget_sb_sermons')) {
return;
}
$new_opts = ['_multiwidget' => 1];
$instance_num = 2; // WordPress reserves 1
foreach ((array) $old_opts as $opts) {
if (!isset($opts['limit'])) {
continue;
}
$new_opts[$instance_num++] = sb_map_sermon_widget_instance($opts);
}
if (count($new_opts) > 1) {
update_option('widget_sb_sermons', $new_opts);
}
}
/**
* Map old sermon widget options to new format.
*
* @param array $opts Old widget options.
* @return array New widget instance options.
*/
function sb_map_sermon_widget_instance($opts)
{
return [
'title' => $opts['title'] ?? '',
'limit' => (int) ($opts['limit'] ?? 5),
'preacher' => (int) ($opts['preacher'] ?? 0),
'service' => (int) ($opts['service'] ?? 0),
'series' => (int) ($opts['series'] ?? 0),
'show_preacher' => !empty($opts['preacherz']),
'show_book' => !empty($opts['book']),
'show_date' => !empty($opts['date']),
];
}
/**
* Migrate popular widget settings from old format.
*/
function sb_migrate_popular_widget()
{
$old_opts = sb_get_option('popular_widget_options');
if (!$old_opts || get_option('widget_sb_popular')) {
return;
}
$new_opts = [
2 => [
'title' => $old_opts['title'] ?? '',
'limit' => (int) ($old_opts['limit'] ?? 5),
'display_sermons' => !empty($old_opts['display_sermons']),
'display_series' => !empty($old_opts['display_series']),
'display_preachers' => !empty($old_opts['display_preachers']),
],
'_multiwidget' => 1,
];
update_option('widget_sb_popular', $new_opts);
}
/**
* 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)
{
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)
{
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)
{
sb_widget_popular($args);
}
/**
* Get a SermonBrowser option value.
*
* Public API - kept for backwards compatibility.
*
* @param string $type Option key.
* @return mixed Option value.
*/
function sb_get_option($type)
{
return OptionsManager::get($type);
}
/**
* Update a SermonBrowser option value.
*
* Public API - kept for backwards compatibility.
*
* @param string $type Option key.
* @param mixed $val Option value.
* @return bool True if updated.
*/
function sb_update_option($type, $val)
{
return OptionsManager::update($type, $val);
}
/**
* Recursive mkdir function with chmod.
*
* @param string $pathname Directory path.
* @param int $mode Permission mode.
* @return bool True on success.
*/
function sb_mkdir($pathname, $mode = 0755)
{
return HelperFunctions::mkdir($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_ABSPATH', sb_sanitise_path(ABSPATH));
}
/**
* Returns list of bible books from the database
*
* @return array
*/
function sb_get_bible_books()
{
return \SermonBrowser\Facades\Book::findAllNames();
}
/**
* Get multiple sermons from the database
*
* Uses Sermon Facade for database operations.
* @param array $filter
* @param array $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 $record_count;
if ($limit == 0) {
$limit = sb_get_option('sermons_per_page');
}
$result = \SermonBrowser\Facades\Sermon::findForFrontendListing(
(array) $filter,
(array) $order,
(int) $page,
(int) $limit,
(bool) $hide_empty
);
$record_count = $result['total'];
return $result['items'];
}
/**
* Returns the default time for a particular service
*
* @param integer $service (id in database)
* @return string (service time)
*/
function sb_default_time($service)
{
$serviceRecord = Service::find((int) $service);
if ($serviceRecord && isset($serviceRecord->time)) {
return $serviceRecord->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)
{
$stuff = File::findBySermon((int) $sermon->id);
if ($mp3_only) {
$stuff = array_filter($stuff, fn($f) => str_ends_with($f->name ?? '', '.mp3'));
}
$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'))) {
File::incrementCountByName($stuff_name);
}
}
/**
* Output a file in chunks (for large file downloads).
*
* @param string $filename Path to the file.
* @return bool True on success.
*/
function sb_output_file($filename)
{
return HelperFunctions::outputFile($filename);
}
/**
* Sanitize Windows paths to use forward slashes.
*
* @param string $path The path.
* @return string Sanitized path.
*/
function sb_sanitise_path($path)
{
return HelperFunctions::sanitisePath($path);
}
/***************************************
** Functions from functions-testable.php **
**************************************/