-
Notifications
You must be signed in to change notification settings - Fork 0
/
library-instruction-recorder.php
1831 lines (1533 loc) · 82.6 KB
/
library-instruction-recorder.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
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: Library Instruction Recorder
Plugin URI: http://bitbucket.org/gsulibwebmaster/library-instruction-recorder
Description: A plugin for recording library instruction events and their associated data.
Version: 1.1.4
Author: Georgia State University Library
Author URI: http://library.gsu.edu/
License: GPLv3
Library Instruction Recorder - A WordPress Plugin
Copyright (C) 2013 Georgia State University Library
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/>.
*/
if(!class_exists('LIR')) {
/*
Class: LIR
The LIR class which enables the Library Instruction Recorder functionality in WordPress.
*/
class LIR {
// Do not change these variables. The plugin name and slug can be changed on the settings page.
const NAME = 'Library Instruction Recorder';
const SLUG = 'LIR';
const OPTIONS = 'lir_options';
const OPTIONS_GROUP = 'lir_options_group';
const AUTOLOAD = 'no';
const VERSION = '1.1.4';
const MIN_VERSION = '3.6';
const TABLE_POSTS = '_posts';
const TABLE_META = '_meta';
const TABLE_FLAGS = '_flags';
const SCHEDULE_TIME = '06:00:00';
const CHARSET = 'utf8';
private static $defaultOptions = array(
'version' => self::VERSION,
'name' => self::NAME,
'slug' => self::SLUG,
'intervalLength' => 15,
'intervalAmount' => 16,
'emailEnabled' => true,
'debug' => false
);
private $options;
private $tables;
/*
Constructor: __construct
Adds register hooks, actions, and filters to WP.
*/
public function __construct() {
// Registration hooks.
register_activation_hook(__FILE__, array('LIR', 'activationHook'));
register_deactivation_hook(__FILE__, array('LIR', 'deactivationHook'));
register_uninstall_hook(__FILE__, array('LIR', 'uninstallHook'));
// Actions and filters.
add_action('admin_menu', array(&$this, 'createMenu'));
add_action('admin_init', array(&$this, 'adminInit'));
add_action('admin_enqueue_scripts', array(&$this, 'addCssJS'));
// A hook needs to be created to add this to the scheduler (weird, I know).
add_action(self::SLUG.'_schedule', array(&$this, 'emailReminders'));
}
/*
Function: init
Initializes WordPress options, LIR table names, and the LIR scheduler. Why is this not
in the construtor you ask? So that this stuff is not processed unless it is needed.
Inputs:
wpdb - Takes the global variable $wpdb by reference if it was already initialized.
*/
private function init(&$wpdb = NULL) {
// If these values are set then return.
if(isset($this->options) && isset($this->tables)) { return; }
// If not passed call global.
if(!isset($wpdb)) { global $wpdb; }
// Load options, self::$defaultOptions if they do not exist.
$this->options = get_option(self::OPTIONS, self::$defaultOptions);
// Prep table names.
$this->tables = array(
'posts' => $wpdb->prefix.self::SLUG.self::TABLE_POSTS,
'meta' => $wpdb->prefix.self::SLUG.self::TABLE_META,
'flags' => $wpdb->prefix.self::SLUG.self::TABLE_FLAGS
);
}
/*
Function: activationHook
Checks to make sure WordPress is compatible, sets up tables, and sets up options.
***STATIC FUNCTION***
See Also:
<deactivationHook> and <uninstallHook>
*/
public static function activationHook() {
if(!current_user_can('manage_options')) {
wp_die('You do not have sufficient permissions to access this page.');
}
// Make sure compatible WordPress version.
global $wp_version;
if(version_compare($wp_version, self::MIN_VERSION, '<')) {
wp_die('This plugin requires WordPress version '.self::MIN_VERSION.' or higher.');
}
// If the option already exists it will not be overwritten.
// Do not autoload the options, they are only used on admin pages.
add_option(self::OPTIONS, self::$defaultOptions, '', self::AUTOLOAD);
// Add LIR tables to the database if they do not exist.
global $wpdb;
require_once(ABSPATH.'wp-admin/includes/upgrade.php'); // Required for dbDelta.
// Post table.
/*************************************
Eventually change the charset so that it uses what is defined in the WP config file (if there).
$wpdb->charset;
*************************************/
$query = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.self::SLUG.self::TABLE_POSTS." (
id mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT,
librarian_name varchar(255) NOT NULL,
librarian2_name varchar(255) DEFAULT NULL,
instructor_name varchar(255) NOT NULL,
instructor_email varchar(255) DEFAULT NULL,
instructor_phone varchar(255) DEFAULT NULL,
class_start datetime NOT NULL,
class_end datetime NOT NULL,
class_location varchar(255) NOT NULL,
class_type varchar(255) NOT NULL,
audience varchar(255) NOT NULL,
class_description mediumtext,
department_group varchar(255) NOT NULL,
course_number varchar(255) DEFAULT NULL,
attendance smallint(6) UNSIGNED DEFAULT NULL,
owner_id bigint(20) NOT NULL,
last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
last_updated_by bigint(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
dbDelta($query);
// Meta table.
$query = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.self::SLUG.self::TABLE_META." (
field varchar(255) NOT NULL,
value mediumtext NOT NULL,
PRIMARY KEY (field)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
dbDelta($query);
// Flag table.
$query = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.self::SLUG.self::TABLE_FLAGS." (
posts_id mediumint(8) UNSIGNED NOT NULL,
name varchar(255) NOT NULL,
value smallint(1) NOT NULL,
PRIMARY KEY (posts_id, name),
FOREIGN KEY (posts_id)
REFERENCES ".$wpdb->prefix.self::SLUG.self::TABLE_POSTS." (id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
dbDelta($query);
}
/*
Function: deactivationHook
Removes LIR scheduler hook.
***STATIC FUNCTION***
See Also:
<activationHook> and <uninstallHook>
*/
public static function deactivationHook() {
if(!current_user_can('manage_options')) {
wp_die('You do not have sufficient permissions to access this page.');
}
// Remove scheduled hook.
wp_clear_scheduled_hook(self::SLUG.'_schedule');
/* DO NOT UNCOMMENT THIS, IT WILL DELETE ALL OF YOUR DATA
// Remove options saved in wp_options table.
delete_option(self::OPTIONS);
// Remove custom database tables (post & meta).
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS ".$wpdb->prefix.self::SLUG.self::TABLE_FLAGS.", ".$wpdb->prefix.self::SLUG.self::TABLE_META.", ".$wpdb->prefix.self::SLUG.self::TABLE_POSTS);
//*/
}
/*
Function: uninstallHook
Used to cleanup items after uninstalling the plugin (databases, wp_options, &c).
UNINSTALLING PERMANENTLY REMOVES ALL DATA ASSOCIATED WITH THIS PLUGIN.
***STATIC FUNCTION***
See Also:
<activationHook> and <deactivationHook>
*/
public static function uninstallHook() {
if(!current_user_can('manage_options')) {
wp_die('You do not have sufficient permissions to access this page.');
}
// We'll make sure the scheduled hook has been removed.
wp_clear_scheduled_hook(self::SLUG.'_schedule');
// Remove WP options.
delete_option(self::OPTIONS);
// Remove custom database tables.
global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS ".$wpdb->prefix.self::SLUG.self::TABLE_FLAGS.", ".$wpdb->prefix.self::SLUG.self::TABLE_META.", ".$wpdb->prefix.self::SLUG.self::TABLE_POSTS);
}
/*
Function: adminInit
Performs plugin updates, registers an option group so that the settings page
functions and can be sanitized, makes sure the scheduler is set, and catches
the post action for downloading reports.
See Also:
<settingsPage>, <sanitizeSettings>, and <generateReport>
*/
public function adminInit() {
global $wpdb;
$this->init($wpdb);
// PLUGIN UPDATES ARE PERFORMED HERE.
// Run the update that fixes the last_updated field in the posts table and does some stuff with options.
if(version_compare('1.1.4', $this->options['version'], '>')) {
// Add email reminders option.
$this->options['emailEnabled'] = true;
// Make debug option bool.
$this->options['debug'] = ($this->options['debug'] == 'on') ? true : false;
update_option(self::OPTIONS, $this->options, self::AUTOLOAD);
// Fix table.
$query = 'ALTER TABLE '.$this->tables['posts'].'
MODIFY COLUMN last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP';
// dbDelta should be used for ALTER statements.
require_once(ABSPATH.'wp-admin/includes/upgrade.php');
dbDelta($query);
}
// If plugin options don't reflect the plugin version, make it so.
if(version_compare(self::VERSION, $this->options['version'], '!=')) {
$this->options['version'] = self::VERSION;
update_option(self::OPTIONS, $this->options, self::AUTOLOAD);
}
// If no settings are present this will end up registering them with autoload set to yes!
register_setting(self::OPTIONS_GROUP, self::OPTIONS, array(&$this, 'sanitizeSettings'));
// Setup/make sure scheduler is setup.
if(!wp_next_scheduled(self::SLUG.'_schedule')) {
wp_schedule_event(strtotime(self::SCHEDULE_TIME.' +1 day', current_time('timestamp')), 'daily', self::SLUG.'_schedule');
}
// Generates and sends CSV file (before standard headers are sent).
// It is worth noting that the admin_post_{action_name} hook only works (haven't tested it yet)
// if being submitted to the /wp-admin/admin-post.php page. That doesn't work well for this
// implementation since the report can be generated as a file or on the reports page.
if(isset($_POST['action']) && ($_POST['action'] == self::SLUG.'_download_report')) {
if(isset($_POST['option']) && ($_POST['option'] == 'file')) {
$this->generateReport(true);
}
}
}
/*
Function: addCssJS
Adds custom CSS and JavaScript links to LIR pages (only).
*/
public function addCssJS() {
global $parent_file;
// If admin page doesn't belong to LIR, do not add CSS and JS.
if($parent_file != self::SLUG) { return; }
// Register DataTables so that it can be a requirement for the admin.js script.
wp_register_script(self::SLUG.'-dataTables', plugins_url('js/jquery.dataTables.min.js', __FILE__), array('jquery'), '1.10.1');
wp_enqueue_script(self::SLUG.'-admin-JS', plugins_url('js/admin.js', __FILE__), array('jquery', self::SLUG.'-dataTables', 'jquery-ui-datepicker', 'jquery-ui-dialog'), self::VERSION);
wp_enqueue_style(self::SLUG.'-admin-Css', plugins_url('css/admin.css', __FILE__), array(), self::VERSION);
wp_enqueue_style(self::SLUG.'-jquery-ui-redmond', plugins_url('css/jquery-ui/redmond/jquery-ui.min.css', __FILE__), array(), '1.10.3');
wp_enqueue_style(self::SLUG.'-dataTables-Css', plugins_url('css/dataTables/css/jquery.dataTables.min.css', __FILE__), array(), '1.10.1');
}
/*
Function: createMenu
Creates a menu and submenu on the dashboard for plugin usage and administration.
See Also:
<defaultPage>, <addClassPage>, <reportsPage>, <fieldsPage>, and <settingsPage>
*/
public function createMenu() {
$this->init();
// Changes language of "add a class" on the submenu when editing a class.
$addClassName = isset($_GET['edit']) ? 'Add/Edit a Class' : 'Add a Class';
// Adds the main menu item.
add_menu_page('', $this->options['slug'], 'read', self::SLUG, array(&$this, 'defaultPage'), '', '58.992');
// Added so the first submenu item does not have the same title as the main menu item.
add_submenu_page(self::SLUG, 'Upcoming Classes', 'Upcoming Classes', 'read', self::SLUG, array(&$this, 'defaultPage'));
add_submenu_page(self::SLUG, $addClassName, $addClassName, 'edit_posts', self::SLUG.'-add-a-class', array(&$this, 'addClassPage'));
add_submenu_page(self::SLUG, 'Reports', 'Reports', 'edit_posts', self::SLUG.'-reports', array(&$this, 'reportsPage'));
add_submenu_page(self::SLUG, 'Fields', 'Fields', 'manage_options', self::SLUG.'-fields', array(&$this, 'fieldsPage'));
add_submenu_page(self::SLUG, 'Settings', 'Settings', 'manage_options', self::SLUG.'-settings', array(&$this, 'settingsPage'));
// This doesn't currently work as intended due to the way class updates are processed.
$this->updateNotificationCount();
}
/*
Function: defaultPage
The default page is displayed when clicking on the LIR menu item. This page shows
a list of upcoming classes while allowing users to see the details, edit entries,
copy entries, and delete entries.
Outputs:
HTML for the default (upcoming classes) page.
See Also:
<addClassPage>
*/
public function defaultPage() {
if(!current_user_can('read')) {
wp_die('You do not have sufficient permissions to access this page.');
}
// If user is a subscriber.
$subscriber = current_user_can('edit_posts') ? false : true;
global $wpdb, $current_user;
$this->init($wpdb);
get_currentuserinfo();
$baseUrl = admin_url('admin.php?page='.self::SLUG);
$delete = (!empty($_GET['delete'])) ? $_GET['delete'] : NULL;
$classRemoved = NULL;
$timeStamp = current_time('timestamp');
// Handle deletion if present.
if($delete) {
$query = $wpdb->prepare("SELECT * FROM ".$this->tables['posts']." WHERE id = %d", $delete);
$class = $wpdb->get_row($query);
// Check if the user has permissions to remove the class and verify the nonce.
if((current_user_can('manage_options') || $current_user->ID == $class->owner_id) && wp_verify_nonce($_GET['n'], self::SLUG.'-delete-'.$delete)) {
$classRemoved = $wpdb->delete($this->tables['posts'], array('id' => $delete), '%d');
}
}
// Queries to display the listings and also to give the appropriate counts for upcoming, incomplete, and previous classes.
$upcoming = $wpdb->get_results("SELECT * FROM ".$this->tables['posts']." WHERE NOW() <= class_end ORDER BY class_start, class_end");
$upcomingCount = $wpdb->num_rows;
$incomplete = $wpdb->get_results("SELECT * FROM ".$this->tables['posts']." WHERE NOW() > class_end AND attendance IS NULL ORDER BY class_start, class_end");
$incompleteCount = $wpdb->num_rows;
$previous = $wpdb->get_results("SELECT * FROM ".$this->tables['posts']." WHERE NOW() > class_end ORDER BY class_start DESC, class_end");
$previousCount = $wpdb->num_rows;
$myclasses = $wpdb->get_results("SELECT * FROM ".$this->tables['posts']." WHERE owner_id = ".$current_user->ID." ORDER BY class_start DESC, clasS_end");
$myclassesCount = $wpdb->num_rows;
// Pick list to display and setup for link persistence.
if(isset($_GET['incomplete'])) {
$result = $incomplete;
}
else if(isset($_GET['previous'])) {
$result = $previous;
}
else if(isset($_GET['myclasses'])) {
$result = $myclasses;
}
else {
$result = $upcoming;
}
?>
<div class="wrap">
<h2>
<?php
echo esc_html($this->options['name']);
if(!$subscriber) { echo ' <a href="'.$baseUrl.'-add-a-class" class="add-new-h2">Add a Class</a>'; }
?>
</h2>
<?php
// For debugging.
if($this->options['debug']) {
echo '<div id="message" class="error">';
echo '<p><strong>Time</strong><br />';
echo $timeStamp.' - '.date('c', $timeStamp).'</p>';
echo '<p><strong>First Schedule?</strong><br />';
echo strtotime(self::SCHEDULE_TIME.' +1 day', $timeStamp).' - '.date('c', strtotime(self::SCHEDULE_TIME.' +1 day', $timeStamp)).'</p>';
echo '<p><strong>Next Schedule</strong><br />';
echo wp_next_scheduled(self::SLUG.'_schedule').' - '.date('c', wp_next_scheduled(self::SLUG.'_schedule')).'</p>';
//global $menu;
//echo '<pre>'.print_r($menu, true).'</pre>';
echo '</div>';
} // End debugging.
// Success or error message for removing a class.
if($delete && $classRemoved) {
echo '<div id="message" class="updated">
<p><strong>The class has been removed!</strong></p>
</div>';
}
else if($delete && !$classRemoved) {
echo '<div id="message" class="error">
<p><strong>There was a problem removing the class.</strong></p>
</div>';
}
?>
<ul class="subsubsub">
<?php
// Upcoming classes.
echo '<li><a href="'.$baseUrl.'"';
if(!isset($_GET['incomplete']) && !isset($_GET['previous']) && !isset($_GET['myclasses'])) { echo ' class="current"'; }
echo '>Upcoming <span class="count">('.$upcomingCount.')</span></a> |</li>';
// Incomplete classes.
echo '<li><a href="'.$baseUrl.'&incomplete=1"';
if(isset($_GET['incomplete']) && ($_GET['incomplete'] == '1')) { echo ' class="current"'; }
echo '>Incomplete <span class="count">('.$incompleteCount.')</span></a> |</li>';
// Previous classes.
echo '<li><a href="'.$baseUrl.'&previous=1"';
if(isset($_GET['previous']) && ($_GET['previous'] == '1')) { echo ' class="current"'; }
echo '>Previous <span class="count">('.$previousCount.')</span></a></li>';
// My classes (if not a subscriber).
if(!$subscriber) {
echo '<li>| <a href="'.$baseUrl.'&myclasses=1"';
if(isset($_GET['myclasses']) && ($_GET['myclasses'] == '1')) { echo ' class="current"'; }
echo '>My Classes <span class="count">('.$myclassesCount.')</span></a></li>';
}
?>
</ul>
<table id="classListingTable" class="widefat">
<?php
// Table header and footer.
$tableHF = '<tr><th class="check-column"> </th><th>Department/Group</th><th>Course #</th><th>Date/Time</th>';
$tableHF .= '<th>Primary Librarian</th><th>Instructor</th><th>Options</th><th class="hide">Hidden Goodies</th></tr>';
echo '<thead>'.$tableHF.'</thead>';
echo '<tfoot>'.$tableHF.'</tfoot>';
// Table body.
echo '<tbody>';
// For each class.
foreach($result as $class) {
echo '<tr class="'.self::SLUG.'-'.$class->id.'"';
if($class->class_description) {
echo ' title="'.esc_attr($class->class_description).'"';
}
echo '>'; // Closing the <tr...
echo '<th> </th>'; // Check-column.
echo '<td name="Department-Group">'.esc_html($class->department_group).'</td>';
if($class->course_number) {
echo '<td name="Course_Number">'.esc_html($class->course_number).'</td>';
}
else {
echo '<td> </td>';
}
// Display start date & time - end date & time.
if(substr($class->class_start, 0, 10) == substr($class->class_end, 0, 10)) {
echo '<td name="Date-Time"><span class="hide">'.$class->class_start.' - '.$class->class_end.'</span>'.date('n/j/Y (D) g:i A - ', strtotime($class->class_start, $timeStamp));
echo date('g:i A', strtotime($class->class_end, $timeStamp)).'</td>';
}
else { // If the end time is not on the same day as the start time.
echo '<td name="Date-Time">'.date('n/j/Y (D) g:i A -', strtotime($class->class_start, $timeStamp)).'<br />';
echo date('n/j/Y (D) g:i A', strtotime($class->class_end, $timeStamp)).'</td>';
}
echo '<td name="Primary_Librarian">'.esc_html($class->librarian_name).'</td>';
// Instructor name and email.
if($class->instructor_email) {
$mailto = esc_attr('mailto:'.$class->instructor_name.' <'.$class->instructor_email.'>');
echo '<td name="Instructor"><a href="'.esc_attr($mailto).'" title="'.esc_attr($class->instructor_email).'">'.esc_html($class->instructor_name).'</a></td>';
}
else {
echo '<td name="Instructor">'.esc_html($class->instructor_name).'</td>';
}
// Start Options section.
echo '<td><a class="stopLinkFire" href="#" onclick="showDetails(\''.self::SLUG.'-'.$class->id.'\')">Other Details</a>';
// Copy a class.
if(current_user_can('edit_posts')) {
echo ' | <a href="'.$baseUrl.'-add-a-class©='.$class->id.'">Copy</a>';
}
// Edit and delete links for classes.
if($class->owner_id == $current_user->ID || current_user_can('manage_options')) {
$var = '';
if(isset($_GET['incomplete'])) { $var = '&incomplete=1'; }
else if(isset($_GET['previous'])) { $var = '&previous=1'; }
else if(isset($_GET['myclasses'])) { $var = '&myclasses=1'; }
echo ' | <a href="'.$baseUrl.'-add-a-class&edit='.$class->id.'">Edit</a>';
echo ' | <a href="#" class="stopLinkFire" onclick="removeClass(\''.$baseUrl.$var.'&delete='.$class->id.'&n='.wp_create_nonce(self::SLUG.'-delete-'.$class->id).'\')">Delete</a>';
}
// Hidden class details.
echo '<td class="hide otherDetails">';
if($class->librarian2_name) { echo '<span name="Secondary_Librarian">'.esc_html($class->librarian2_name).'</span>'; }
if($class->instructor_email) { echo '<span name="Instructor_Email">'.esc_html($class->instructor_email).'</span>'; }
if($class->instructor_phone) { echo '<span name="Instructor_Phone">'.esc_html($class->instructor_phone).'</span>'; }
echo '<span name="Class_Location">'.esc_html($class->class_location).'</span>';
echo '<span name="Class_Type">'.esc_html($class->class_type).'</span>';
echo '<span name="Audience">'.esc_html($class->audience).'</span>';
if($class->class_description) { echo '<span name="Class_Description">'.esc_html($class->class_description).'</span>'; }
// Flags.
$flags = $wpdb->get_results('SELECT name, value FROM '.$this->tables['flags']. ' WHERE posts_id = '.$class->id ,ARRAY_A);
foreach($flags as $f) {
echo '<span name="'.esc_attr(preg_replace(array('/[^0-9a-zA-Z\/]/', '/\//'), array('_', '-'), $f['name'])).'">';
echo $f['value'] ? 'yes' : 'no';
echo '</span>';
}
echo '<span name="Attendance">'; echo ($class->attendance === NULL) ? 'Not Yet Recorded' : esc_html($class->attendance); echo '</span>';
echo '<span name="Last_Updated">'.date('n/j/Y g:i A', strtotime($class->last_updated, $timeStamp)).'</span>';
echo '</td>';
echo '</td></tr>';
}// End foreach loop for classes.
?>
</tbody>
</table>
</div>
<?php
}
/*
Function: addClassPage
The add a class page allows users to add a class to the instruction recorder. This
page is also used for editing and copying existing entries.
Outputs:
HTML for the add a class page.
See Also:
<addUpdateClass>
*/
public function addClassPage() {
if(!current_user_can('edit_posts')) {
wp_die('You do not have sufficient permissions to access this page.');
}
global $user_identity, $wpdb, $current_user;
$this->init($wpdb);
get_currentuserinfo();
$baseUrl = admin_url('admin.php?page='.self::SLUG.'-add-a-class');
$classAdded = NULL;
$error = array();
$timeStamp = current_time('timestamp');
// Remove added slashes!
if(!empty($_POST)) { $_POST = stripslashes_deep($_POST); }
// Prepare required meta fields (so we can check these).
$departmentGroup = unserialize($wpdb->get_var("SELECT value FROM ".$this->tables['meta']." WHERE field = 'department_group_values'"));
if(empty($departmentGroup)) { array_push($error, 'The department/group field is empty, please contact an administrator before continuing.'); }
$classLocation = unserialize($wpdb->get_var("SELECT value FROM ".$this->tables['meta']." WHERE field = 'class_location_values'"));
if(empty($classLocation)) { array_push($error, 'The class location field is empty, please contact an administrator before continuing.'); }
$classType = unserialize($wpdb->get_var("SELECT value FROM ".$this->tables['meta']." WHERE field = 'class_type_values'"));
if(empty($classType)) { array_push($error, 'The class type field is empty, please contact an administrator before continuing.'); }
$audience = unserialize($wpdb->get_var("SELECT value FROM ".$this->tables['meta']." WHERE field = 'audience_values'"));
if(empty($audience)) { array_push($error, 'The audience field is empty, please contact an administrator before continuing.'); }
// Edit a class setup and permission checking (for edit).
if(isset($_GET['edit']) && !isset($_POST['edit'])) {
$class = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$this->tables['posts']." WHERE id = %d", $_GET['edit']));
// Save DB to POST so fields can be populated from same pool during editing and failed submissions.
foreach($class as $x => $y) {
$_POST[$x] = $y;
}
// Permission checking.
if(!current_user_can('manage_options') && ($current_user->ID != $class->owner_id)) {
array_push($error, 'You do not have sufficient permissions to edit this class. <a href="'.$baseUrl.'">Add a new class?</a>');
$_POST['submitted'] = NULL; // Ensures the class is never processed for submission.
}
}
// If this is a copy class request (only if it has not been submitted).
else if(isset($_GET['copy']) && !isset($_POST['submitted'])) {
$class = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$this->tables['posts']." WHERE id = %d", $_GET['copy']));
// Save DB to POST so fields can be populated from same pool during editing and failed submissions.
foreach($class as $x => $y) {
$_POST[$x] = $y;
}
}
// Submission handling. **This should be done before headers are sent.**
if(isset($_POST['submitted']) && ($debug['nonce verified'] = wp_verify_nonce($_POST[self::SLUG.'_nonce'], self::SLUG.'_add_class'))) {
$classAdded = false; // Needed.
// Check to make sure all required fields have been submitted.
if(empty($_POST['librarian_name'])) { array_push($error, 'Missing Field: Primary Librarian'); }
if(empty($_POST['instructor_name'])) { array_push($error, 'Missing Field: Instructor Name'); }
if(empty($_POST['department_group'])) { array_push($error, 'Missing Field: Department/Group'); }
if(empty($_POST['class_date'])) { array_push($error, 'Missing Field: Class Date'); }
if(empty($_POST['class_time'])) { array_push($error, 'Missing Field: Class Time'); }
if(empty($_POST['class_length'])) { array_push($error, 'Missing Field: Class Length'); }
if(empty($_POST['class_location'])) { array_push($error, 'Missing Field: Class Location'); }
if(empty($_POST['class_type'])) { array_push($error, 'Missing Field: Class Type'); }
if(empty($_POST['audience'])) { array_push($error, 'Missing Field: Audience'); }
// Go to function to insert data into database.
if(empty($error)) { $classAdded = isset($_POST['edit']) ? $this->addUpdateClass($_POST['edit']) : $this->addUpdateClass(); }
// This will make things easier from here on down, although should not happen.
if($classAdded === 0) { $classAdded = true; }
// If update fails with no other errors.
if(!$classAdded && empty($error) && isset($_POST['edit'])) { array_push($error, 'An error has occurred while trying to update the class. Please try again.'); }
// If insert fails with no other errors.
else if(!$classAdded && empty($error)) { array_push($error, 'An error has occurred while trying to submit the class. Please try again.'); }
}
?>
<div class="wrap">
<h2><?= (isset($_GET['edit'])) ? 'Edit' : 'Add'; ?> a Class</h2>
<?php
// Added for debugging (if set).
if($this->options['debug']) {
echo '<div id="message" class="error">';
if(!empty($_POST)) {
echo '<p><strong>POST</strong></p>
<pre>'.print_r($_POST, true).'</pre>';
$array = preg_grep('/^flagName\d+/', array_keys($_POST));
echo '<p><strong>Flags</strong></p>
<pre>'.print_r($array, true).'</pre>';
}
if(!empty($debug)) {
echo '<p><strong>Other</strong></p>';
foreach($debug as $x => $y) {
echo '<p>'.$x.': '.$y.'</p>';
}
}
echo '<p>Last Query: '.$wpdb->last_query.'</p>';
echo '<p>Class Added: ';
if($classAdded) { echo $classAdded; }
else if($classAdded === NULL) { echo 'NULL'; }
else if($classAdded === false) { echo 'false'; }
else { echo 'who knows'; }
echo '</p>';
echo '</div>';
}
// End debugging.
// Message if an error occurred.
// Separating this from success messages since there are instances of a submission going through with an error present.
if(!empty($error)) {
echo '<div id="message" class="error">
<p><strong>';
foreach($error as $e) {
echo $e.'<br />';
}
echo '</strong></p>
</div>';
}
// Message if class was added.
if($classAdded && !isset($_POST['edit'])) {
echo '<div id="message" class="updated">
<p><strong>The class has been added!</strong> Need to <a href="'.$baseUrl.'&edit='.$classAdded.'">edit it</a>? <a href="'.$baseUrl.'©='.$classAdded.'">Copy it</a>? Would you like to <a href="'.$baseUrl.'">add a new class?</a></p>
</div>';
}
// Message if class was updated.
else if($classAdded && isset($_POST['edit'])) {
echo '<div id="message" class="updated">
<p><strong>The class has been updated!</strong> Need to <a href="'.$baseUrl.'&edit='.$_POST['edit'].'">edit it</a> again? <a href="'.$baseUrl.'©='.$_POST['edit'].'">Copy it</a>? Would you like to <a href="'.$baseUrl.'">add a new class?</a></p>
</div>';
}
?>
<form action="" method="post">
<table class="form-table">
<tr>
<th>*Primary Librarian</th>
<td><select name="librarian_name"><option value=""></option>
<?php
$user = $wpdb->get_results("SELECT display_name FROM ".$wpdb->users." ORDER BY display_name");
foreach($user as $u) {
// Hide admin account.
if($u->display_name == "admin") { continue; }
echo '<option';
// If nothing has been submitted and it's a new submission select current user.
if(($classAdded === NULL) && !(isset($_GET['edit']) || isset($_GET['copy'])) && ($u->display_name == $user_identity)) {
echo ' selected="selected"';
}
// If this is an edit or copy that hasn't been submitted display the previous name.
else if(($classAdded === NULL) && (isset($_GET['edit']) || isset($_GET['copy'])) && ($u->display_name == $_POST['librarian_name'])) {
echo ' selected="selected"';
}
// If there was a submission error display submitted name.
else if(($classAdded === false) && isset($_POST['librarian_name']) && ($u->display_name == $_POST['librarian_name'])) {
echo ' selected="selected"';
}
// After a successful submission.
else if($classAdded && ($u->display_name == $user_identity)) {
echo ' selected="selected"';
}
echo ' value="'.esc_attr($u->display_name).'">'.esc_html($u->display_name).'</option>';
}
?>
</select></td>
</tr>
<tr>
<th>Secondary Librarian</th>
<td><select name="librarian2_name"><option value=""></option>
<?php
foreach($user as $u) {
if($u->display_name == "admin") { continue; }
if(!$classAdded && isset($_POST['librarian2_name']) && ($u->display_name == $_POST['librarian2_name'])) {
echo '<option value="'.esc_attr($u->display_name).'" selected="selected">'.esc_html($u->display_name).'</option>';
}
else {
echo '<option value="'.esc_attr($u->display_name).'">'.esc_html($u->display_name).'</option>';
}
}
?>
</select></td>
</tr>
<tr>
<th>*Instructor Name</th>
<td><input type="text" name="instructor_name" value="<?php if(!$classAdded && !empty($_POST['instructor_name'])) echo esc_attr($_POST['instructor_name']); ?>" /></td>
</tr>
<tr>
<th>Instructor Email</th>
<td><input type="email" name="instructor_email" value="<?php if(!$classAdded && !empty($_POST['instructor_email'])) echo esc_attr($_POST['instructor_email']); ?>" /></td>
</tr>
<tr>
<th>Instructor Phone</th>
<td><input type="tel" name="instructor_phone" value="<?php if(!$classAdded && !empty($_POST['instructor_phone'])) echo esc_attr($_POST['instructor_phone']); ?>" /></td>
</tr>
<tr>
<th>Class Description</th>
<td><textarea id="classDescription" name="class_description"><?php if(!$classAdded && !empty($_POST['class_description'])) echo esc_textarea($_POST['class_description']); ?></textarea></td>
</tr>
<tr>
<th>*Department/Group</th>
<td>
<select name="department_group">
<option value=""> </option>
<?php
foreach($departmentGroup as $x) {
if(!$classAdded && isset($_POST['department_group']) && ($x == $_POST['department_group'])) {
echo '<option value="'.esc_attr($x).'" selected="selected">'.esc_html($x).'</option>';
}
else {
echo '<option value="'.esc_attr($x).'">'.esc_html($x).'</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<th>Course Number</th>
<td><input type="text" name="course_number" value="<?php if(!$classAdded && !empty($_POST['course_number'])) echo esc_attr($_POST['course_number']); ?>" /></td>
</tr>
<tr>
<th>*Class Date (M/D/YYYY)</th>
<td>
<?php
echo '<input type="text" class="'.self::SLUG.'-date" name="class_date" value="';
if(!$classAdded && !empty($_POST['class_date'])) {
echo esc_attr($_POST['class_date']);
}
else if(!$classAdded && !empty($_POST['class_start'])) {
echo date('n/j/Y', strtotime($_POST['class_start'], $timeStamp));
}
else {
echo date('n/j/Y', $timeStamp);
}
echo '" />';
?>
</td>
</tr>
<tr>
<th>*Class Time (H:MM AM|PM)</th>
<?php
if(!$classAdded && !empty($_POST['class_time'])) {
$time = date('g:i A', strtotime($_POST['class_time'], $timeStamp));
}
else if(!$classAdded && !empty($_POST['class_start'])) {
$time = date('g:i A', strtotime($_POST['class_start'], $timeStamp));
$_POST['class_length'] = (strtotime($_POST['class_end'], $timeStamp) - strtotime($_POST['class_start'], $timeStamp)) / 60;
}
else {
// Timezone was set here before.
$minutes = date('i', strtotime("+15 minutes", $timeStamp)) - date('i', strtotime("+15 minutes", $timeStamp)) % 15;
$time = date('g:', strtotime("+15 minutes", $timeStamp)).(($minutes) ? $minutes : '00').date(' A', $timeStamp);
}
?>
<td><input type="text" name="class_time" value="<?= esc_attr($time); ?>" /> <label>*Length</label><?php // Don't need to escape time but why not. ?>
<select name="class_length">
<option value="0"> </option>
<?php
for($i = 1; $i <= $this->options['intervalAmount']; $i++) {
$time = $this->options['intervalLength'] * $i;
echo '<option';
// Pre-select the option box if this is not a new class.
if(!$classAdded && !empty($_POST['class_length']) && ($_POST['class_length'] == $time)) { echo ' selected="selected"'; }
echo ' value="'.$time.'">';
if(floor($time / 60)) { echo floor($time / 60) == 1 ? '1 hour ' : floor($time / 60). ' hours '; }
if($time % 60) { echo ($time % 60) == 1 ? '1 minute' : ($time % 60).' minutes'; }
echo '</option>';
}
?>
</select>
</td>
</tr>
<tr>
<th>*Class Location</th>
<td><select name="class_location">
<option value=""> </option>
<?php
foreach($classLocation as $x) {
echo '<option value="'.esc_attr($x).'"';
if(!$classAdded && isset($_POST['class_location']) && ($_POST['class_location'] == $x)) {
echo ' selected="selected"';
}
echo '>'.esc_html($x).'</option>';
}
?>
</select></td>
</tr>
<tr>
<th>*Class Type</th>
<td><select name="class_type">
<option value=""> </option>
<?php
foreach($classType as $x) {
echo '<option value="'.esc_attr($x).'"';
if(!$classAdded && isset($_POST['class_type']) && ($_POST['class_type'] == $x)) {
echo ' selected="selected"';
}
echo '>'.esc_html($x).'</option>';
}
?>
</select></td>
</tr>
<tr>
<th>*Audience</th>
<td><select name="audience">
<option value=""> </option>
<?php
foreach($audience as $x) {
echo '<option value="'.esc_attr($x).'"';
if(!$classAdded && isset($_POST['audience']) && ($_POST['audience'] == $x)) {
echo ' selected="selected"';
}
echo '>'.esc_html($x).'</option>';
}
?>
</select></td>
</tr>
<?php
/*
Flags.
*/
$i = 1;
// Non-submitted edits.
if(($classAdded === NULL) && (isset($_GET['edit']) || isset($_GET['copy']))) {
$tempID = isset($_GET['edit']) ? $_GET['edit'] : $_GET['copy'];
$flags = $wpdb->get_results($wpdb->prepare("SELECT name, value FROM ".$this->tables['flags']." WHERE posts_id = %d", $tempID, OBJECT));
foreach($flags as $f) {
echo '<tr><th>'.esc_html($f->name).'</th>';
echo '<td><input type="checkbox" name="flagValue'.$i.'" ';
if($f->value) {
echo 'checked="checked"';
}
echo ' />';
echo '<input type="hidden" name="flagName'.$i.'" value="'.esc_attr($f->name).'" /></td></tr>';
$i++;
}
}
// For new entries and after successful submissions.
else if(($classAdded === NULL) || $classAdded) {
$flags = unserialize($wpdb->get_var("SELECT value FROM ".$this->tables['meta']." WHERE field = 'flag_info'"));
foreach($flags as $name => $isEnabled) {
if($isEnabled) {
echo '<tr><th>'.esc_html($name).'</th>';
echo '<td><input type="checkbox" name="flagValue'.$i.'" />';
echo '<input type="hidden" name="flagName'.$i.'" value="'.esc_attr($name).'" /></td></tr>';
$i++;
}
}
}
// For failed submissions.
// This could potentially be manipulated by fake POST data.
else if($classAdded === false) {
echo '<!-- FLAGS (classAdded === false) -->';
$flagNames = preg_grep('/^flagName\d+/', array_keys($_POST));
foreach($flagNames as $name) {
$d = substr($name, -1, 1);
if(!empty($_POST[$name])) {
echo '<tr><th>'.esc_html($_POST[$name]).'</th>';
echo '<td><input type="checkbox" name="flagValue'.$d.'"'; if(isset($_POST['flagValue'.$d]) && $_POST['flagValue'.$d] == 'on') { echo ' checked="checked"'; } echo ' />';
echo '<input type="hidden" name="flagName'.$d.'" value="'.esc_attr($_POST[$name]).'" /></td></tr>';
}
}
}
?>
<tr>
<th>Number of Students Attended</th>