Completed
Branch BUG-9042-ics-organizer-email (7b2e23)
by
unknown
29:24 queued 16:15
created
admin_pages/messages/Messages_Admin_Page.core.php 2 patches
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
         $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88 88
         $this->_admin_base_path = EE_MSG_ADMIN;
89 89
         
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
90
+        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state'] : array();
91 91
         
92 92
         $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93 93
         $this->_load_message_resource_manager();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
             array('none_selected' => __('Show All Messengers', 'event_espresso')),
220 220
             $messenger_options
221 221
         );
222
-        $input             = new EE_Select_Input(
222
+        $input = new EE_Select_Input(
223 223
             $messenger_options,
224 224
             array(
225 225
                 'html_name'  => 'ee_messenger_filter_by',
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             array('none_selected' => __('Show All Message Types', 'event_espresso')),
258 258
             $message_type_options
259 259
         );
260
-        $input                = new EE_Select_Input(
260
+        $input = new EE_Select_Input(
261 261
             $message_type_options,
262 262
             array(
263 263
                 'html_name'  => 'ee_message_type_filter_by',
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
             array('none_selected' => __('Show all Contexts', 'event_espresso')),
296 296
             $context_options
297 297
         );
298
-        $input           = new EE_Select_Input(
298
+        $input = new EE_Select_Input(
299 299
             $context_options,
300 300
             array(
301 301
                 'html_name'  => 'ee_context_filter_by',
@@ -676,47 +676,47 @@  discard block
 block discarded – undo
676 676
     
677 677
     public function messages_help_tab()
678 678
     {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
679
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
680 680
     }
681 681
     
682 682
     
683 683
     public function messengers_help_tab()
684 684
     {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
685
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
686 686
     }
687 687
     
688 688
     
689 689
     public function message_types_help_tab()
690 690
     {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
691
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
692 692
     }
693 693
     
694 694
     
695 695
     public function messages_overview_help_tab()
696 696
     {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
697
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
698 698
     }
699 699
     
700 700
     
701 701
     public function message_templates_help_tab()
702 702
     {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
703
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
704 704
     }
705 705
     
706 706
     
707 707
     public function edit_message_template_help_tab()
708 708
     {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
709
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'.esc_attr__('Editor Title',
710
+                'event_espresso').'" />';
711
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'.esc_attr__('Context Switcher and Preview',
712
+                'event_espresso').'" />';
713
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'.esc_attr__('Message Template Form Fields',
714
+                'event_espresso').'" />';
715
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'.esc_attr__('Shortcodes Metabox',
716
+                'event_espresso').'" />';
717
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'.esc_attr__('Publish Metabox',
718
+                'event_espresso').'" />';
719
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
720 720
             $args);
721 721
     }
722 722
     
@@ -725,37 +725,37 @@  discard block
 block discarded – undo
725 725
     {
726 726
         $this->_set_shortcodes();
727 727
         $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
728
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
729 729
             $args);
730 730
     }
731 731
     
732 732
     
733 733
     public function preview_message_help_tab()
734 734
     {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
735
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
736 736
     }
737 737
     
738 738
     
739 739
     public function settings_help_tab()
740 740
     {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
741
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'.'" alt="'.esc_attr__('Active Email Tab',
742
+                'event_espresso').'" />';
743
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'.'" alt="'.esc_attr__('Inactive Email Tab',
744
+                'event_espresso').'" />';
745 745
         $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746 746
         $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
747
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
748 748
     }
749 749
     
750 750
     
751 751
     public function load_scripts_styles()
752 752
     {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
753
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754 754
         wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
756
+        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL.'ee-messages-settings.js',
757 757
             array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
758
+        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
759 759
             array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760 760
     }
761 761
     
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
         
788 788
         $this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
790
+        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
791 791
             __('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792 792
                 'event_espresso'),
793 793
             $this->_message_template_group->messenger_obj()->label['singular'],
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
         EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797 797
             'event_espresso');
798 798
         
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
799
+        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL.'ee_message_editor.js', array('jquery'),
800 800
             EVENT_ESPRESSO_VERSION);
801 801
         
802 802
         wp_enqueue_script('ee_admin_js');
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
     
828 828
     public function load_scripts_styles_settings()
829 829
     {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
830
+        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL.'ee_message_settings.css', array(),
831 831
             EVENT_ESPRESSO_VERSION);
832 832
         wp_enqueue_style('ee-text-links');
833 833
         wp_enqueue_style('ee-message-settings');
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
             }
894 894
             $status_bulk_actions = $common_bulk_actions;
895 895
             //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
896
+            if ( ! empty($status_bulk_actions)) {
897 897
                 switch ($status) {
898 898
                     case EEM_Message::status_idle:
899 899
                     case EEM_Message::status_resend:
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
             }
919 919
 
920 920
             //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
921
+            if ($status === EEM_Message::status_messenger_executing) {
922 922
                 continue;
923 923
             }
924 924
             
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
         $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945 945
         $this->_template_args['per_column']        = 6;
946 946
         $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
947
+        $this->_template_args['before_list_table'] = '<h3>'.EEM_Message::instance()->get_pretty_label_for_results().'</h3>';
948 948
         $this->display_admin_list_table_page_with_no_sidebar();
949 949
     }
950 950
     
@@ -968,37 +968,37 @@  discard block
 block discarded – undo
968 968
         /** @type array $status_items status legend setup */
969 969
         $status_items = array(
970 970
             'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
971
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
972 972
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973 973
             ),
974 974
             'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
975
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
976 976
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977 977
             ),
978 978
             'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
979
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
980 980
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981 981
             ),
982 982
             'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
983
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
984 984
                 'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985 985
             ),
986 986
             'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
987
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
988 988
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989 989
             ),
990 990
             'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
991
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
992 992
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993 993
             ),
994 994
             'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
995
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
996 996
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997 997
             )
998 998
         );
999 999
         if (EEM_Message::debug()) {
1000 1000
             $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1001
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1002 1002
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003 1003
             );
1004 1004
         }
@@ -1010,10 +1010,10 @@  discard block
 block discarded – undo
1010 1010
     protected function _custom_mtps_preview()
1011 1011
     {
1012 1012
         $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
-                'event_espresso') . '</strong>';
1013
+        $this->_template_args['preview_img']  = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png" alt="'.esc_attr__('Preview Custom Message Templates screenshot',
1014
+                'event_espresso').'" />';
1015
+        $this->_template_args['preview_text'] = '<strong>'.__('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
+                'event_espresso').'</strong>';
1017 1017
         $this->display_admin_caf_preview_page('custom_message_types', false);
1018 1018
     }
1019 1019
     
@@ -1261,7 +1261,7 @@  discard block
 block discarded – undo
1261 1261
                             //let's verify if we need this extra field via the shortcodes parameter.
1262 1262
                             $continue = false;
1263 1263
                             if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1264
+                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1265 1265
                                     if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266 1266
                                         $continue = true;
1267 1267
                                     }
@@ -1271,9 +1271,9 @@  discard block
 block discarded – undo
1271 1271
                                 }
1272 1272
                             }
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1274
+                            $field_id                                = $reference_field.'-'.$extra_field.'-content';
1275 1275
                             $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1276
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['.$reference_field.'][content]['.$extra_field.']';
1277 1277
                             $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279 1279
                             $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
                                                                                 is_array($validators[$extra_field])
1284 1284
                                                                                 && isset($validators[$extra_field]['msg'])
1285 1285
                                                                             )
1286
-                                ? 'validate-error ' . $css_class
1286
+                                ? 'validate-error '.$css_class
1287 1287
                                 : $css_class;
1288 1288
                             
1289 1289
                             $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
@@ -1311,11 +1311,11 @@  discard block
 block discarded – undo
1311 1311
                                 
1312 1312
                             }/**/
1313 1313
                         }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1314
+                        $templatefield_MTP_id          = $reference_field.'-MTP_ID';
1315
+                        $templatefield_templatename_id = $reference_field.'-name';
1316 1316
                         
1317 1317
                         $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1318
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1319 1319
                             'label'      => null,
1320 1320
                             'input'      => 'hidden',
1321 1321
                             'type'       => 'int',
@@ -1328,7 +1328,7 @@  discard block
 block discarded – undo
1328 1328
                         );
1329 1329
                         
1330 1330
                         $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1331
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1332 1332
                             'label'      => null,
1333 1333
                             'input'      => 'hidden',
1334 1334
                             'type'       => 'string',
@@ -1342,9 +1342,9 @@  discard block
 block discarded – undo
1342 1342
                     }
1343 1343
                     continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344 1344
                 } else {
1345
-                    $field_id                                 = $template_field . '-content';
1345
+                    $field_id                                 = $template_field.'-content';
1346 1346
                     $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1347
+                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields['.$template_field.'][content]';
1348 1348
                     $message_template                         = isset($message_templates[$context][$template_field])
1349 1349
                         ? $message_templates[$context][$template_field]
1350 1350
                         : null;
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
                     $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366 1366
                                                                     && in_array($template_field, $v_fields)
1367 1367
                                                                     && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1368
+                        ? 'validate-error '.$css_class
1369 1369
                         : $css_class;
1370 1370
                     
1371 1371
                     //shortcode selector
@@ -1376,12 +1376,12 @@  discard block
 block discarded – undo
1376 1376
                 
1377 1377
                 //k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+                $templatefield_MTP_id                = $template_field.'-MTP_ID';
1380
+                $templatefield_field_templatename_id = $template_field.'-name';
1381 1381
                 
1382 1382
                 //foreach template field there are actually two form fields created
1383 1383
                 $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1384
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1385 1385
                     'label'      => null,
1386 1386
                     'input'      => 'hidden',
1387 1387
                     'type'       => 'int',
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
                 );
1395 1395
                 
1396 1396
                 $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1397
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1398 1398
                     'label'      => null,
1399 1399
                     'input'      => 'hidden',
1400 1400
                     'type'       => 'string',
@@ -1512,7 +1512,7 @@  discard block
 block discarded – undo
1512 1512
                 'format'     => '%d',
1513 1513
                 'db-col'     => 'MTP_deleted'
1514 1514
             );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1515
+            $sidebar_form_fields['ee-msg-author'] = array(
1516 1516
                 'name'       => 'MTP_user_id',
1517 1517
                 'label'      => __('Author', 'event_espresso'),
1518 1518
                 'input'      => 'hidden',
@@ -1531,17 +1531,17 @@  discard block
 block discarded – undo
1531 1531
                 'value' => $action
1532 1532
             );
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1534
+            $sidebar_form_fields['ee-msg-id'] = array(
1535 1535
                 'name'  => 'id',
1536 1536
                 'input' => 'hidden',
1537 1537
                 'type'  => 'int',
1538 1538
                 'value' => $GRP_ID
1539 1539
             );
1540 1540
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1541
+                'name'  => $action.'_nonce',
1542 1542
                 'input' => 'hidden',
1543 1543
                 'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1544
+                'value' => wp_create_nonce($action.'_nonce')
1545 1545
             );
1546 1546
             
1547 1547
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
         );
1574 1574
         
1575 1575
         //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1576
+        $preview_url = parent::add_query_args_and_nonce(
1577 1577
             array(
1578 1578
                 'message_type' => $message_template_group->message_type(),
1579 1579
                 'messenger'    => $message_template_group->messenger(),
@@ -1583,8 +1583,8 @@  discard block
 block discarded – undo
1583 1583
             ),
1584 1584
             $this->_admin_base_url
1585 1585
         );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1586
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'.__('Preview',
1587
+                'event_espresso').'</a>';
1588 1588
         
1589 1589
         
1590 1590
         //setup context switcher
@@ -1612,8 +1612,8 @@  discard block
 block discarded – undo
1612 1612
         $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613 1613
         
1614 1614
         $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1615
+            ? EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_edit_meta_box.template.php'
1616
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1617 1617
         
1618 1618
         //send along EE_Message_Template_Group object for further template use.
1619 1619
         $this->_template_args['MTP'] = $message_template_group;
@@ -1648,7 +1648,7 @@  discard block
 block discarded – undo
1648 1648
     
1649 1649
     public function _add_form_element_before()
1650 1650
     {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1651
+        return '<form method="post" action="'.$this->_template_args["edit_message_template_form_url"].'" id="ee-msg-edit-frm">';
1652 1652
     }
1653 1653
     
1654 1654
     public function _add_form_element_after()
@@ -1843,14 +1843,14 @@  discard block
 block discarded – undo
1843 1843
         }
1844 1844
         
1845 1845
         //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1846
+        $query_args = array(
1847 1847
             'id'      => $this->_req_data['GRP_ID'],
1848 1848
             'context' => $this->_req_data['context'],
1849 1849
             'action'  => 'edit_message_template'
1850 1850
         );
1851 1851
         $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1852
+        $preview_button         = '<a href="'.$go_back_url.'" class="button-secondary messages-preview-go-back-button">'.__('Go Back to Edit',
1853
+                'event_espresso').'</a>';
1854 1854
         $message_types          = $this->get_installed_message_types();
1855 1855
         $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856 1856
         $active_messenger_label = $active_messenger instanceof EE_messenger
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
         );
1865 1865
         //setup display of preview.
1866 1866
         $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1867
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.stripslashes($preview);
1868 1868
         $this->_template_args['data']['force_json'] = true;
1869 1869
         
1870 1870
         return '';
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
         }
1947 1947
         
1948 1948
         //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1949
+        $variations = $this->_message_template_group->get_template_pack()->get_variations(
1950 1950
             $this->_message_template_group->messenger(),
1951 1951
             $this->_message_template_group->message_type()
1952 1952
         );
@@ -1960,12 +1960,12 @@  discard block
 block discarded – undo
1960 1960
         
1961 1961
         $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962 1962
         
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1963
+        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
1964 1964
             'MTP_template_pack',
1965 1965
             $tp_select_values,
1966 1966
             $this->_message_template_group->get_template_pack_name()
1967 1967
         );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1968
+        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
1969 1969
             'MTP_template_variation',
1970 1970
             $variations_select_values,
1971 1971
             $this->_message_template_group->get_template_pack_variation()
@@ -1975,7 +1975,7 @@  discard block
 block discarded – undo
1975 1975
         $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976 1976
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977 1977
         
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1978
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
1979 1979
         
1980 1980
         EEH_Template::display_template($template, $template_args);
1981 1981
     }
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
         if ( ! empty($fields)) {
2005 2005
             //yup there be fields
2006 2006
             foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2007
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2008 2008
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009 2009
                 $default  = isset($config['default']) ? $config['default'] : '';
2010 2010
                 $default  = isset($config['value']) ? $config['value'] : $default;
@@ -2019,7 +2019,7 @@  discard block
 block discarded – undo
2019 2019
                     : $fix;
2020 2020
                 
2021 2021
                 $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2022
+                    'name'       => 'test_settings_fld['.$field.']',
2023 2023
                     'label'      => $config['label'],
2024 2024
                     'input'      => $config['input'],
2025 2025
                     'type'       => $config['type'],
@@ -2049,7 +2049,7 @@  discard block
 block discarded – undo
2049 2049
         }
2050 2050
         
2051 2051
         //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2052
+        $test_settings_html .= '<p>'.__('Need to reset this message type and start over?', 'event_espresso').'</p>';
2053 2053
         $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054 2054
         $test_settings_html .= $this->get_action_link_or_button(
2055 2055
             'reset_to_default',
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
             'linked_input_id' => $linked_input_id
2081 2081
         );
2082 2082
         
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2083
+        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2084 2084
             $template_args, true);
2085 2085
     }
2086 2086
     
@@ -2098,7 +2098,7 @@  discard block
 block discarded – undo
2098 2098
         //$messenger = $this->_message_template_group->messenger_obj();
2099 2099
         //now let's set the content depending on the status of the shortcodes array
2100 2100
         if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2101
+            $content = '<p>'.__('There are no valid shortcodes available', 'event_espresso').'</p>';
2102 2102
             echo $content;
2103 2103
         } else {
2104 2104
             //$alt = 0;
@@ -2215,7 +2215,7 @@  discard block
 block discarded – undo
2215 2215
                     <?php
2216 2216
                 }
2217 2217
                 //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2218
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2219 2219
                 ?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
@@ -2313,7 +2313,7 @@  discard block
 block discarded – undo
2313 2313
             : '';
2314 2314
         $context      = ucwords(str_replace('_', ' ', $context_slug));
2315 2315
         
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2316
+        $item_desc = $messenger_label && $message_type_label ? $messenger_label.' '.$message_type_label.' '.$context.' ' : '';
2317 2317
         $item_desc .= 'Message Template';
2318 2318
         $query_args  = array();
2319 2319
         $edit_array  = array();
@@ -2682,8 +2682,8 @@  discard block
 block discarded – undo
2682 2682
      */
2683 2683
     protected function _learn_more_about_message_templates_link()
2684 2684
     {
2685
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2686
-            'event_espresso') . '</a>';
2685
+        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'.__('learn more about how message templates works',
2686
+            'event_espresso').'</a>';
2687 2687
     }
2688 2688
     
2689 2689
     
@@ -2759,10 +2759,10 @@  discard block
 block discarded – undo
2759 2759
                 
2760 2760
                 $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2761 2761
                     'label'    => ucwords($message_type->label['singular']),
2762
-                    'class'    => 'message-type-' . $a_or_i,
2763
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2764
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2765
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2762
+                    'class'    => 'message-type-'.$a_or_i,
2763
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
2764
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
2765
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
2766 2766
                     'title'    => $a_or_i == 'active'
2767 2767
                         ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2768 2768
                         : __('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -2798,9 +2798,9 @@  discard block
 block discarded – undo
2798 2798
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2799 2799
             
2800 2800
             foreach ($fields as $fldname => $fldprops) {
2801
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2801
+                $field_id                       = $messenger->name.'-'.$message_type->name.'-'.$fldname;
2802 2802
                 $template_form_field[$field_id] = array(
2803
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2803
+                    'name'       => 'message_type_settings['.$fldname.']',
2804 2804
                     'label'      => $fldprops['label'],
2805 2805
                     'input'      => $fldprops['field_type'],
2806 2806
                     'type'       => $fldprops['value_type'],
@@ -2841,7 +2841,7 @@  discard block
 block discarded – undo
2841 2841
         $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2842 2842
         
2843 2843
         
2844
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2844
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
2845 2845
         $content  = EEH_Template::display_template($template, $settings_template_args, true);
2846 2846
         
2847 2847
         return $content;
@@ -2871,11 +2871,11 @@  discard block
 block discarded – undo
2871 2871
                 $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2872 2872
                     ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2873 2873
                     : '';
2874
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2874
+                $m_boxes[$messenger.'_a_box']         = sprintf(
2875 2875
                     __('%s Settings', 'event_espresso'),
2876 2876
                     $tab_array['label']
2877 2877
                 );
2878
-                $m_template_args[$messenger . '_a_box'] = array(
2878
+                $m_template_args[$messenger.'_a_box'] = array(
2879 2879
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2880 2880
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2881 2881
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2889,8 +2889,8 @@  discard block
 block discarded – undo
2889 2889
                 // message type meta boxes
2890 2890
                 // (which is really just the inactive container for each messenger
2891 2891
                 // showing inactive message types for that messenger)
2892
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
-                $mt_template_args[$messenger . '_i_box'] = array(
2892
+                $mt_boxes[$messenger.'_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
+                $mt_template_args[$messenger.'_i_box'] = array(
2894 2894
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895 2895
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896 2896
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2906,14 +2906,14 @@  discard block
 block discarded – undo
2906 2906
         
2907 2907
         
2908 2908
         //register messenger metaboxes
2909
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2909
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
2910 2910
         foreach ($m_boxes as $box => $label) {
2911 2911
             $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2912 2912
             $msgr          = str_replace('_a_box', '', $box);
2913 2913
             add_meta_box(
2914
-                'espresso_' . $msgr . '_settings',
2914
+                'espresso_'.$msgr.'_settings',
2915 2915
                 $label,
2916
-                function ($post, $metabox) {
2916
+                function($post, $metabox) {
2917 2917
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2918 2918
                         $metabox["args"]["template_args"], true);
2919 2919
                 },
@@ -2925,17 +2925,17 @@  discard block
 block discarded – undo
2925 2925
         }
2926 2926
         
2927 2927
         //register message type metaboxes
2928
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2928
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
2929 2929
         foreach ($mt_boxes as $box => $label) {
2930 2930
             $callback_args = array(
2931 2931
                 'template_path' => $mt_template_path,
2932 2932
                 'template_args' => $mt_template_args[$box]
2933 2933
             );
2934
-            $mt            = str_replace('_i_box', '', $box);
2934
+            $mt = str_replace('_i_box', '', $box);
2935 2935
             add_meta_box(
2936
-                'espresso_' . $mt . '_inactive_mts',
2936
+                'espresso_'.$mt.'_inactive_mts',
2937 2937
                 $label,
2938
-                function ($post, $metabox) {
2938
+                function($post, $metabox) {
2939 2939
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2940 2940
                         $metabox["args"]["template_args"], true);
2941 2941
                 },
@@ -3037,7 +3037,7 @@  discard block
 block discarded – undo
3037 3037
             if ($form->is_valid()) {
3038 3038
                 $valid_data = $form->valid_data();
3039 3039
                 foreach ($valid_data as $property => $value) {
3040
-                    $setter = 'set_' . $property;
3040
+                    $setter = 'set_'.$property;
3041 3041
                     if (method_exists($network_config, $setter)) {
3042 3042
                         $network_config->{$setter}($value);
3043 3043
                     } else if (
@@ -3066,8 +3066,8 @@  discard block
 block discarded – undo
3066 3066
      */
3067 3067
     protected function _get_mt_tabs($tab_array)
3068 3068
     {
3069
-        $tab_array = (array)$tab_array;
3070
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3069
+        $tab_array = (array) $tab_array;
3070
+        $template  = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3071 3071
         $tabs      = '';
3072 3072
         
3073 3073
         foreach ($tab_array as $tab) {
@@ -3100,9 +3100,9 @@  discard block
 block discarded – undo
3100 3100
             $existing_settings = $messenger->get_existing_admin_settings();
3101 3101
             
3102 3102
             foreach ($fields as $fldname => $fldprops) {
3103
-                $field_id                       = $messenger->name . '-' . $fldname;
3103
+                $field_id                       = $messenger->name.'-'.$fldname;
3104 3104
                 $template_form_field[$field_id] = array(
3105
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3105
+                    'name'       => 'messenger_settings['.$field_id.']',
3106 3106
                     'label'      => $fldprops['label'],
3107 3107
                     'input'      => $fldprops['field_type'],
3108 3108
                     'type'       => $fldprops['value_type'],
@@ -3137,7 +3137,7 @@  discard block
 block discarded – undo
3137 3137
         //make sure any active message types that are existing are included in the hidden fields
3138 3138
         if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3139 3139
             foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3140
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3140
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3141 3141
                     'type'  => 'hidden',
3142 3142
                     'value' => $mt
3143 3143
                 );
@@ -3147,7 +3147,7 @@  discard block
 block discarded – undo
3147 3147
             $settings_template_args['hidden_fields'],
3148 3148
             'array'
3149 3149
         );
3150
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3150
+        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3151 3151
         
3152 3152
         $settings_template_args['messenger']           = $messenger->name;
3153 3153
         $settings_template_args['description']         = $messenger->description;
@@ -3164,9 +3164,9 @@  discard block
 block discarded – undo
3164 3164
         
3165 3165
         
3166 3166
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3167
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3167
+        $settings_template_args['nonce']         = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3168 3168
         $settings_template_args['on_off_status'] = $active ? true : false;
3169
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3169
+        $template                                = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3170 3170
         $content                                 = EEH_Template::display_template($template, $settings_template_args,
3171 3171
             true);
3172 3172
         
@@ -3194,7 +3194,7 @@  discard block
 block discarded – undo
3194 3194
         
3195 3195
         //do a nonce check here since we're not arriving via a normal route
3196 3196
         $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3197
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3197
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3198 3198
         
3199 3199
         $this->_verify_nonce($nonce, $nonce_ref);
3200 3200
         
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
         
3297 3297
         //do a nonce check here since we're not arriving via a normal route
3298 3298
         $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3299
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3299
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3300 3300
         
3301 3301
         $this->_verify_nonce($nonce, $nonce_ref);
3302 3302
         
Please login to merge, or discard this patch.
Indentation   +3620 added lines, -3620 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('NO direct script access allowed');
2
+	exit('NO direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -17,2213 +17,2213 @@  discard block
 block discarded – undo
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19 19
     
20
-    /**
21
-     * @type EE_Message_Resource_Manager $_message_resource_manager
22
-     */
23
-    protected $_message_resource_manager;
24
-    
25
-    /**
26
-     * @type string $_active_message_type_name
27
-     */
28
-    protected $_active_message_type_name = '';
29
-    
30
-    /**
31
-     * @type EE_messenger $_active_messenger
32
-     */
33
-    protected $_active_messenger;
34
-    protected $_activate_state;
35
-    protected $_activate_meta_box_type;
36
-    protected $_current_message_meta_box;
37
-    protected $_current_message_meta_box_object;
38
-    protected $_context_switcher;
39
-    protected $_shortcodes = array();
40
-    protected $_active_messengers = array();
41
-    protected $_active_message_types = array();
42
-    
43
-    /**
44
-     * @var EE_Message_Template_Group $_message_template_group
45
-     */
46
-    protected $_message_template_group;
47
-    protected $_m_mt_settings = array();
48
-    
49
-    
50
-    /**
51
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
-     * IF there is no group then it gets automatically set to the Default template pack.
53
-     *
54
-     * @since 4.5.0
55
-     *
56
-     * @var EE_Messages_Template_Pack
57
-     */
58
-    protected $_template_pack;
59
-    
60
-    
61
-    /**
62
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
-     * group is.  If there is no group then it automatically gets set to default.
64
-     *
65
-     * @since 4.5.0
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_variation;
70
-    
71
-    
72
-    /**
73
-     * @param bool $routing
74
-     */
75
-    public function __construct($routing = true)
76
-    {
77
-        //make sure messages autoloader is running
78
-        EED_Messages::set_autoloaders();
79
-        parent::__construct($routing);
80
-    }
81
-    
82
-    
83
-    protected function _init_page_props()
84
-    {
85
-        $this->page_slug        = EE_MSG_PG_SLUG;
86
-        $this->page_label       = __('Messages Settings', 'event_espresso');
87
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
-        $this->_admin_base_path = EE_MSG_ADMIN;
89
-        
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
-        
92
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
-        $this->_load_message_resource_manager();
94
-    }
95
-    
96
-    
97
-    /**
98
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
-     *
100
-     *
101
-     * @throws EE_Error
102
-     */
103
-    protected function _load_message_resource_manager()
104
-    {
105
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
-    }
107
-    
108
-    
109
-    /**
110
-     * @deprecated 4.9.9.rc.014
111
-     * @return array
112
-     */
113
-    public function get_messengers_for_list_table()
114
-    {
115
-        EE_Error::doing_it_wrong(
116
-            __METHOD__,
117
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
20
+	/**
21
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
22
+	 */
23
+	protected $_message_resource_manager;
24
+    
25
+	/**
26
+	 * @type string $_active_message_type_name
27
+	 */
28
+	protected $_active_message_type_name = '';
29
+    
30
+	/**
31
+	 * @type EE_messenger $_active_messenger
32
+	 */
33
+	protected $_active_messenger;
34
+	protected $_activate_state;
35
+	protected $_activate_meta_box_type;
36
+	protected $_current_message_meta_box;
37
+	protected $_current_message_meta_box_object;
38
+	protected $_context_switcher;
39
+	protected $_shortcodes = array();
40
+	protected $_active_messengers = array();
41
+	protected $_active_message_types = array();
42
+    
43
+	/**
44
+	 * @var EE_Message_Template_Group $_message_template_group
45
+	 */
46
+	protected $_message_template_group;
47
+	protected $_m_mt_settings = array();
48
+    
49
+    
50
+	/**
51
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
+	 * IF there is no group then it gets automatically set to the Default template pack.
53
+	 *
54
+	 * @since 4.5.0
55
+	 *
56
+	 * @var EE_Messages_Template_Pack
57
+	 */
58
+	protected $_template_pack;
59
+    
60
+    
61
+	/**
62
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
+	 * group is.  If there is no group then it automatically gets set to default.
64
+	 *
65
+	 * @since 4.5.0
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_variation;
70
+    
71
+    
72
+	/**
73
+	 * @param bool $routing
74
+	 */
75
+	public function __construct($routing = true)
76
+	{
77
+		//make sure messages autoloader is running
78
+		EED_Messages::set_autoloaders();
79
+		parent::__construct($routing);
80
+	}
81
+    
82
+    
83
+	protected function _init_page_props()
84
+	{
85
+		$this->page_slug        = EE_MSG_PG_SLUG;
86
+		$this->page_label       = __('Messages Settings', 'event_espresso');
87
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
+		$this->_admin_base_path = EE_MSG_ADMIN;
89
+        
90
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
+        
92
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
+		$this->_load_message_resource_manager();
94
+	}
95
+    
96
+    
97
+	/**
98
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
+	 *
100
+	 *
101
+	 * @throws EE_Error
102
+	 */
103
+	protected function _load_message_resource_manager()
104
+	{
105
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
+	}
107
+    
108
+    
109
+	/**
110
+	 * @deprecated 4.9.9.rc.014
111
+	 * @return array
112
+	 */
113
+	public function get_messengers_for_list_table()
114
+	{
115
+		EE_Error::doing_it_wrong(
116
+			__METHOD__,
117
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
118 118
 			values for use in creating a messenger filter dropdown which is now generated differently via
119 119
 			 Messages_Admin_Page::get_messengers_select_input', 'event_espresso'),
120
-            '4.9.9.rc.014'
121
-        );
122
-        
123
-        $m_values          = array();
124
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
-        //setup messengers for selects
126
-        $i = 1;
127
-        foreach ($active_messengers as $active_messenger) {
128
-            if ($active_messenger instanceof EE_Message) {
129
-                $m_values[$i]['id']   = $active_messenger->messenger();
130
-                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
-                $i++;
132
-            }
133
-        }
134
-        
135
-        return $m_values;
136
-    }
137
-    
138
-    
139
-    /**
140
-     * @deprecated 4.9.9.rc.014
141
-     * @return array
142
-     */
143
-    public function get_message_types_for_list_table()
144
-    {
145
-        EE_Error::doing_it_wrong(
146
-            __METHOD__,
147
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
120
+			'4.9.9.rc.014'
121
+		);
122
+        
123
+		$m_values          = array();
124
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
+		//setup messengers for selects
126
+		$i = 1;
127
+		foreach ($active_messengers as $active_messenger) {
128
+			if ($active_messenger instanceof EE_Message) {
129
+				$m_values[$i]['id']   = $active_messenger->messenger();
130
+				$m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
+				$i++;
132
+			}
133
+		}
134
+        
135
+		return $m_values;
136
+	}
137
+    
138
+    
139
+	/**
140
+	 * @deprecated 4.9.9.rc.014
141
+	 * @return array
142
+	 */
143
+	public function get_message_types_for_list_table()
144
+	{
145
+		EE_Error::doing_it_wrong(
146
+			__METHOD__,
147
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
148 148
 			values for use in creating a message type filter dropdown which is now generated differently via
149 149
 			 Messages_Admin_Page::get_message_types_select_input', 'event_espresso'),
150
-            '4.9.9.rc.014'
151
-        );
152
-        
153
-        $mt_values       = array();
154
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
-        $i               = 1;
156
-        foreach ($active_messages as $active_message) {
157
-            if ($active_message instanceof EE_Message) {
158
-                $mt_values[$i]['id']   = $active_message->message_type();
159
-                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
-                $i++;
161
-            }
162
-        }
163
-        
164
-        return $mt_values;
165
-    }
166
-    
167
-    
168
-    /**
169
-     * @deprecated 4.9.9.rc.014
170
-     * @return array
171
-     */
172
-    public function get_contexts_for_message_types_for_list_table()
173
-    {
174
-        EE_Error::doing_it_wrong(
175
-            __METHOD__,
176
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
150
+			'4.9.9.rc.014'
151
+		);
152
+        
153
+		$mt_values       = array();
154
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
+		$i               = 1;
156
+		foreach ($active_messages as $active_message) {
157
+			if ($active_message instanceof EE_Message) {
158
+				$mt_values[$i]['id']   = $active_message->message_type();
159
+				$mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
+				$i++;
161
+			}
162
+		}
163
+        
164
+		return $mt_values;
165
+	}
166
+    
167
+    
168
+	/**
169
+	 * @deprecated 4.9.9.rc.014
170
+	 * @return array
171
+	 */
172
+	public function get_contexts_for_message_types_for_list_table()
173
+	{
174
+		EE_Error::doing_it_wrong(
175
+			__METHOD__,
176
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
177 177
 			values for use in creating a message type context filter dropdown which is now generated differently via
178 178
 			 Messages_Admin_Page::get_contexts_for_message_types_select_input', 'event_espresso'),
179
-            '4.9.9.rc.014'
180
-        );
181
-        
182
-        $contexts                = array();
183
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
-        foreach ($active_message_contexts as $active_message) {
185
-            if ($active_message instanceof EE_Message) {
186
-                $message_type = $active_message->message_type_object();
187
-                if ($message_type instanceof EE_message_type) {
188
-                    $message_type_contexts = $message_type->get_contexts();
189
-                    foreach ($message_type_contexts as $context => $context_details) {
190
-                        $contexts[$context] = $context_details['label'];
191
-                    }
192
-                }
193
-            }
194
-        }
195
-        
196
-        return $contexts;
197
-    }
198
-    
199
-    
200
-    /**
201
-     * Generate select input with provided messenger options array.
202
-     *
203
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
-     *                                 labels.
205
-     *
206
-     * @return string
207
-     */
208
-    public function get_messengers_select_input($messenger_options)
209
-    {
210
-        //if empty or just one value then just return an empty string
211
-        if (empty($messenger_options)
212
-            || ! is_array($messenger_options)
213
-            || count($messenger_options) === 1
214
-        ) {
215
-            return '';
216
-        }
217
-        //merge in default
218
-        $messenger_options = array_merge(
219
-            array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
-            $messenger_options
221
-        );
222
-        $input             = new EE_Select_Input(
223
-            $messenger_options,
224
-            array(
225
-                'html_name'  => 'ee_messenger_filter_by',
226
-                'html_id'    => 'ee_messenger_filter_by',
227
-                'html_class' => 'wide',
228
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
-                    : 'none_selected'
231
-            )
232
-        );
233
-        
234
-        return $input->get_html_for_input();
235
-    }
236
-    
237
-    
238
-    /**
239
-     * Generate select input with provided message type options array.
240
-     *
241
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
-     *                                    message type labels
243
-     *
244
-     * @return string
245
-     */
246
-    public function get_message_types_select_input($message_type_options)
247
-    {
248
-        //if empty or count of options is 1 then just return an empty string
249
-        if (empty($message_type_options)
250
-            || ! is_array($message_type_options)
251
-            || count($message_type_options) === 1
252
-        ) {
253
-            return '';
254
-        }
255
-        //merge in default
256
-        $message_type_options = array_merge(
257
-            array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
-            $message_type_options
259
-        );
260
-        $input                = new EE_Select_Input(
261
-            $message_type_options,
262
-            array(
263
-                'html_name'  => 'ee_message_type_filter_by',
264
-                'html_id'    => 'ee_message_type_filter_by',
265
-                'html_class' => 'wide',
266
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
-                    : 'none_selected',
269
-            )
270
-        );
271
-        
272
-        return $input->get_html_for_input();
273
-    }
274
-    
275
-    
276
-    /**
277
-     * Generate select input with provide message type contexts array.
278
-     *
279
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
-     *                               context label.
281
-     *
282
-     * @return string
283
-     */
284
-    public function get_contexts_for_message_types_select_input($context_options)
285
-    {
286
-        //if empty or count of options is one then just return empty string
287
-        if (empty($context_options)
288
-            || ! is_array($context_options)
289
-            || count($context_options) === 1
290
-        ) {
291
-            return '';
292
-        }
293
-        //merge in default
294
-        $context_options = array_merge(
295
-            array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
-            $context_options
297
-        );
298
-        $input           = new EE_Select_Input(
299
-            $context_options,
300
-            array(
301
-                'html_name'  => 'ee_context_filter_by',
302
-                'html_id'    => 'ee_context_filter_by',
303
-                'html_class' => 'wide',
304
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
305
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
306
-                    : 'none_selected',
307
-            )
308
-        );
309
-        
310
-        return $input->get_html_for_input();
311
-    }
312
-    
313
-    
314
-    protected function _ajax_hooks()
315
-    {
316
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
-    }
322
-    
323
-    
324
-    protected function _define_page_props()
325
-    {
326
-        $this->_admin_page_title = $this->page_label;
327
-        $this->_labels           = array(
328
-            'buttons'    => array(
329
-                'add'    => __('Add New Message Template', 'event_espresso'),
330
-                'edit'   => __('Edit Message Template', 'event_espresso'),
331
-                'delete' => __('Delete Message Template', 'event_espresso')
332
-            ),
333
-            'publishbox' => __('Update Actions', 'event_espresso')
334
-        );
335
-    }
336
-    
337
-    
338
-    /**
339
-     *        an array for storing key => value pairs of request actions and their corresponding methods
340
-     * @access protected
341
-     * @return void
342
-     */
343
-    protected function _set_page_routes()
344
-    {
345
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
-            ? $this->_req_data['GRP_ID']
347
-            : 0;
348
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
-            ? $this->_req_data['id']
350
-            : $grp_id;
351
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
-            ? $this->_req_data['MSG_ID']
353
-            : 0;
354
-        
355
-        $this->_page_routes = array(
356
-            'default'                          => array(
357
-                'func'       => '_message_queue_list_table',
358
-                'capability' => 'ee_read_global_messages'
359
-            ),
360
-            'global_mtps'                      => array(
361
-                'func'       => '_ee_default_messages_overview_list_table',
362
-                'capability' => 'ee_read_global_messages'
363
-            ),
364
-            'custom_mtps'                      => array(
365
-                'func'       => '_custom_mtps_preview',
366
-                'capability' => 'ee_read_messages'
367
-            ),
368
-            'add_new_message_template'         => array(
369
-                'func'       => '_add_message_template',
370
-                'capability' => 'ee_edit_messages',
371
-                'noheader'   => true
372
-            ),
373
-            'edit_message_template'            => array(
374
-                'func'       => '_edit_message_template',
375
-                'capability' => 'ee_edit_message',
376
-                'obj_id'     => $grp_id
377
-            ),
378
-            'preview_message'                  => array(
379
-                'func'               => '_preview_message',
380
-                'capability'         => 'ee_read_message',
381
-                'obj_id'             => $grp_id,
382
-                'noheader'           => true,
383
-                'headers_sent_route' => 'display_preview_message'
384
-            ),
385
-            'display_preview_message'          => array(
386
-                'func'       => '_display_preview_message',
387
-                'capability' => 'ee_read_message',
388
-                'obj_id'     => $grp_id
389
-            ),
390
-            'insert_message_template'          => array(
391
-                'func'       => '_insert_or_update_message_template',
392
-                'capability' => 'ee_edit_messages',
393
-                'args'       => array('new_template' => true),
394
-                'noheader'   => true
395
-            ),
396
-            'update_message_template'          => array(
397
-                'func'       => '_insert_or_update_message_template',
398
-                'capability' => 'ee_edit_message',
399
-                'obj_id'     => $grp_id,
400
-                'args'       => array('new_template' => false),
401
-                'noheader'   => true
402
-            ),
403
-            'trash_message_template'           => array(
404
-                'func'       => '_trash_or_restore_message_template',
405
-                'capability' => 'ee_delete_message',
406
-                'obj_id'     => $grp_id,
407
-                'args'       => array('trash' => true, 'all' => true),
408
-                'noheader'   => true
409
-            ),
410
-            'trash_message_template_context'   => array(
411
-                'func'       => '_trash_or_restore_message_template',
412
-                'capability' => 'ee_delete_message',
413
-                'obj_id'     => $grp_id,
414
-                'args'       => array('trash' => true),
415
-                'noheader'   => true
416
-            ),
417
-            'restore_message_template'         => array(
418
-                'func'       => '_trash_or_restore_message_template',
419
-                'capability' => 'ee_delete_message',
420
-                'obj_id'     => $grp_id,
421
-                'args'       => array('trash' => false, 'all' => true),
422
-                'noheader'   => true
423
-            ),
424
-            'restore_message_template_context' => array(
425
-                'func'       => '_trash_or_restore_message_template',
426
-                'capability' => 'ee_delete_message',
427
-                'obj_id'     => $grp_id,
428
-                'args'       => array('trash' => false),
429
-                'noheader'   => true
430
-            ),
431
-            'delete_message_template'          => array(
432
-                'func'       => '_delete_message_template',
433
-                'capability' => 'ee_delete_message',
434
-                'obj_id'     => $grp_id,
435
-                'noheader'   => true
436
-            ),
437
-            'reset_to_default'                 => array(
438
-                'func'       => '_reset_to_default_template',
439
-                'capability' => 'ee_edit_message',
440
-                'obj_id'     => $grp_id,
441
-                'noheader'   => true
442
-            ),
443
-            'settings'                         => array(
444
-                'func'       => '_settings',
445
-                'capability' => 'manage_options'
446
-            ),
447
-            'update_global_settings'           => array(
448
-                'func'       => '_update_global_settings',
449
-                'capability' => 'manage_options',
450
-                'noheader'   => true
451
-            ),
452
-            'generate_now'                     => array(
453
-                'func'       => '_generate_now',
454
-                'capability' => 'ee_send_message',
455
-                'noheader'   => true
456
-            ),
457
-            'generate_and_send_now'            => array(
458
-                'func'       => '_generate_and_send_now',
459
-                'capability' => 'ee_send_message',
460
-                'noheader'   => true
461
-            ),
462
-            'queue_for_resending'              => array(
463
-                'func'       => '_queue_for_resending',
464
-                'capability' => 'ee_send_message',
465
-                'noheader'   => true
466
-            ),
467
-            'send_now'                         => array(
468
-                'func'       => '_send_now',
469
-                'capability' => 'ee_send_message',
470
-                'noheader'   => true
471
-            ),
472
-            'delete_ee_message'                => array(
473
-                'func'       => '_delete_ee_messages',
474
-                'capability' => 'ee_delete_message',
475
-                'noheader'   => true
476
-            ),
477
-            'delete_ee_messages'               => array(
478
-                'func'       => '_delete_ee_messages',
479
-                'capability' => 'ee_delete_messages',
480
-                'noheader'   => true,
481
-                'obj_id'     => $msg_id
482
-            )
483
-        );
484
-    }
485
-    
486
-    
487
-    protected function _set_page_config()
488
-    {
489
-        $this->_page_config = array(
490
-            'default'                  => array(
491
-                'nav'           => array(
492
-                    'label' => __('Message Activity', 'event_espresso'),
493
-                    'order' => 10
494
-                ),
495
-                'list_table'    => 'EE_Message_List_Table',
496
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
-                'require_nonce' => false
498
-            ),
499
-            'global_mtps'              => array(
500
-                'nav'           => array(
501
-                    'label' => __('Default Message Templates', 'event_espresso'),
502
-                    'order' => 20
503
-                ),
504
-                'list_table'    => 'Messages_Template_List_Table',
505
-                'help_tabs'     => array(
506
-                    'messages_overview_help_tab'                                => array(
507
-                        'title'    => __('Messages Overview', 'event_espresso'),
508
-                        'filename' => 'messages_overview'
509
-                    ),
510
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
511
-                        'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'messages_overview_table_column_headings'
513
-                    ),
514
-                    'messages_overview_messages_filters_help_tab'               => array(
515
-                        'title'    => __('Message Filters', 'event_espresso'),
516
-                        'filename' => 'messages_overview_filters'
517
-                    ),
518
-                    'messages_overview_messages_views_help_tab'                 => array(
519
-                        'title'    => __('Message Views', 'event_espresso'),
520
-                        'filename' => 'messages_overview_views'
521
-                    ),
522
-                    'message_overview_message_types_help_tab'                   => array(
523
-                        'title'    => __('Message Types', 'event_espresso'),
524
-                        'filename' => 'messages_overview_types'
525
-                    ),
526
-                    'messages_overview_messengers_help_tab'                     => array(
527
-                        'title'    => __('Messengers', 'event_espresso'),
528
-                        'filename' => 'messages_overview_messengers',
529
-                    ),
530
-                    'messages_overview_other_help_tab'                          => array(
531
-                        'title'    => __('Messages Other', 'event_espresso'),
532
-                        'filename' => 'messages_overview_other',
533
-                    ),
534
-                ),
535
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
536
-                'require_nonce' => false
537
-            ),
538
-            'custom_mtps'              => array(
539
-                'nav'           => array(
540
-                    'label' => __('Custom Message Templates', 'event_espresso'),
541
-                    'order' => 30
542
-                ),
543
-                'help_tabs'     => array(),
544
-                'help_tour'     => array(),
545
-                'require_nonce' => false
546
-            ),
547
-            'add_new_message_template' => array(
548
-                'nav'           => array(
549
-                    'label'      => __('Add New Message Templates', 'event_espresso'),
550
-                    'order'      => 5,
551
-                    'persistent' => false
552
-                ),
553
-                'require_nonce' => false
554
-            ),
555
-            'edit_message_template'    => array(
556
-                'labels'        => array(
557
-                    'buttons'    => array(
558
-                        'reset' => __('Reset Templates'),
559
-                    ),
560
-                    'publishbox' => __('Update Actions', 'event_espresso')
561
-                ),
562
-                'nav'           => array(
563
-                    'label'      => __('Edit Message Templates', 'event_espresso'),
564
-                    'order'      => 5,
565
-                    'persistent' => false,
566
-                    'url'        => ''
567
-                ),
568
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
-                'has_metaboxes' => true,
570
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
-                'help_tabs'     => array(
572
-                    'edit_message_template'       => array(
573
-                        'title'    => __('Message Template Editor', 'event_espresso'),
574
-                        'callback' => 'edit_message_template_help_tab'
575
-                    ),
576
-                    'message_templates_help_tab'  => array(
577
-                        'title'    => __('Message Templates', 'event_espresso'),
578
-                        'filename' => 'messages_templates'
579
-                    ),
580
-                    'message_template_shortcodes' => array(
581
-                        'title'    => __('Message Shortcodes', 'event_espresso'),
582
-                        'callback' => 'message_template_shortcodes_help_tab'
583
-                    ),
584
-                    'message_preview_help_tab'    => array(
585
-                        'title'    => __('Message Preview', 'event_espresso'),
586
-                        'filename' => 'messages_preview'
587
-                    ),
588
-                ),
589
-                'require_nonce' => false
590
-            ),
591
-            'display_preview_message'  => array(
592
-                'nav'           => array(
593
-                    'label'      => __('Message Preview', 'event_espresso'),
594
-                    'order'      => 5,
595
-                    'url'        => '',
596
-                    'persistent' => false
597
-                ),
598
-                'help_tabs'     => array(
599
-                    'preview_message' => array(
600
-                        'title'    => __('About Previews', 'event_espresso'),
601
-                        'callback' => 'preview_message_help_tab'
602
-                    )
603
-                ),
604
-                'require_nonce' => false
605
-            ),
606
-            'settings'                 => array(
607
-                'nav'           => array(
608
-                    'label' => __('Settings', 'event_espresso'),
609
-                    'order' => 40
610
-                ),
611
-                'metaboxes'     => array('_messages_settings_metaboxes'),
612
-                'help_tabs'     => array(
613
-                    'messages_settings_help_tab'               => array(
614
-                        'title'    => __('Messages Settings', 'event_espresso'),
615
-                        'filename' => 'messages_settings'
616
-                    ),
617
-                    'messages_settings_message_types_help_tab' => array(
618
-                        'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
-                        'filename' => 'messages_settings_message_types'
620
-                    ),
621
-                    'messages_settings_messengers_help_tab'    => array(
622
-                        'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
-                        'filename' => 'messages_settings_messengers'
624
-                    ),
625
-                ),
626
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
627
-                'require_nonce' => false
628
-            )
629
-        );
630
-    }
631
-    
632
-    
633
-    protected function _add_screen_options()
634
-    {
635
-        //todo
636
-    }
637
-    
638
-    
639
-    protected function _add_screen_options_global_mtps()
640
-    {
641
-        /**
642
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
644
-         */
645
-        $page_title              = $this->_admin_page_title;
646
-        $this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
-        $this->_per_page_screen_option();
648
-        $this->_admin_page_title = $page_title;
649
-    }
650
-    
651
-    
652
-    protected function _add_screen_options_default()
653
-    {
654
-        $this->_admin_page_title = __('Message Activity', 'event_espresso');
655
-        $this->_per_page_screen_option();
656
-    }
657
-    
658
-    
659
-    //none of the below group are currently used for Messages
660
-    protected function _add_feature_pointers()
661
-    {
662
-    }
663
-    
664
-    public function admin_init()
665
-    {
666
-    }
667
-    
668
-    public function admin_notices()
669
-    {
670
-    }
671
-    
672
-    public function admin_footer_scripts()
673
-    {
674
-    }
675
-    
676
-    
677
-    public function messages_help_tab()
678
-    {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
-    }
681
-    
682
-    
683
-    public function messengers_help_tab()
684
-    {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
-    }
687
-    
688
-    
689
-    public function message_types_help_tab()
690
-    {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
-    }
693
-    
694
-    
695
-    public function messages_overview_help_tab()
696
-    {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
-    }
699
-    
700
-    
701
-    public function message_templates_help_tab()
702
-    {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
-    }
705
-    
706
-    
707
-    public function edit_message_template_help_tab()
708
-    {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
-            $args);
721
-    }
722
-    
723
-    
724
-    public function message_template_shortcodes_help_tab()
725
-    {
726
-        $this->_set_shortcodes();
727
-        $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
-            $args);
730
-    }
179
+			'4.9.9.rc.014'
180
+		);
181
+        
182
+		$contexts                = array();
183
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
+		foreach ($active_message_contexts as $active_message) {
185
+			if ($active_message instanceof EE_Message) {
186
+				$message_type = $active_message->message_type_object();
187
+				if ($message_type instanceof EE_message_type) {
188
+					$message_type_contexts = $message_type->get_contexts();
189
+					foreach ($message_type_contexts as $context => $context_details) {
190
+						$contexts[$context] = $context_details['label'];
191
+					}
192
+				}
193
+			}
194
+		}
195
+        
196
+		return $contexts;
197
+	}
198
+    
199
+    
200
+	/**
201
+	 * Generate select input with provided messenger options array.
202
+	 *
203
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
+	 *                                 labels.
205
+	 *
206
+	 * @return string
207
+	 */
208
+	public function get_messengers_select_input($messenger_options)
209
+	{
210
+		//if empty or just one value then just return an empty string
211
+		if (empty($messenger_options)
212
+			|| ! is_array($messenger_options)
213
+			|| count($messenger_options) === 1
214
+		) {
215
+			return '';
216
+		}
217
+		//merge in default
218
+		$messenger_options = array_merge(
219
+			array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
+			$messenger_options
221
+		);
222
+		$input             = new EE_Select_Input(
223
+			$messenger_options,
224
+			array(
225
+				'html_name'  => 'ee_messenger_filter_by',
226
+				'html_id'    => 'ee_messenger_filter_by',
227
+				'html_class' => 'wide',
228
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
+					: 'none_selected'
231
+			)
232
+		);
233
+        
234
+		return $input->get_html_for_input();
235
+	}
236
+    
237
+    
238
+	/**
239
+	 * Generate select input with provided message type options array.
240
+	 *
241
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
+	 *                                    message type labels
243
+	 *
244
+	 * @return string
245
+	 */
246
+	public function get_message_types_select_input($message_type_options)
247
+	{
248
+		//if empty or count of options is 1 then just return an empty string
249
+		if (empty($message_type_options)
250
+			|| ! is_array($message_type_options)
251
+			|| count($message_type_options) === 1
252
+		) {
253
+			return '';
254
+		}
255
+		//merge in default
256
+		$message_type_options = array_merge(
257
+			array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
+			$message_type_options
259
+		);
260
+		$input                = new EE_Select_Input(
261
+			$message_type_options,
262
+			array(
263
+				'html_name'  => 'ee_message_type_filter_by',
264
+				'html_id'    => 'ee_message_type_filter_by',
265
+				'html_class' => 'wide',
266
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
+					: 'none_selected',
269
+			)
270
+		);
271
+        
272
+		return $input->get_html_for_input();
273
+	}
274
+    
275
+    
276
+	/**
277
+	 * Generate select input with provide message type contexts array.
278
+	 *
279
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
+	 *                               context label.
281
+	 *
282
+	 * @return string
283
+	 */
284
+	public function get_contexts_for_message_types_select_input($context_options)
285
+	{
286
+		//if empty or count of options is one then just return empty string
287
+		if (empty($context_options)
288
+			|| ! is_array($context_options)
289
+			|| count($context_options) === 1
290
+		) {
291
+			return '';
292
+		}
293
+		//merge in default
294
+		$context_options = array_merge(
295
+			array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
+			$context_options
297
+		);
298
+		$input           = new EE_Select_Input(
299
+			$context_options,
300
+			array(
301
+				'html_name'  => 'ee_context_filter_by',
302
+				'html_id'    => 'ee_context_filter_by',
303
+				'html_class' => 'wide',
304
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
305
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
306
+					: 'none_selected',
307
+			)
308
+		);
309
+        
310
+		return $input->get_html_for_input();
311
+	}
312
+    
313
+    
314
+	protected function _ajax_hooks()
315
+	{
316
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
+	}
322
+    
323
+    
324
+	protected function _define_page_props()
325
+	{
326
+		$this->_admin_page_title = $this->page_label;
327
+		$this->_labels           = array(
328
+			'buttons'    => array(
329
+				'add'    => __('Add New Message Template', 'event_espresso'),
330
+				'edit'   => __('Edit Message Template', 'event_espresso'),
331
+				'delete' => __('Delete Message Template', 'event_espresso')
332
+			),
333
+			'publishbox' => __('Update Actions', 'event_espresso')
334
+		);
335
+	}
336
+    
337
+    
338
+	/**
339
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
340
+	 * @access protected
341
+	 * @return void
342
+	 */
343
+	protected function _set_page_routes()
344
+	{
345
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
+			? $this->_req_data['GRP_ID']
347
+			: 0;
348
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
+			? $this->_req_data['id']
350
+			: $grp_id;
351
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
+			? $this->_req_data['MSG_ID']
353
+			: 0;
354
+        
355
+		$this->_page_routes = array(
356
+			'default'                          => array(
357
+				'func'       => '_message_queue_list_table',
358
+				'capability' => 'ee_read_global_messages'
359
+			),
360
+			'global_mtps'                      => array(
361
+				'func'       => '_ee_default_messages_overview_list_table',
362
+				'capability' => 'ee_read_global_messages'
363
+			),
364
+			'custom_mtps'                      => array(
365
+				'func'       => '_custom_mtps_preview',
366
+				'capability' => 'ee_read_messages'
367
+			),
368
+			'add_new_message_template'         => array(
369
+				'func'       => '_add_message_template',
370
+				'capability' => 'ee_edit_messages',
371
+				'noheader'   => true
372
+			),
373
+			'edit_message_template'            => array(
374
+				'func'       => '_edit_message_template',
375
+				'capability' => 'ee_edit_message',
376
+				'obj_id'     => $grp_id
377
+			),
378
+			'preview_message'                  => array(
379
+				'func'               => '_preview_message',
380
+				'capability'         => 'ee_read_message',
381
+				'obj_id'             => $grp_id,
382
+				'noheader'           => true,
383
+				'headers_sent_route' => 'display_preview_message'
384
+			),
385
+			'display_preview_message'          => array(
386
+				'func'       => '_display_preview_message',
387
+				'capability' => 'ee_read_message',
388
+				'obj_id'     => $grp_id
389
+			),
390
+			'insert_message_template'          => array(
391
+				'func'       => '_insert_or_update_message_template',
392
+				'capability' => 'ee_edit_messages',
393
+				'args'       => array('new_template' => true),
394
+				'noheader'   => true
395
+			),
396
+			'update_message_template'          => array(
397
+				'func'       => '_insert_or_update_message_template',
398
+				'capability' => 'ee_edit_message',
399
+				'obj_id'     => $grp_id,
400
+				'args'       => array('new_template' => false),
401
+				'noheader'   => true
402
+			),
403
+			'trash_message_template'           => array(
404
+				'func'       => '_trash_or_restore_message_template',
405
+				'capability' => 'ee_delete_message',
406
+				'obj_id'     => $grp_id,
407
+				'args'       => array('trash' => true, 'all' => true),
408
+				'noheader'   => true
409
+			),
410
+			'trash_message_template_context'   => array(
411
+				'func'       => '_trash_or_restore_message_template',
412
+				'capability' => 'ee_delete_message',
413
+				'obj_id'     => $grp_id,
414
+				'args'       => array('trash' => true),
415
+				'noheader'   => true
416
+			),
417
+			'restore_message_template'         => array(
418
+				'func'       => '_trash_or_restore_message_template',
419
+				'capability' => 'ee_delete_message',
420
+				'obj_id'     => $grp_id,
421
+				'args'       => array('trash' => false, 'all' => true),
422
+				'noheader'   => true
423
+			),
424
+			'restore_message_template_context' => array(
425
+				'func'       => '_trash_or_restore_message_template',
426
+				'capability' => 'ee_delete_message',
427
+				'obj_id'     => $grp_id,
428
+				'args'       => array('trash' => false),
429
+				'noheader'   => true
430
+			),
431
+			'delete_message_template'          => array(
432
+				'func'       => '_delete_message_template',
433
+				'capability' => 'ee_delete_message',
434
+				'obj_id'     => $grp_id,
435
+				'noheader'   => true
436
+			),
437
+			'reset_to_default'                 => array(
438
+				'func'       => '_reset_to_default_template',
439
+				'capability' => 'ee_edit_message',
440
+				'obj_id'     => $grp_id,
441
+				'noheader'   => true
442
+			),
443
+			'settings'                         => array(
444
+				'func'       => '_settings',
445
+				'capability' => 'manage_options'
446
+			),
447
+			'update_global_settings'           => array(
448
+				'func'       => '_update_global_settings',
449
+				'capability' => 'manage_options',
450
+				'noheader'   => true
451
+			),
452
+			'generate_now'                     => array(
453
+				'func'       => '_generate_now',
454
+				'capability' => 'ee_send_message',
455
+				'noheader'   => true
456
+			),
457
+			'generate_and_send_now'            => array(
458
+				'func'       => '_generate_and_send_now',
459
+				'capability' => 'ee_send_message',
460
+				'noheader'   => true
461
+			),
462
+			'queue_for_resending'              => array(
463
+				'func'       => '_queue_for_resending',
464
+				'capability' => 'ee_send_message',
465
+				'noheader'   => true
466
+			),
467
+			'send_now'                         => array(
468
+				'func'       => '_send_now',
469
+				'capability' => 'ee_send_message',
470
+				'noheader'   => true
471
+			),
472
+			'delete_ee_message'                => array(
473
+				'func'       => '_delete_ee_messages',
474
+				'capability' => 'ee_delete_message',
475
+				'noheader'   => true
476
+			),
477
+			'delete_ee_messages'               => array(
478
+				'func'       => '_delete_ee_messages',
479
+				'capability' => 'ee_delete_messages',
480
+				'noheader'   => true,
481
+				'obj_id'     => $msg_id
482
+			)
483
+		);
484
+	}
485
+    
486
+    
487
+	protected function _set_page_config()
488
+	{
489
+		$this->_page_config = array(
490
+			'default'                  => array(
491
+				'nav'           => array(
492
+					'label' => __('Message Activity', 'event_espresso'),
493
+					'order' => 10
494
+				),
495
+				'list_table'    => 'EE_Message_List_Table',
496
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
+				'require_nonce' => false
498
+			),
499
+			'global_mtps'              => array(
500
+				'nav'           => array(
501
+					'label' => __('Default Message Templates', 'event_espresso'),
502
+					'order' => 20
503
+				),
504
+				'list_table'    => 'Messages_Template_List_Table',
505
+				'help_tabs'     => array(
506
+					'messages_overview_help_tab'                                => array(
507
+						'title'    => __('Messages Overview', 'event_espresso'),
508
+						'filename' => 'messages_overview'
509
+					),
510
+					'messages_overview_messages_table_column_headings_help_tab' => array(
511
+						'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
+						'filename' => 'messages_overview_table_column_headings'
513
+					),
514
+					'messages_overview_messages_filters_help_tab'               => array(
515
+						'title'    => __('Message Filters', 'event_espresso'),
516
+						'filename' => 'messages_overview_filters'
517
+					),
518
+					'messages_overview_messages_views_help_tab'                 => array(
519
+						'title'    => __('Message Views', 'event_espresso'),
520
+						'filename' => 'messages_overview_views'
521
+					),
522
+					'message_overview_message_types_help_tab'                   => array(
523
+						'title'    => __('Message Types', 'event_espresso'),
524
+						'filename' => 'messages_overview_types'
525
+					),
526
+					'messages_overview_messengers_help_tab'                     => array(
527
+						'title'    => __('Messengers', 'event_espresso'),
528
+						'filename' => 'messages_overview_messengers',
529
+					),
530
+					'messages_overview_other_help_tab'                          => array(
531
+						'title'    => __('Messages Other', 'event_espresso'),
532
+						'filename' => 'messages_overview_other',
533
+					),
534
+				),
535
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
536
+				'require_nonce' => false
537
+			),
538
+			'custom_mtps'              => array(
539
+				'nav'           => array(
540
+					'label' => __('Custom Message Templates', 'event_espresso'),
541
+					'order' => 30
542
+				),
543
+				'help_tabs'     => array(),
544
+				'help_tour'     => array(),
545
+				'require_nonce' => false
546
+			),
547
+			'add_new_message_template' => array(
548
+				'nav'           => array(
549
+					'label'      => __('Add New Message Templates', 'event_espresso'),
550
+					'order'      => 5,
551
+					'persistent' => false
552
+				),
553
+				'require_nonce' => false
554
+			),
555
+			'edit_message_template'    => array(
556
+				'labels'        => array(
557
+					'buttons'    => array(
558
+						'reset' => __('Reset Templates'),
559
+					),
560
+					'publishbox' => __('Update Actions', 'event_espresso')
561
+				),
562
+				'nav'           => array(
563
+					'label'      => __('Edit Message Templates', 'event_espresso'),
564
+					'order'      => 5,
565
+					'persistent' => false,
566
+					'url'        => ''
567
+				),
568
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
+				'has_metaboxes' => true,
570
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
+				'help_tabs'     => array(
572
+					'edit_message_template'       => array(
573
+						'title'    => __('Message Template Editor', 'event_espresso'),
574
+						'callback' => 'edit_message_template_help_tab'
575
+					),
576
+					'message_templates_help_tab'  => array(
577
+						'title'    => __('Message Templates', 'event_espresso'),
578
+						'filename' => 'messages_templates'
579
+					),
580
+					'message_template_shortcodes' => array(
581
+						'title'    => __('Message Shortcodes', 'event_espresso'),
582
+						'callback' => 'message_template_shortcodes_help_tab'
583
+					),
584
+					'message_preview_help_tab'    => array(
585
+						'title'    => __('Message Preview', 'event_espresso'),
586
+						'filename' => 'messages_preview'
587
+					),
588
+				),
589
+				'require_nonce' => false
590
+			),
591
+			'display_preview_message'  => array(
592
+				'nav'           => array(
593
+					'label'      => __('Message Preview', 'event_espresso'),
594
+					'order'      => 5,
595
+					'url'        => '',
596
+					'persistent' => false
597
+				),
598
+				'help_tabs'     => array(
599
+					'preview_message' => array(
600
+						'title'    => __('About Previews', 'event_espresso'),
601
+						'callback' => 'preview_message_help_tab'
602
+					)
603
+				),
604
+				'require_nonce' => false
605
+			),
606
+			'settings'                 => array(
607
+				'nav'           => array(
608
+					'label' => __('Settings', 'event_espresso'),
609
+					'order' => 40
610
+				),
611
+				'metaboxes'     => array('_messages_settings_metaboxes'),
612
+				'help_tabs'     => array(
613
+					'messages_settings_help_tab'               => array(
614
+						'title'    => __('Messages Settings', 'event_espresso'),
615
+						'filename' => 'messages_settings'
616
+					),
617
+					'messages_settings_message_types_help_tab' => array(
618
+						'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
+						'filename' => 'messages_settings_message_types'
620
+					),
621
+					'messages_settings_messengers_help_tab'    => array(
622
+						'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
+						'filename' => 'messages_settings_messengers'
624
+					),
625
+				),
626
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
627
+				'require_nonce' => false
628
+			)
629
+		);
630
+	}
631
+    
632
+    
633
+	protected function _add_screen_options()
634
+	{
635
+		//todo
636
+	}
637
+    
638
+    
639
+	protected function _add_screen_options_global_mtps()
640
+	{
641
+		/**
642
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
644
+		 */
645
+		$page_title              = $this->_admin_page_title;
646
+		$this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
+		$this->_per_page_screen_option();
648
+		$this->_admin_page_title = $page_title;
649
+	}
650
+    
651
+    
652
+	protected function _add_screen_options_default()
653
+	{
654
+		$this->_admin_page_title = __('Message Activity', 'event_espresso');
655
+		$this->_per_page_screen_option();
656
+	}
657
+    
658
+    
659
+	//none of the below group are currently used for Messages
660
+	protected function _add_feature_pointers()
661
+	{
662
+	}
663
+    
664
+	public function admin_init()
665
+	{
666
+	}
667
+    
668
+	public function admin_notices()
669
+	{
670
+	}
671
+    
672
+	public function admin_footer_scripts()
673
+	{
674
+	}
675
+    
676
+    
677
+	public function messages_help_tab()
678
+	{
679
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
+	}
681
+    
682
+    
683
+	public function messengers_help_tab()
684
+	{
685
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
+	}
687
+    
688
+    
689
+	public function message_types_help_tab()
690
+	{
691
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
+	}
693
+    
694
+    
695
+	public function messages_overview_help_tab()
696
+	{
697
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
+	}
699
+    
700
+    
701
+	public function message_templates_help_tab()
702
+	{
703
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
+	}
705
+    
706
+    
707
+	public function edit_message_template_help_tab()
708
+	{
709
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
+				'event_espresso') . '" />';
711
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
+				'event_espresso') . '" />';
713
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
+				'event_espresso') . '" />';
715
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
+				'event_espresso') . '" />';
717
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
+				'event_espresso') . '" />';
719
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
+			$args);
721
+	}
722
+    
723
+    
724
+	public function message_template_shortcodes_help_tab()
725
+	{
726
+		$this->_set_shortcodes();
727
+		$args['shortcodes'] = $this->_shortcodes;
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
+			$args);
730
+	}
731 731
     
732 732
     
733
-    public function preview_message_help_tab()
734
-    {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
-    }
733
+	public function preview_message_help_tab()
734
+	{
735
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
+	}
737 737
     
738
-    
739
-    public function settings_help_tab()
740
-    {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
745
-        $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
-        $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
-    }
738
+    
739
+	public function settings_help_tab()
740
+	{
741
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
+				'event_espresso') . '" />';
743
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
+				'event_espresso') . '" />';
745
+		$args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
+		$args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
+	}
749 749
     
750 750
     
751
-    public function load_scripts_styles()
752
-    {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
-        wp_enqueue_style('espresso_ee_msg');
751
+	public function load_scripts_styles()
752
+	{
753
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
+		wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
-            array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
-            array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
-    }
756
+		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
+			array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
+		wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
+			array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
+	}
761 761
     
762 762
     
763
-    public function load_scripts_styles_default()
764
-    {
765
-        wp_enqueue_script('ee-msg-list-table-js');
766
-    }
763
+	public function load_scripts_styles_default()
764
+	{
765
+		wp_enqueue_script('ee-msg-list-table-js');
766
+	}
767 767
     
768 768
     
769
-    public function wp_editor_css($mce_css)
770
-    {
771
-        //if we're on the edit_message_template route
772
-        if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
-            $message_type_name = $this->_active_message_type_name;
769
+	public function wp_editor_css($mce_css)
770
+	{
771
+		//if we're on the edit_message_template route
772
+		if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
+			$message_type_name = $this->_active_message_type_name;
774 774
             
775
-            //we're going to REPLACE the existing mce css
776
-            //we need to get the css file location from the active messenger
777
-            $mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
-                'wpeditor', $this->_variation);
779
-        }
775
+			//we're going to REPLACE the existing mce css
776
+			//we need to get the css file location from the active messenger
777
+			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
+				'wpeditor', $this->_variation);
779
+		}
780 780
         
781
-        return $mce_css;
782
-    }
783
-    
784
-    
785
-    public function load_scripts_styles_edit_message_template()
786
-    {
787
-        
788
-        $this->_set_shortcodes();
781
+		return $mce_css;
782
+	}
783
+    
784
+    
785
+	public function load_scripts_styles_edit_message_template()
786
+	{
787
+        
788
+		$this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
-            __('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
-                'event_espresso'),
793
-            $this->_message_template_group->messenger_obj()->label['singular'],
794
-            $this->_message_template_group->message_type_obj()->label['singular']
795
-        );
796
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
-            'event_espresso');
798
-        
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
-            EVENT_ESPRESSO_VERSION);
801
-        
802
-        wp_enqueue_script('ee_admin_js');
803
-        wp_enqueue_script('ee_msgs_edit_js');
804
-        
805
-        //add in special css for tiny_mce
806
-        add_filter('mce_css', array($this, 'wp_editor_css'));
807
-    }
808
-    
809
-    
810
-    public function load_scripts_styles_display_preview_message()
811
-    {
812
-        
813
-        $this->_set_message_template_group();
814
-        
815
-        if (isset($this->_req_data['messenger'])) {
816
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
-        }
818
-        
819
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
-        
821
-        
822
-        wp_enqueue_style('espresso_preview_css',
823
-            $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
-                $this->_variation));
825
-    }
826
-    
827
-    
828
-    public function load_scripts_styles_settings()
829
-    {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
-            EVENT_ESPRESSO_VERSION);
832
-        wp_enqueue_style('ee-text-links');
833
-        wp_enqueue_style('ee-message-settings');
834
-        
835
-        wp_enqueue_script('ee-messages-settings');
836
-    }
837
-    
838
-    
839
-    /**
840
-     * set views array for List Table
841
-     */
842
-    public function _set_list_table_views_global_mtps()
843
-    {
844
-        $this->_views = array(
845
-            'in_use' => array(
846
-                'slug'        => 'in_use',
847
-                'label'       => __('In Use', 'event_espresso'),
848
-                'count'       => 0,
849
-                'bulk_action' => array(
850
-                    'trash_message_template' => __('Move to Trash', 'event_espresso')
851
-                )
852
-            )
853
-        );
854
-    }
855
-    
856
-    
857
-    /**
858
-     * set views array for message queue list table
859
-     */
860
-    public function _set_list_table_views_default()
861
-    {
862
-        EE_Registry::instance()->load_helper('Template');
863
-        
864
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
-            'message_list_table_bulk_actions')
866
-            ? array(
867
-                'generate_now'          => __('Generate Now', 'event_espresso'),
868
-                'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
-                'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
-                'send_now'              => __('Send Now', 'event_espresso')
871
-            )
872
-            : array();
873
-        
874
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
-            'message_list_table_bulk_actions')
876
-            ? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
-            : array();
878
-        
879
-        
880
-        $this->_views = array(
881
-            'all' => array(
882
-                'slug'        => 'all',
883
-                'label'       => __('All', 'event_espresso'),
884
-                'count'       => 0,
885
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
-            )
887
-        );
888
-        
889
-        
890
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
891
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
-                continue;
893
-            }
894
-            $status_bulk_actions = $common_bulk_actions;
895
-            //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
897
-                switch ($status) {
898
-                    case EEM_Message::status_idle:
899
-                    case EEM_Message::status_resend:
900
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
-                        break;
790
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
+			__('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
+				'event_espresso'),
793
+			$this->_message_template_group->messenger_obj()->label['singular'],
794
+			$this->_message_template_group->message_type_obj()->label['singular']
795
+		);
796
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
+			'event_espresso');
798
+        
799
+		wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
+			EVENT_ESPRESSO_VERSION);
801
+        
802
+		wp_enqueue_script('ee_admin_js');
803
+		wp_enqueue_script('ee_msgs_edit_js');
804
+        
805
+		//add in special css for tiny_mce
806
+		add_filter('mce_css', array($this, 'wp_editor_css'));
807
+	}
808
+    
809
+    
810
+	public function load_scripts_styles_display_preview_message()
811
+	{
812
+        
813
+		$this->_set_message_template_group();
814
+        
815
+		if (isset($this->_req_data['messenger'])) {
816
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
+		}
818
+        
819
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
+        
821
+        
822
+		wp_enqueue_style('espresso_preview_css',
823
+			$this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
+				$this->_variation));
825
+	}
826
+    
827
+    
828
+	public function load_scripts_styles_settings()
829
+	{
830
+		wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
+			EVENT_ESPRESSO_VERSION);
832
+		wp_enqueue_style('ee-text-links');
833
+		wp_enqueue_style('ee-message-settings');
834
+        
835
+		wp_enqueue_script('ee-messages-settings');
836
+	}
837
+    
838
+    
839
+	/**
840
+	 * set views array for List Table
841
+	 */
842
+	public function _set_list_table_views_global_mtps()
843
+	{
844
+		$this->_views = array(
845
+			'in_use' => array(
846
+				'slug'        => 'in_use',
847
+				'label'       => __('In Use', 'event_espresso'),
848
+				'count'       => 0,
849
+				'bulk_action' => array(
850
+					'trash_message_template' => __('Move to Trash', 'event_espresso')
851
+				)
852
+			)
853
+		);
854
+	}
855
+    
856
+    
857
+	/**
858
+	 * set views array for message queue list table
859
+	 */
860
+	public function _set_list_table_views_default()
861
+	{
862
+		EE_Registry::instance()->load_helper('Template');
863
+        
864
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
+			'message_list_table_bulk_actions')
866
+			? array(
867
+				'generate_now'          => __('Generate Now', 'event_espresso'),
868
+				'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
+				'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
+				'send_now'              => __('Send Now', 'event_espresso')
871
+			)
872
+			: array();
873
+        
874
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
+			'message_list_table_bulk_actions')
876
+			? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
+			: array();
878
+        
879
+        
880
+		$this->_views = array(
881
+			'all' => array(
882
+				'slug'        => 'all',
883
+				'label'       => __('All', 'event_espresso'),
884
+				'count'       => 0,
885
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
+			)
887
+		);
888
+        
889
+        
890
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
891
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
+				continue;
893
+			}
894
+			$status_bulk_actions = $common_bulk_actions;
895
+			//unset bulk actions not applying to status
896
+			if (! empty($status_bulk_actions)) {
897
+				switch ($status) {
898
+					case EEM_Message::status_idle:
899
+					case EEM_Message::status_resend:
900
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
+						break;
902 902
                     
903
-                    case EEM_Message::status_failed:
904
-                    case EEM_Message::status_debug_only:
905
-                    case EEM_Message::status_messenger_executing:
906
-                        $status_bulk_actions = array();
907
-                        break;
903
+					case EEM_Message::status_failed:
904
+					case EEM_Message::status_debug_only:
905
+					case EEM_Message::status_messenger_executing:
906
+						$status_bulk_actions = array();
907
+						break;
908 908
                     
909
-                    case EEM_Message::status_incomplete:
910
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
-                        break;
909
+					case EEM_Message::status_incomplete:
910
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
+						break;
912 912
                     
913
-                    case EEM_Message::status_retry:
914
-                    case EEM_Message::status_sent:
915
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
-                        break;
917
-                }
918
-            }
913
+					case EEM_Message::status_retry:
914
+					case EEM_Message::status_sent:
915
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
+						break;
917
+				}
918
+			}
919 919
 
920
-            //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
922
-                continue;
923
-            }
920
+			//skip adding messenger executing status to views because it will be included with the Failed view.
921
+			if ( $status === EEM_Message::status_messenger_executing ) {
922
+				continue;
923
+			}
924 924
             
925
-            $this->_views[strtolower($status)] = array(
926
-                'slug'        => strtolower($status),
927
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
-                'count'       => 0,
929
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
-            );
931
-        }
932
-    }
933
-    
934
-    
935
-    protected function _ee_default_messages_overview_list_table()
936
-    {
937
-        $this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
-        $this->display_admin_list_table_page_with_no_sidebar();
939
-    }
940
-    
941
-    
942
-    protected function _message_queue_list_table()
943
-    {
944
-        $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
-        $this->_template_args['per_column']        = 6;
946
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
-        $this->display_admin_list_table_page_with_no_sidebar();
949
-    }
950
-    
951
-    
952
-    protected function _message_legend_items()
953
-    {
954
-        
955
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
-        $action_items       = array();
957
-        
958
-        foreach ($action_css_classes as $action_item => $action_details) {
959
-            if ($action_item === 'see_notifications_for') {
960
-                continue;
961
-            }
962
-            $action_items[$action_item] = array(
963
-                'class' => $action_details['css_class'],
964
-                'desc'  => $action_details['label']
965
-            );
966
-        }
967
-        
968
-        /** @type array $status_items status legend setup */
969
-        $status_items = array(
970
-            'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
-            ),
974
-            'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
-            ),
978
-            'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
-            ),
982
-            'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
-                'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
-            ),
986
-            'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
-            ),
990
-            'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
-            ),
994
-            'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
-            )
998
-        );
999
-        if (EEM_Message::debug()) {
1000
-            $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
-            );
1004
-        }
1005
-        
1006
-        return array_merge($action_items, $status_items);
1007
-    }
1008
-    
1009
-    
1010
-    protected function _custom_mtps_preview()
1011
-    {
1012
-        $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
-                'event_espresso') . '</strong>';
1017
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1018
-    }
1019
-    
1020
-    
1021
-    /**
1022
-     * get_message_templates
1023
-     * This gets all the message templates for listing on the overview list.
1024
-     *
1025
-     * @access public
1026
-     *
1027
-     * @param int    $perpage the amount of templates groups to show per page
1028
-     * @param string $type    the current _view we're getting templates for
1029
-     * @param bool   $count   return count?
1030
-     * @param bool   $all     disregard any paging info (get all data);
1031
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
-     *
1033
-     * @return array
1034
-     */
1035
-    public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
-    {
1037
-        
1038
-        $MTP = EEM_Message_Template_Group::instance();
1039
-        
1040
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
-        $orderby                    = $this->_req_data['orderby'];
1042
-        
1043
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
-        
1045
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
-        
1048
-        $offset = ($current_page - 1) * $per_page;
1049
-        $limit  = $all ? null : array($offset, $per_page);
1050
-        
1051
-        
1052
-        //options will match what is in the _views array property
1053
-        switch ($type) {
925
+			$this->_views[strtolower($status)] = array(
926
+				'slug'        => strtolower($status),
927
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
+				'count'       => 0,
929
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
+			);
931
+		}
932
+	}
933
+    
934
+    
935
+	protected function _ee_default_messages_overview_list_table()
936
+	{
937
+		$this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
+		$this->display_admin_list_table_page_with_no_sidebar();
939
+	}
940
+    
941
+    
942
+	protected function _message_queue_list_table()
943
+	{
944
+		$this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
+		$this->_template_args['per_column']        = 6;
946
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
+		$this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
+		$this->display_admin_list_table_page_with_no_sidebar();
949
+	}
950
+    
951
+    
952
+	protected function _message_legend_items()
953
+	{
954
+        
955
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
+		$action_items       = array();
957
+        
958
+		foreach ($action_css_classes as $action_item => $action_details) {
959
+			if ($action_item === 'see_notifications_for') {
960
+				continue;
961
+			}
962
+			$action_items[$action_item] = array(
963
+				'class' => $action_details['css_class'],
964
+				'desc'  => $action_details['label']
965
+			);
966
+		}
967
+        
968
+		/** @type array $status_items status legend setup */
969
+		$status_items = array(
970
+			'sent_status'       => array(
971
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
+			),
974
+			'idle_status'       => array(
975
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
+			),
978
+			'failed_status'     => array(
979
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
+			),
982
+			'messenger_executing_status' => array(
983
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
+				'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
+			),
986
+			'resend_status'     => array(
987
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
+			),
990
+			'incomplete_status' => array(
991
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
+			),
994
+			'retry_status'      => array(
995
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
+			)
998
+		);
999
+		if (EEM_Message::debug()) {
1000
+			$status_items['debug_only_status'] = array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
+			);
1004
+		}
1005
+        
1006
+		return array_merge($action_items, $status_items);
1007
+	}
1008
+    
1009
+    
1010
+	protected function _custom_mtps_preview()
1011
+	{
1012
+		$this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
+				'event_espresso') . '" />';
1015
+		$this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
+				'event_espresso') . '</strong>';
1017
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1018
+	}
1019
+    
1020
+    
1021
+	/**
1022
+	 * get_message_templates
1023
+	 * This gets all the message templates for listing on the overview list.
1024
+	 *
1025
+	 * @access public
1026
+	 *
1027
+	 * @param int    $perpage the amount of templates groups to show per page
1028
+	 * @param string $type    the current _view we're getting templates for
1029
+	 * @param bool   $count   return count?
1030
+	 * @param bool   $all     disregard any paging info (get all data);
1031
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
+	 *
1033
+	 * @return array
1034
+	 */
1035
+	public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
+	{
1037
+        
1038
+		$MTP = EEM_Message_Template_Group::instance();
1039
+        
1040
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
+		$orderby                    = $this->_req_data['orderby'];
1042
+        
1043
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
+        
1045
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
+        
1048
+		$offset = ($current_page - 1) * $per_page;
1049
+		$limit  = $all ? null : array($offset, $per_page);
1050
+        
1051
+        
1052
+		//options will match what is in the _views array property
1053
+		switch ($type) {
1054 1054
             
1055
-            case 'in_use':
1056
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
-                break;
1055
+			case 'in_use':
1056
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
+				break;
1058 1058
             
1059
-            default:
1060
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1059
+			default:
1060
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1061 1061
             
1062
-        }
1063
-        
1064
-        return $templates;
1065
-    }
1066
-    
1067
-    
1068
-    /**
1069
-     * filters etc might need a list of installed message_types
1070
-     * @return array an array of message type objects
1071
-     */
1072
-    public function get_installed_message_types()
1073
-    {
1074
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
-        $installed               = array();
1076
-        
1077
-        foreach ($installed_message_types as $message_type) {
1078
-            $installed[$message_type->name] = $message_type;
1079
-        }
1080
-        
1081
-        return $installed;
1082
-    }
1083
-    
1084
-    
1085
-    /**
1086
-     * _add_message_template
1087
-     *
1088
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1089
-     *
1090
-     * @param string $message_type
1091
-     * @param string $messenger
1092
-     * @param string $GRP_ID
1093
-     *
1094
-     * @throws EE_error
1095
-     */
1096
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
-    {
1098
-        //set values override any request data
1099
-        $message_type = ! empty($message_type) ? $message_type : '';
1100
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
-        
1102
-        $messenger = ! empty($messenger) ? $messenger : '';
1103
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
-        
1105
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
-        
1108
-        //we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
-        if (empty($message_type) || empty($messenger)) {
1110
-            throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
-                'event_espresso'));
1112
-        }
1113
-        
1114
-        //we need the GRP_ID for the template being used as the base for the new template
1115
-        if (empty($GRP_ID)) {
1116
-            throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
-                'event_espresso'));
1118
-        }
1119
-        
1120
-        //let's just make sure the template gets generated!
1121
-        
1122
-        //we need to reassign some variables for what the insert is expecting
1123
-        $this->_req_data['MTP_messenger']    = $messenger;
1124
-        $this->_req_data['MTP_message_type'] = $message_type;
1125
-        $this->_req_data['GRP_ID']           = $GRP_ID;
1126
-        $this->_insert_or_update_message_template(true);
1127
-    }
1128
-    
1129
-    
1130
-    /**
1131
-     * public wrapper for the _add_message_template method
1132
-     *
1133
-     * @param string $message_type     message type slug
1134
-     * @param string $messenger        messenger slug
1135
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
-     *                                 off of.
1137
-     */
1138
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1139
-    {
1140
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
-    }
1142
-    
1143
-    
1144
-    /**
1145
-     * _edit_message_template
1146
-     *
1147
-     * @access protected
1148
-     * @return void
1149
-     */
1150
-    protected function _edit_message_template()
1151
-    {
1152
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
-        $template_fields = '';
1154
-        $sidebar_fields  = '';
1155
-        //we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
-        
1158
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
-            ? absint($this->_req_data['id'])
1160
-            : false;
1161
-        
1162
-        $this->_set_shortcodes(); //this also sets the _message_template property.
1163
-        $message_template_group = $this->_message_template_group;
1164
-        $c_label                = $message_template_group->context_label();
1165
-        $c_config               = $message_template_group->contexts_config();
1166
-        
1167
-        reset($c_config);
1168
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
-            ? strtolower($this->_req_data['context'])
1170
-            : key($c_config);
1171
-        
1172
-        
1173
-        if (empty($GRP_ID)) {
1174
-            $action = 'insert_message_template';
1175
-            //$button_both = false;
1176
-            //$button_text = array( __( 'Save','event_espresso') );
1177
-            //$button_actions = array('something_different');
1178
-            //$referrer = false;
1179
-            $edit_message_template_form_url = add_query_arg(
1180
-                array('action' => $action, 'noheader' => true),
1181
-                EE_MSG_ADMIN_URL
1182
-            );
1183
-        } else {
1184
-            $action = 'update_message_template';
1185
-            //$button_both = true;
1186
-            //$button_text = array();
1187
-            //$button_actions = array();
1188
-            //$referrer = $this->_admin_base_url;
1189
-            $edit_message_template_form_url = add_query_arg(
1190
-                array('action' => $action, 'noheader' => true),
1191
-                EE_MSG_ADMIN_URL
1192
-            );
1193
-        }
1194
-        
1195
-        //set active messenger for this view
1196
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
-            $message_template_group->messenger()
1198
-        );
1199
-        $this->_active_message_type_name = $message_template_group->message_type();
1200
-        
1201
-        
1202
-        //Do we have any validation errors?
1203
-        $validators = $this->_get_transient();
1204
-        $v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
-        
1206
-        
1207
-        //we need to assemble the title from Various details
1208
-        $context_label = sprintf(
1209
-            __('(%s %s)', 'event_espresso'),
1210
-            $c_config[$context]['label'],
1211
-            ucwords($c_label['label'])
1212
-        );
1213
-        
1214
-        $title = sprintf(
1215
-            __(' %s %s Template %s', 'event_espresso'),
1216
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1217
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1218
-            $context_label
1219
-        );
1220
-        
1221
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1222
-        $this->_template_args['message_template'] = $message_template_group;
1223
-        $this->_template_args['is_extra_fields']  = false;
1224
-        
1225
-        
1226
-        //let's get EEH_MSG_Template so we can get template form fields
1227
-        $template_field_structure = EEH_MSG_Template::get_fields(
1228
-            $message_template_group->messenger(),
1229
-            $message_template_group->message_type()
1230
-        );
1231
-        
1232
-        if ( ! $template_field_structure) {
1233
-            $template_field_structure = false;
1234
-            $template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
-                'event_espresso');
1236
-        }
1237
-        
1238
-        
1239
-        $message_templates = $message_template_group->context_templates();
1240
-        
1241
-        
1242
-        //if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
-        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
-            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
-                unset($template_field_structure[$context][$reference_field]);
1246
-            }
1247
-        }
1248
-        
1249
-        //let's loop through the template_field_structure and actually assemble the input fields!
1250
-        if ( ! empty($template_field_structure)) {
1251
-            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
-                //if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
-                if ($template_field == 'extra') {
1254
-                    $this->_template_args['is_extra_fields'] = true;
1255
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
-                        $message_template = $message_templates[$context][$reference_field];
1257
-                        $content          = $message_template instanceof EE_Message_Template
1258
-                            ? $message_template->get('MTP_content')
1259
-                            : '';
1260
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1261
-                            //let's verify if we need this extra field via the shortcodes parameter.
1262
-                            $continue = false;
1263
-                            if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
-                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
-                                        $continue = true;
1267
-                                    }
1268
-                                }
1269
-                                if ($continue) {
1270
-                                    continue;
1271
-                                }
1272
-                            }
1062
+		}
1063
+        
1064
+		return $templates;
1065
+	}
1066
+    
1067
+    
1068
+	/**
1069
+	 * filters etc might need a list of installed message_types
1070
+	 * @return array an array of message type objects
1071
+	 */
1072
+	public function get_installed_message_types()
1073
+	{
1074
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
+		$installed               = array();
1076
+        
1077
+		foreach ($installed_message_types as $message_type) {
1078
+			$installed[$message_type->name] = $message_type;
1079
+		}
1080
+        
1081
+		return $installed;
1082
+	}
1083
+    
1084
+    
1085
+	/**
1086
+	 * _add_message_template
1087
+	 *
1088
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1089
+	 *
1090
+	 * @param string $message_type
1091
+	 * @param string $messenger
1092
+	 * @param string $GRP_ID
1093
+	 *
1094
+	 * @throws EE_error
1095
+	 */
1096
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
+	{
1098
+		//set values override any request data
1099
+		$message_type = ! empty($message_type) ? $message_type : '';
1100
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
+        
1102
+		$messenger = ! empty($messenger) ? $messenger : '';
1103
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
+        
1105
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
+        
1108
+		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
+		if (empty($message_type) || empty($messenger)) {
1110
+			throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
+				'event_espresso'));
1112
+		}
1113
+        
1114
+		//we need the GRP_ID for the template being used as the base for the new template
1115
+		if (empty($GRP_ID)) {
1116
+			throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
+				'event_espresso'));
1118
+		}
1119
+        
1120
+		//let's just make sure the template gets generated!
1121
+        
1122
+		//we need to reassign some variables for what the insert is expecting
1123
+		$this->_req_data['MTP_messenger']    = $messenger;
1124
+		$this->_req_data['MTP_message_type'] = $message_type;
1125
+		$this->_req_data['GRP_ID']           = $GRP_ID;
1126
+		$this->_insert_or_update_message_template(true);
1127
+	}
1128
+    
1129
+    
1130
+	/**
1131
+	 * public wrapper for the _add_message_template method
1132
+	 *
1133
+	 * @param string $message_type     message type slug
1134
+	 * @param string $messenger        messenger slug
1135
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
+	 *                                 off of.
1137
+	 */
1138
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1139
+	{
1140
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
+	}
1142
+    
1143
+    
1144
+	/**
1145
+	 * _edit_message_template
1146
+	 *
1147
+	 * @access protected
1148
+	 * @return void
1149
+	 */
1150
+	protected function _edit_message_template()
1151
+	{
1152
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
+		$template_fields = '';
1154
+		$sidebar_fields  = '';
1155
+		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
+        
1158
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
+			? absint($this->_req_data['id'])
1160
+			: false;
1161
+        
1162
+		$this->_set_shortcodes(); //this also sets the _message_template property.
1163
+		$message_template_group = $this->_message_template_group;
1164
+		$c_label                = $message_template_group->context_label();
1165
+		$c_config               = $message_template_group->contexts_config();
1166
+        
1167
+		reset($c_config);
1168
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
+			? strtolower($this->_req_data['context'])
1170
+			: key($c_config);
1171
+        
1172
+        
1173
+		if (empty($GRP_ID)) {
1174
+			$action = 'insert_message_template';
1175
+			//$button_both = false;
1176
+			//$button_text = array( __( 'Save','event_espresso') );
1177
+			//$button_actions = array('something_different');
1178
+			//$referrer = false;
1179
+			$edit_message_template_form_url = add_query_arg(
1180
+				array('action' => $action, 'noheader' => true),
1181
+				EE_MSG_ADMIN_URL
1182
+			);
1183
+		} else {
1184
+			$action = 'update_message_template';
1185
+			//$button_both = true;
1186
+			//$button_text = array();
1187
+			//$button_actions = array();
1188
+			//$referrer = $this->_admin_base_url;
1189
+			$edit_message_template_form_url = add_query_arg(
1190
+				array('action' => $action, 'noheader' => true),
1191
+				EE_MSG_ADMIN_URL
1192
+			);
1193
+		}
1194
+        
1195
+		//set active messenger for this view
1196
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
+			$message_template_group->messenger()
1198
+		);
1199
+		$this->_active_message_type_name = $message_template_group->message_type();
1200
+        
1201
+        
1202
+		//Do we have any validation errors?
1203
+		$validators = $this->_get_transient();
1204
+		$v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
+        
1206
+        
1207
+		//we need to assemble the title from Various details
1208
+		$context_label = sprintf(
1209
+			__('(%s %s)', 'event_espresso'),
1210
+			$c_config[$context]['label'],
1211
+			ucwords($c_label['label'])
1212
+		);
1213
+        
1214
+		$title = sprintf(
1215
+			__(' %s %s Template %s', 'event_espresso'),
1216
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1217
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1218
+			$context_label
1219
+		);
1220
+        
1221
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1222
+		$this->_template_args['message_template'] = $message_template_group;
1223
+		$this->_template_args['is_extra_fields']  = false;
1224
+        
1225
+        
1226
+		//let's get EEH_MSG_Template so we can get template form fields
1227
+		$template_field_structure = EEH_MSG_Template::get_fields(
1228
+			$message_template_group->messenger(),
1229
+			$message_template_group->message_type()
1230
+		);
1231
+        
1232
+		if ( ! $template_field_structure) {
1233
+			$template_field_structure = false;
1234
+			$template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
+				'event_espresso');
1236
+		}
1237
+        
1238
+        
1239
+		$message_templates = $message_template_group->context_templates();
1240
+        
1241
+        
1242
+		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
+		if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
+			foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
+				unset($template_field_structure[$context][$reference_field]);
1246
+			}
1247
+		}
1248
+        
1249
+		//let's loop through the template_field_structure and actually assemble the input fields!
1250
+		if ( ! empty($template_field_structure)) {
1251
+			foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
+				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
+				if ($template_field == 'extra') {
1254
+					$this->_template_args['is_extra_fields'] = true;
1255
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
+						$message_template = $message_templates[$context][$reference_field];
1257
+						$content          = $message_template instanceof EE_Message_Template
1258
+							? $message_template->get('MTP_content')
1259
+							: '';
1260
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1261
+							//let's verify if we need this extra field via the shortcodes parameter.
1262
+							$continue = false;
1263
+							if (isset($extra_array['shortcodes_required'])) {
1264
+								foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
+									if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
+										$continue = true;
1267
+									}
1268
+								}
1269
+								if ($continue) {
1270
+									continue;
1271
+								}
1272
+							}
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
-                            $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
-                            $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1274
+							$field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
+							$template_form_fields[$field_id]         = $extra_array;
1276
+							$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
+							$css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279
-                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
-                                                                            && in_array($extra_field, $v_fields)
1281
-                                                                            &&
1282
-                                                                            (
1283
-                                                                                is_array($validators[$extra_field])
1284
-                                                                                && isset($validators[$extra_field]['msg'])
1285
-                                                                            )
1286
-                                ? 'validate-error ' . $css_class
1287
-                                : $css_class;
1279
+							$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
+																			&& in_array($extra_field, $v_fields)
1281
+																			&&
1282
+																			(
1283
+																				is_array($validators[$extra_field])
1284
+																				&& isset($validators[$extra_field]['msg'])
1285
+																			)
1286
+								? 'validate-error ' . $css_class
1287
+								: $css_class;
1288 1288
                             
1289
-                            $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
-                                ? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
-                                : '';
1289
+							$template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
+								? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
+								: '';
1292 1292
                             
1293
-                            //do we have a validation error?  if we do then let's use that value instead
1294
-                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1293
+							//do we have a validation error?  if we do then let's use that value instead
1294
+							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1295 1295
                             
1296 1296
                             
1297
-                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1297
+							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1298 1298
                             
1299
-                            //shortcode selector
1300
-                            $field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
-                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
-                                $field_name_to_use,
1303
-                                $field_id
1304
-                            );
1299
+							//shortcode selector
1300
+							$field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
+							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
+								$field_name_to_use,
1303
+								$field_id
1304
+							);
1305 1305
                             
1306
-                            if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
-                                //we want to decode the entities
1308
-                                $template_form_fields[$field_id]['value'] = stripslashes(
1309
-                                    html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
-                                );
1306
+							if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
+								//we want to decode the entities
1308
+								$template_form_fields[$field_id]['value'] = stripslashes(
1309
+									html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
+								);
1311 1311
                                 
1312
-                            }/**/
1313
-                        }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1312
+							}/**/
1313
+						}
1314
+						$templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
+						$templatefield_templatename_id = $reference_field . '-name';
1316 1316
                         
1317
-                        $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
-                            'label'      => null,
1320
-                            'input'      => 'hidden',
1321
-                            'type'       => 'int',
1322
-                            'required'   => false,
1323
-                            'validation' => false,
1324
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
-                            'css_class'  => '',
1326
-                            'format'     => '%d',
1327
-                            'db-col'     => 'MTP_ID'
1328
-                        );
1317
+						$template_form_fields[$templatefield_MTP_id] = array(
1318
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
+							'label'      => null,
1320
+							'input'      => 'hidden',
1321
+							'type'       => 'int',
1322
+							'required'   => false,
1323
+							'validation' => false,
1324
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
+							'css_class'  => '',
1326
+							'format'     => '%d',
1327
+							'db-col'     => 'MTP_ID'
1328
+						);
1329 1329
                         
1330
-                        $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
-                            'label'      => null,
1333
-                            'input'      => 'hidden',
1334
-                            'type'       => 'string',
1335
-                            'required'   => false,
1336
-                            'validation' => true,
1337
-                            'value'      => $reference_field,
1338
-                            'css_class'  => '',
1339
-                            'format'     => '%s',
1340
-                            'db-col'     => 'MTP_template_field'
1341
-                        );
1342
-                    }
1343
-                    continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
-                } else {
1345
-                    $field_id                                 = $template_field . '-content';
1346
-                    $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
-                    $message_template                         = isset($message_templates[$context][$template_field])
1349
-                        ? $message_templates[$context][$template_field]
1350
-                        : null;
1351
-                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
-                                                                && is_array($message_templates[$context])
1353
-                                                                && $message_template instanceof EE_Message_Template
1354
-                        ? $message_template->get('MTP_content')
1355
-                        : '';
1330
+						$template_form_fields[$templatefield_templatename_id] = array(
1331
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
+							'label'      => null,
1333
+							'input'      => 'hidden',
1334
+							'type'       => 'string',
1335
+							'required'   => false,
1336
+							'validation' => true,
1337
+							'value'      => $reference_field,
1338
+							'css_class'  => '',
1339
+							'format'     => '%s',
1340
+							'db-col'     => 'MTP_template_field'
1341
+						);
1342
+					}
1343
+					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
+				} else {
1345
+					$field_id                                 = $template_field . '-content';
1346
+					$template_form_fields[$field_id]          = $field_setup_array;
1347
+					$template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
+					$message_template                         = isset($message_templates[$context][$template_field])
1349
+						? $message_templates[$context][$template_field]
1350
+						: null;
1351
+					$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
+																&& is_array($message_templates[$context])
1353
+																&& $message_template instanceof EE_Message_Template
1354
+						? $message_template->get('MTP_content')
1355
+						: '';
1356 1356
                     
1357
-                    //do we have a validator error for this field?  if we do then we'll use that value instead
1358
-                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
-                        ? $validators[$template_field]['value']
1360
-                        : $template_form_fields[$field_id]['value'];
1357
+					//do we have a validator error for this field?  if we do then we'll use that value instead
1358
+					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
+						? $validators[$template_field]['value']
1360
+						: $template_form_fields[$field_id]['value'];
1361 1361
                     
1362 1362
                     
1363
-                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
-                    $css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
-                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
-                                                                    && in_array($template_field, $v_fields)
1367
-                                                                    && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1369
-                        : $css_class;
1363
+					$template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
+					$css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
+					$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
+																	&& in_array($template_field, $v_fields)
1367
+																	&& isset($validators[$template_field]['msg'])
1368
+						? 'validate-error ' . $css_class
1369
+						: $css_class;
1370 1370
                     
1371
-                    //shortcode selector
1372
-                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
-                        $template_field, $field_id
1374
-                    );
1375
-                }
1371
+					//shortcode selector
1372
+					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
+						$template_field, $field_id
1374
+					);
1375
+				}
1376 1376
                 
1377
-                //k took care of content field(s) now let's take care of others.
1377
+				//k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+				$templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
+				$templatefield_field_templatename_id = $template_field . '-name';
1381 1381
                 
1382
-                //foreach template field there are actually two form fields created
1383
-                $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
-                    'label'      => null,
1386
-                    'input'      => 'hidden',
1387
-                    'type'       => 'int',
1388
-                    'required'   => false,
1389
-                    'validation' => true,
1390
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
-                    'css_class'  => '',
1392
-                    'format'     => '%d',
1393
-                    'db-col'     => 'MTP_ID'
1394
-                );
1382
+				//foreach template field there are actually two form fields created
1383
+				$template_form_fields[$templatefield_MTP_id] = array(
1384
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
+					'label'      => null,
1386
+					'input'      => 'hidden',
1387
+					'type'       => 'int',
1388
+					'required'   => false,
1389
+					'validation' => true,
1390
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
+					'css_class'  => '',
1392
+					'format'     => '%d',
1393
+					'db-col'     => 'MTP_ID'
1394
+				);
1395 1395
                 
1396
-                $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
-                    'label'      => null,
1399
-                    'input'      => 'hidden',
1400
-                    'type'       => 'string',
1401
-                    'required'   => false,
1402
-                    'validation' => true,
1403
-                    'value'      => $template_field,
1404
-                    'css_class'  => '',
1405
-                    'format'     => '%s',
1406
-                    'db-col'     => 'MTP_template_field'
1407
-                );
1396
+				$template_form_fields[$templatefield_field_templatename_id] = array(
1397
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
+					'label'      => null,
1399
+					'input'      => 'hidden',
1400
+					'type'       => 'string',
1401
+					'required'   => false,
1402
+					'validation' => true,
1403
+					'value'      => $template_field,
1404
+					'css_class'  => '',
1405
+					'format'     => '%s',
1406
+					'db-col'     => 'MTP_template_field'
1407
+				);
1408 1408
                 
1409
-            }
1409
+			}
1410 1410
             
1411
-            //add other fields
1412
-            $template_form_fields['ee-msg-current-context'] = array(
1413
-                'name'       => 'MTP_context',
1414
-                'label'      => null,
1415
-                'input'      => 'hidden',
1416
-                'type'       => 'string',
1417
-                'required'   => false,
1418
-                'validation' => true,
1419
-                'value'      => $context,
1420
-                'css_class'  => '',
1421
-                'format'     => '%s',
1422
-                'db-col'     => 'MTP_context'
1423
-            );
1411
+			//add other fields
1412
+			$template_form_fields['ee-msg-current-context'] = array(
1413
+				'name'       => 'MTP_context',
1414
+				'label'      => null,
1415
+				'input'      => 'hidden',
1416
+				'type'       => 'string',
1417
+				'required'   => false,
1418
+				'validation' => true,
1419
+				'value'      => $context,
1420
+				'css_class'  => '',
1421
+				'format'     => '%s',
1422
+				'db-col'     => 'MTP_context'
1423
+			);
1424 1424
             
1425
-            $template_form_fields['ee-msg-grp-id'] = array(
1426
-                'name'       => 'GRP_ID',
1427
-                'label'      => null,
1428
-                'input'      => 'hidden',
1429
-                'type'       => 'int',
1430
-                'required'   => false,
1431
-                'validation' => true,
1432
-                'value'      => $GRP_ID,
1433
-                'css_class'  => '',
1434
-                'format'     => '%d',
1435
-                'db-col'     => 'GRP_ID'
1436
-            );
1425
+			$template_form_fields['ee-msg-grp-id'] = array(
1426
+				'name'       => 'GRP_ID',
1427
+				'label'      => null,
1428
+				'input'      => 'hidden',
1429
+				'type'       => 'int',
1430
+				'required'   => false,
1431
+				'validation' => true,
1432
+				'value'      => $GRP_ID,
1433
+				'css_class'  => '',
1434
+				'format'     => '%d',
1435
+				'db-col'     => 'GRP_ID'
1436
+			);
1437 1437
             
1438
-            $template_form_fields['ee-msg-messenger'] = array(
1439
-                'name'       => 'MTP_messenger',
1440
-                'label'      => null,
1441
-                'input'      => 'hidden',
1442
-                'type'       => 'string',
1443
-                'required'   => false,
1444
-                'validation' => true,
1445
-                'value'      => $message_template_group->messenger(),
1446
-                'css_class'  => '',
1447
-                'format'     => '%s',
1448
-                'db-col'     => 'MTP_messenger'
1449
-            );
1438
+			$template_form_fields['ee-msg-messenger'] = array(
1439
+				'name'       => 'MTP_messenger',
1440
+				'label'      => null,
1441
+				'input'      => 'hidden',
1442
+				'type'       => 'string',
1443
+				'required'   => false,
1444
+				'validation' => true,
1445
+				'value'      => $message_template_group->messenger(),
1446
+				'css_class'  => '',
1447
+				'format'     => '%s',
1448
+				'db-col'     => 'MTP_messenger'
1449
+			);
1450 1450
             
1451
-            $template_form_fields['ee-msg-message-type'] = array(
1452
-                'name'       => 'MTP_message_type',
1453
-                'label'      => null,
1454
-                'input'      => 'hidden',
1455
-                'type'       => 'string',
1456
-                'required'   => false,
1457
-                'validation' => true,
1458
-                'value'      => $message_template_group->message_type(),
1459
-                'css_class'  => '',
1460
-                'format'     => '%s',
1461
-                'db-col'     => 'MTP_message_type'
1462
-            );
1451
+			$template_form_fields['ee-msg-message-type'] = array(
1452
+				'name'       => 'MTP_message_type',
1453
+				'label'      => null,
1454
+				'input'      => 'hidden',
1455
+				'type'       => 'string',
1456
+				'required'   => false,
1457
+				'validation' => true,
1458
+				'value'      => $message_template_group->message_type(),
1459
+				'css_class'  => '',
1460
+				'format'     => '%s',
1461
+				'db-col'     => 'MTP_message_type'
1462
+			);
1463 1463
             
1464
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1465
-                'name'       => 'MTP_is_global',
1466
-                'label'      => __('Global Template', 'event_espresso'),
1467
-                'input'      => 'hidden',
1468
-                'type'       => 'int',
1469
-                'required'   => false,
1470
-                'validation' => true,
1471
-                'value'      => $message_template_group->get('MTP_is_global'),
1472
-                'css_class'  => '',
1473
-                'format'     => '%d',
1474
-                'db-col'     => 'MTP_is_global'
1475
-            );
1464
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1465
+				'name'       => 'MTP_is_global',
1466
+				'label'      => __('Global Template', 'event_espresso'),
1467
+				'input'      => 'hidden',
1468
+				'type'       => 'int',
1469
+				'required'   => false,
1470
+				'validation' => true,
1471
+				'value'      => $message_template_group->get('MTP_is_global'),
1472
+				'css_class'  => '',
1473
+				'format'     => '%d',
1474
+				'db-col'     => 'MTP_is_global'
1475
+			);
1476 1476
             
1477
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1478
-                'name'       => 'MTP_is_override',
1479
-                'label'      => __('Override all custom', 'event_espresso'),
1480
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
-                'type'       => 'int',
1482
-                'required'   => false,
1483
-                'validation' => true,
1484
-                'value'      => $message_template_group->get('MTP_is_override'),
1485
-                'css_class'  => '',
1486
-                'format'     => '%d',
1487
-                'db-col'     => 'MTP_is_override'
1488
-            );
1477
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1478
+				'name'       => 'MTP_is_override',
1479
+				'label'      => __('Override all custom', 'event_espresso'),
1480
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
+				'type'       => 'int',
1482
+				'required'   => false,
1483
+				'validation' => true,
1484
+				'value'      => $message_template_group->get('MTP_is_override'),
1485
+				'css_class'  => '',
1486
+				'format'     => '%d',
1487
+				'db-col'     => 'MTP_is_override'
1488
+			);
1489 1489
             
1490
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1491
-                'name'       => 'MTP_is_active',
1492
-                'label'      => __('Active Template', 'event_espresso'),
1493
-                'input'      => 'hidden',
1494
-                'type'       => 'int',
1495
-                'required'   => false,
1496
-                'validation' => true,
1497
-                'value'      => $message_template_group->is_active(),
1498
-                'css_class'  => '',
1499
-                'format'     => '%d',
1500
-                'db-col'     => 'MTP_is_active'
1501
-            );
1490
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1491
+				'name'       => 'MTP_is_active',
1492
+				'label'      => __('Active Template', 'event_espresso'),
1493
+				'input'      => 'hidden',
1494
+				'type'       => 'int',
1495
+				'required'   => false,
1496
+				'validation' => true,
1497
+				'value'      => $message_template_group->is_active(),
1498
+				'css_class'  => '',
1499
+				'format'     => '%d',
1500
+				'db-col'     => 'MTP_is_active'
1501
+			);
1502 1502
             
1503
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1504
-                'name'       => 'MTP_deleted',
1505
-                'label'      => null,
1506
-                'input'      => 'hidden',
1507
-                'type'       => 'int',
1508
-                'required'   => false,
1509
-                'validation' => true,
1510
-                'value'      => $message_template_group->get('MTP_deleted'),
1511
-                'css_class'  => '',
1512
-                'format'     => '%d',
1513
-                'db-col'     => 'MTP_deleted'
1514
-            );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1516
-                'name'       => 'MTP_user_id',
1517
-                'label'      => __('Author', 'event_espresso'),
1518
-                'input'      => 'hidden',
1519
-                'type'       => 'int',
1520
-                'required'   => false,
1521
-                'validation' => false,
1522
-                'value'      => $message_template_group->user(),
1523
-                'format'     => '%d',
1524
-                'db-col'     => 'MTP_user_id'
1525
-            );
1503
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1504
+				'name'       => 'MTP_deleted',
1505
+				'label'      => null,
1506
+				'input'      => 'hidden',
1507
+				'type'       => 'int',
1508
+				'required'   => false,
1509
+				'validation' => true,
1510
+				'value'      => $message_template_group->get('MTP_deleted'),
1511
+				'css_class'  => '',
1512
+				'format'     => '%d',
1513
+				'db-col'     => 'MTP_deleted'
1514
+			);
1515
+			$sidebar_form_fields['ee-msg-author']  = array(
1516
+				'name'       => 'MTP_user_id',
1517
+				'label'      => __('Author', 'event_espresso'),
1518
+				'input'      => 'hidden',
1519
+				'type'       => 'int',
1520
+				'required'   => false,
1521
+				'validation' => false,
1522
+				'value'      => $message_template_group->user(),
1523
+				'format'     => '%d',
1524
+				'db-col'     => 'MTP_user_id'
1525
+			);
1526 1526
             
1527
-            $sidebar_form_fields['ee-msg-route'] = array(
1528
-                'name'  => 'action',
1529
-                'input' => 'hidden',
1530
-                'type'  => 'string',
1531
-                'value' => $action
1532
-            );
1527
+			$sidebar_form_fields['ee-msg-route'] = array(
1528
+				'name'  => 'action',
1529
+				'input' => 'hidden',
1530
+				'type'  => 'string',
1531
+				'value' => $action
1532
+			);
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1535
-                'name'  => 'id',
1536
-                'input' => 'hidden',
1537
-                'type'  => 'int',
1538
-                'value' => $GRP_ID
1539
-            );
1540
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1542
-                'input' => 'hidden',
1543
-                'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1545
-            );
1534
+			$sidebar_form_fields['ee-msg-id']        = array(
1535
+				'name'  => 'id',
1536
+				'input' => 'hidden',
1537
+				'type'  => 'int',
1538
+				'value' => $GRP_ID
1539
+			);
1540
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
+				'name'  => $action . '_nonce',
1542
+				'input' => 'hidden',
1543
+				'type'  => 'string',
1544
+				'value' => wp_create_nonce($action . '_nonce')
1545
+			);
1546 1546
             
1547
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1549
-                    'name'  => 'template_switch',
1550
-                    'input' => 'hidden',
1551
-                    'type'  => 'int',
1552
-                    'value' => 1
1553
-                );
1554
-            }
1547
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1549
+					'name'  => 'template_switch',
1550
+					'input' => 'hidden',
1551
+					'type'  => 'int',
1552
+					'value' => 1
1553
+				);
1554
+			}
1555 1555
             
1556 1556
             
1557
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1557
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1559 1559
             
1560 1560
             
1561
-        } //end if ( !empty($template_field_structure) )
1561
+		} //end if ( !empty($template_field_structure) )
1562 1562
         
1563
-        //set extra content for publish box
1564
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
-        $this->_set_publish_post_box_vars(
1566
-            'id',
1567
-            $GRP_ID,
1568
-            false,
1569
-            add_query_arg(
1570
-                array('action' => 'global_mtps'),
1571
-                $this->_admin_base_url
1572
-            )
1573
-        );
1574
-        
1575
-        //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1577
-            array(
1578
-                'message_type' => $message_template_group->message_type(),
1579
-                'messenger'    => $message_template_group->messenger(),
1580
-                'context'      => $context,
1581
-                'GRP_ID'       => $GRP_ID,
1582
-                'action'       => 'preview_message'
1583
-            ),
1584
-            $this->_admin_base_url
1585
-        );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1588
-        
1589
-        
1590
-        //setup context switcher
1591
-        $context_switcher_args = array(
1592
-            'page'    => 'espresso_messages',
1593
-            'action'  => 'edit_message_template',
1594
-            'id'      => $GRP_ID,
1595
-            'context' => $context,
1596
-            'extra'   => $preview_button
1597
-        );
1598
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
-        
1600
-        
1601
-        //main box
1602
-        $this->_template_args['template_fields']                         = $template_fields;
1603
-        $this->_template_args['sidebar_box_id']                          = 'details';
1604
-        $this->_template_args['action']                                  = $action;
1605
-        $this->_template_args['context']                                 = $context;
1606
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
-        $this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
-        
1609
-        
1610
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
-        
1614
-        $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
-        
1618
-        //send along EE_Message_Template_Group object for further template use.
1619
-        $this->_template_args['MTP'] = $message_template_group;
1620
-        
1621
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
-            $this->_template_args, true);
1623
-        
1624
-        
1625
-        //finally, let's set the admin_page title
1626
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
-        
1628
-        
1629
-        //we need to take care of setting the shortcodes property for use elsewhere.
1630
-        $this->_set_shortcodes();
1631
-        
1632
-        
1633
-        //final template wrapper
1634
-        $this->display_admin_page_with_sidebar();
1635
-    }
1636
-    
1637
-    
1638
-    public function filter_tinymce_init($mceInit, $editor_id)
1639
-    {
1640
-        return $mceInit;
1641
-    }
1642
-    
1643
-    
1644
-    public function add_context_switcher()
1645
-    {
1646
-        return $this->_context_switcher;
1647
-    }
1648
-    
1649
-    public function _add_form_element_before()
1650
-    {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
-    }
1653
-    
1654
-    public function _add_form_element_after()
1655
-    {
1656
-        return '</form>';
1657
-    }
1658
-    
1659
-    
1660
-    /**
1661
-     * This executes switching the template pack for a message template.
1662
-     *
1663
-     * @since 4.5.0
1664
-     *
1665
-     */
1666
-    public function switch_template_pack()
1667
-    {
1668
-        $GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
-        
1671
-        //verify we have needed values.
1672
-        if (empty($GRP_ID) || empty($template_pack)) {
1673
-            $this->_template_args['error'] = true;
1674
-            EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
-                __FILE__, __FUNCTION__, __LINE__);
1676
-        } else {
1677
-            //get template, set the new template_pack and then reset to default
1678
-            /** @type EE_Message_Template_Group $message_template_group */
1679
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1563
+		//set extra content for publish box
1564
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
+		$this->_set_publish_post_box_vars(
1566
+			'id',
1567
+			$GRP_ID,
1568
+			false,
1569
+			add_query_arg(
1570
+				array('action' => 'global_mtps'),
1571
+				$this->_admin_base_url
1572
+			)
1573
+		);
1574
+        
1575
+		//add preview button
1576
+		$preview_url    = parent::add_query_args_and_nonce(
1577
+			array(
1578
+				'message_type' => $message_template_group->message_type(),
1579
+				'messenger'    => $message_template_group->messenger(),
1580
+				'context'      => $context,
1581
+				'GRP_ID'       => $GRP_ID,
1582
+				'action'       => 'preview_message'
1583
+			),
1584
+			$this->_admin_base_url
1585
+		);
1586
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
+				'event_espresso') . '</a>';
1588
+        
1589
+        
1590
+		//setup context switcher
1591
+		$context_switcher_args = array(
1592
+			'page'    => 'espresso_messages',
1593
+			'action'  => 'edit_message_template',
1594
+			'id'      => $GRP_ID,
1595
+			'context' => $context,
1596
+			'extra'   => $preview_button
1597
+		);
1598
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
+        
1600
+        
1601
+		//main box
1602
+		$this->_template_args['template_fields']                         = $template_fields;
1603
+		$this->_template_args['sidebar_box_id']                          = 'details';
1604
+		$this->_template_args['action']                                  = $action;
1605
+		$this->_template_args['context']                                 = $context;
1606
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
+		$this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
+        
1609
+        
1610
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
+        
1614
+		$this->_template_path = $this->_template_args['GRP_ID']
1615
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
+        
1618
+		//send along EE_Message_Template_Group object for further template use.
1619
+		$this->_template_args['MTP'] = $message_template_group;
1620
+        
1621
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
+			$this->_template_args, true);
1623
+        
1624
+        
1625
+		//finally, let's set the admin_page title
1626
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
+        
1628
+        
1629
+		//we need to take care of setting the shortcodes property for use elsewhere.
1630
+		$this->_set_shortcodes();
1631
+        
1632
+        
1633
+		//final template wrapper
1634
+		$this->display_admin_page_with_sidebar();
1635
+	}
1636
+    
1637
+    
1638
+	public function filter_tinymce_init($mceInit, $editor_id)
1639
+	{
1640
+		return $mceInit;
1641
+	}
1642
+    
1643
+    
1644
+	public function add_context_switcher()
1645
+	{
1646
+		return $this->_context_switcher;
1647
+	}
1648
+    
1649
+	public function _add_form_element_before()
1650
+	{
1651
+		return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
+	}
1653
+    
1654
+	public function _add_form_element_after()
1655
+	{
1656
+		return '</form>';
1657
+	}
1658
+    
1659
+    
1660
+	/**
1661
+	 * This executes switching the template pack for a message template.
1662
+	 *
1663
+	 * @since 4.5.0
1664
+	 *
1665
+	 */
1666
+	public function switch_template_pack()
1667
+	{
1668
+		$GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
+        
1671
+		//verify we have needed values.
1672
+		if (empty($GRP_ID) || empty($template_pack)) {
1673
+			$this->_template_args['error'] = true;
1674
+			EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
+				__FILE__, __FUNCTION__, __LINE__);
1676
+		} else {
1677
+			//get template, set the new template_pack and then reset to default
1678
+			/** @type EE_Message_Template_Group $message_template_group */
1679
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1680 1680
             
1681
-            $message_template_group->set_template_pack_name($template_pack);
1682
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1683
-            $this->_req_data['mt']   = $message_template_group->message_type();
1681
+			$message_template_group->set_template_pack_name($template_pack);
1682
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1683
+			$this->_req_data['mt']   = $message_template_group->message_type();
1684 1684
             
1685
-            $query_args = $this->_reset_to_default_template();
1685
+			$query_args = $this->_reset_to_default_template();
1686 1686
             
1687
-            if (empty($query_args['id'])) {
1688
-                EE_Error::add_error(
1689
-                    __(
1690
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
-                        'event_espresso'
1692
-                    ),
1693
-                    __FILE__, __FUNCTION__, __LINE__
1694
-                );
1695
-                $this->_template_args['error'] = true;
1696
-            } else {
1697
-                $template_label       = $message_template_group->get_template_pack()->label;
1698
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
-                EE_Error::add_success(
1700
-                    sprintf(
1701
-                        __(
1702
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
-                            'event_espresso'
1704
-                        ),
1705
-                        $template_label,
1706
-                        $template_pack_labels->template_pack
1707
-                    )
1708
-                );
1709
-                //generate the redirect url for js.
1710
-                $url                                          = self::add_query_args_and_nonce($query_args,
1711
-                    $this->_admin_base_url);
1712
-                $this->_template_args['data']['redirect_url'] = $url;
1713
-                $this->_template_args['success']              = true;
1714
-            }
1687
+			if (empty($query_args['id'])) {
1688
+				EE_Error::add_error(
1689
+					__(
1690
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
+						'event_espresso'
1692
+					),
1693
+					__FILE__, __FUNCTION__, __LINE__
1694
+				);
1695
+				$this->_template_args['error'] = true;
1696
+			} else {
1697
+				$template_label       = $message_template_group->get_template_pack()->label;
1698
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
+				EE_Error::add_success(
1700
+					sprintf(
1701
+						__(
1702
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
+							'event_espresso'
1704
+						),
1705
+						$template_label,
1706
+						$template_pack_labels->template_pack
1707
+					)
1708
+				);
1709
+				//generate the redirect url for js.
1710
+				$url                                          = self::add_query_args_and_nonce($query_args,
1711
+					$this->_admin_base_url);
1712
+				$this->_template_args['data']['redirect_url'] = $url;
1713
+				$this->_template_args['success']              = true;
1714
+			}
1715 1715
             
1716
-            $this->_return_json();
1716
+			$this->_return_json();
1717 1717
             
1718
-        }
1719
-    }
1720
-    
1721
-    
1722
-    /**
1723
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
-     * they want.
1725
-     *
1726
-     * @access protected
1727
-     * @return array|null
1728
-     */
1729
-    protected function _reset_to_default_template()
1730
-    {
1731
-        
1732
-        $templates = array();
1733
-        $GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
-        //we need to make sure we've got the info we need.
1735
-        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
-            EE_Error::add_error(
1737
-                __(
1738
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1739
-                    'event_espresso'
1740
-                ),
1741
-                __FILE__, __FUNCTION__, __LINE__
1742
-            );
1743
-        }
1744
-        
1745
-        // all templates will be reset to whatever the defaults are
1746
-        // for the global template matching the messenger and message type.
1747
-        $success = ! empty($GRP_ID) ? true : false;
1748
-        
1749
-        if ($success) {
1718
+		}
1719
+	}
1720
+    
1721
+    
1722
+	/**
1723
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
+	 * they want.
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return array|null
1728
+	 */
1729
+	protected function _reset_to_default_template()
1730
+	{
1731
+        
1732
+		$templates = array();
1733
+		$GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
+		//we need to make sure we've got the info we need.
1735
+		if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
+			EE_Error::add_error(
1737
+				__(
1738
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1739
+					'event_espresso'
1740
+				),
1741
+				__FILE__, __FUNCTION__, __LINE__
1742
+			);
1743
+		}
1744
+        
1745
+		// all templates will be reset to whatever the defaults are
1746
+		// for the global template matching the messenger and message type.
1747
+		$success = ! empty($GRP_ID) ? true : false;
1748
+        
1749
+		if ($success) {
1750 1750
             
1751
-            //let's first determine if the incoming template is a global template,
1752
-            // if it isn't then we need to get the global template matching messenger and message type.
1753
-            //$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1751
+			//let's first determine if the incoming template is a global template,
1752
+			// if it isn't then we need to get the global template matching messenger and message type.
1753
+			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1754 1754
             
1755 1755
             
1756
-            //note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
1756
+			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
1758 1758
             
1759
-            if ($success) {
1760
-                // if successfully deleted, lets generate the new ones.
1761
-                // Note. We set GLOBAL to true, because resets on ANY template
1762
-                // will use the related global template defaults for regeneration.
1763
-                // This means that if a custom template is reset it resets to whatever the related global template is.
1764
-                // HOWEVER, we DO keep the template pack and template variation set
1765
-                // for the current custom template when resetting.
1766
-                $templates = $this->_generate_new_templates(
1767
-                    $this->_req_data['msgr'],
1768
-                    $this->_req_data['mt'],
1769
-                    $GRP_ID,
1770
-                    true
1771
-                );
1772
-            }
1759
+			if ($success) {
1760
+				// if successfully deleted, lets generate the new ones.
1761
+				// Note. We set GLOBAL to true, because resets on ANY template
1762
+				// will use the related global template defaults for regeneration.
1763
+				// This means that if a custom template is reset it resets to whatever the related global template is.
1764
+				// HOWEVER, we DO keep the template pack and template variation set
1765
+				// for the current custom template when resetting.
1766
+				$templates = $this->_generate_new_templates(
1767
+					$this->_req_data['msgr'],
1768
+					$this->_req_data['mt'],
1769
+					$GRP_ID,
1770
+					true
1771
+				);
1772
+			}
1773 1773
             
1774
-        }
1775
-        
1776
-        //any error messages?
1777
-        if ( ! $success) {
1778
-            EE_Error::add_error(
1779
-                __('Something went wrong with deleting existing templates. Unable to reset to default',
1780
-                    'event_espresso'),
1781
-                __FILE__, __FUNCTION__, __LINE__
1782
-            );
1783
-        }
1784
-        
1785
-        //all good, let's add a success message!
1786
-        if ($success && ! empty($templates)) {
1787
-            $templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
-            EE_Error::overwrite_success();
1789
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
-        }
1791
-        
1792
-        
1793
-        $query_args = array(
1794
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
-        );
1798
-        
1799
-        //if called via ajax then we return query args otherwise redirect
1800
-        if (defined('DOING_AJAX') && DOING_AJAX) {
1801
-            return $query_args;
1802
-        } else {
1803
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1774
+		}
1775
+        
1776
+		//any error messages?
1777
+		if ( ! $success) {
1778
+			EE_Error::add_error(
1779
+				__('Something went wrong with deleting existing templates. Unable to reset to default',
1780
+					'event_espresso'),
1781
+				__FILE__, __FUNCTION__, __LINE__
1782
+			);
1783
+		}
1784
+        
1785
+		//all good, let's add a success message!
1786
+		if ($success && ! empty($templates)) {
1787
+			$templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
+			EE_Error::overwrite_success();
1789
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
+		}
1791
+        
1792
+        
1793
+		$query_args = array(
1794
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
+		);
1798
+        
1799
+		//if called via ajax then we return query args otherwise redirect
1800
+		if (defined('DOING_AJAX') && DOING_AJAX) {
1801
+			return $query_args;
1802
+		} else {
1803
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1804 1804
             
1805
-            return null;
1806
-        }
1807
-    }
1808
-    
1809
-    
1810
-    /**
1811
-     * Retrieve and set the message preview for display.
1812
-     *
1813
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
-     *
1815
-     * @return string
1816
-     */
1817
-    public function _preview_message($send = false)
1818
-    {
1819
-        //first make sure we've got the necessary parameters
1820
-        if (
1821
-        ! isset(
1822
-            $this->_req_data['message_type'],
1823
-            $this->_req_data['messenger'],
1824
-            $this->_req_data['messenger'],
1825
-            $this->_req_data['GRP_ID']
1826
-        )
1827
-        ) {
1828
-            EE_Error::add_error(
1829
-                __('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
-                __FILE__, __FUNCTION__, __LINE__
1831
-            );
1832
-        }
1833
-        
1834
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
-        
1836
-        
1837
-        //get the preview!
1838
-        $preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
-            $this->_req_data['messenger'], $send);
1840
-        
1841
-        if ($send) {
1842
-            return $preview;
1843
-        }
1844
-        
1845
-        //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1847
-            'id'      => $this->_req_data['GRP_ID'],
1848
-            'context' => $this->_req_data['context'],
1849
-            'action'  => 'edit_message_template'
1850
-        );
1851
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1854
-        $message_types          = $this->get_installed_message_types();
1855
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
-        $active_messenger_label = $active_messenger instanceof EE_messenger
1857
-            ? ucwords($active_messenger->label['singular'])
1858
-            : esc_html__('Unknown Messenger', 'event_espresso');
1859
-        //let's provide a helpful title for context
1860
-        $preview_title = sprintf(
1861
-            __('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
-            $active_messenger_label,
1863
-            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
-        );
1865
-        //setup display of preview.
1866
-        $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
-        $this->_template_args['data']['force_json'] = true;
1869
-        
1870
-        return '';
1871
-    }
1872
-    
1873
-    
1874
-    /**
1875
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
-     * gets called automatically.
1877
-     *
1878
-     * @since 4.5.0
1879
-     *
1880
-     * @return string
1881
-     */
1882
-    protected function _display_preview_message()
1883
-    {
1884
-        $this->display_admin_page_with_no_sidebar();
1885
-    }
1886
-    
1887
-    
1888
-    /**
1889
-     * registers metaboxes that should show up on the "edit_message_template" page
1890
-     *
1891
-     * @access protected
1892
-     * @return void
1893
-     */
1894
-    protected function _register_edit_meta_boxes()
1895
-    {
1896
-        add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
-            array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
-        add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
-            $this->_current_screen->id, 'side', 'high');
1900
-        add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
-            $this->_current_screen->id, 'side', 'high');
1902
-    }
1903
-    
1904
-    
1905
-    /**
1906
-     * metabox content for all template pack and variation selection.
1907
-     *
1908
-     * @since 4.5.0
1909
-     *
1910
-     * @return string
1911
-     */
1912
-    public function template_pack_meta_box()
1913
-    {
1914
-        $this->_set_message_template_group();
1915
-        
1916
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
-        
1918
-        $tp_select_values = array();
1919
-        
1920
-        foreach ($tp_collection as $tp) {
1921
-            //only include template packs that support this messenger and message type!
1922
-            $supports = $tp->get_supports();
1923
-            if (
1924
-                ! isset($supports[$this->_message_template_group->messenger()])
1925
-                || ! in_array(
1926
-                    $this->_message_template_group->message_type(),
1927
-                    $supports[$this->_message_template_group->messenger()]
1928
-                )
1929
-            ) {
1930
-                //not supported
1931
-                continue;
1932
-            }
1805
+			return null;
1806
+		}
1807
+	}
1808
+    
1809
+    
1810
+	/**
1811
+	 * Retrieve and set the message preview for display.
1812
+	 *
1813
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
+	 *
1815
+	 * @return string
1816
+	 */
1817
+	public function _preview_message($send = false)
1818
+	{
1819
+		//first make sure we've got the necessary parameters
1820
+		if (
1821
+		! isset(
1822
+			$this->_req_data['message_type'],
1823
+			$this->_req_data['messenger'],
1824
+			$this->_req_data['messenger'],
1825
+			$this->_req_data['GRP_ID']
1826
+		)
1827
+		) {
1828
+			EE_Error::add_error(
1829
+				__('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
+				__FILE__, __FUNCTION__, __LINE__
1831
+			);
1832
+		}
1833
+        
1834
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
+        
1836
+        
1837
+		//get the preview!
1838
+		$preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
+			$this->_req_data['messenger'], $send);
1840
+        
1841
+		if ($send) {
1842
+			return $preview;
1843
+		}
1844
+        
1845
+		//let's add a button to go back to the edit view
1846
+		$query_args             = array(
1847
+			'id'      => $this->_req_data['GRP_ID'],
1848
+			'context' => $this->_req_data['context'],
1849
+			'action'  => 'edit_message_template'
1850
+		);
1851
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
+		$preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
+				'event_espresso') . '</a>';
1854
+		$message_types          = $this->get_installed_message_types();
1855
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
+		$active_messenger_label = $active_messenger instanceof EE_messenger
1857
+			? ucwords($active_messenger->label['singular'])
1858
+			: esc_html__('Unknown Messenger', 'event_espresso');
1859
+		//let's provide a helpful title for context
1860
+		$preview_title = sprintf(
1861
+			__('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
+			$active_messenger_label,
1863
+			ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
+		);
1865
+		//setup display of preview.
1866
+		$this->_admin_page_title                    = $preview_title;
1867
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
+		$this->_template_args['data']['force_json'] = true;
1869
+        
1870
+		return '';
1871
+	}
1872
+    
1873
+    
1874
+	/**
1875
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
+	 * gets called automatically.
1877
+	 *
1878
+	 * @since 4.5.0
1879
+	 *
1880
+	 * @return string
1881
+	 */
1882
+	protected function _display_preview_message()
1883
+	{
1884
+		$this->display_admin_page_with_no_sidebar();
1885
+	}
1886
+    
1887
+    
1888
+	/**
1889
+	 * registers metaboxes that should show up on the "edit_message_template" page
1890
+	 *
1891
+	 * @access protected
1892
+	 * @return void
1893
+	 */
1894
+	protected function _register_edit_meta_boxes()
1895
+	{
1896
+		add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
+			array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
+		add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
+			$this->_current_screen->id, 'side', 'high');
1900
+		add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
+			$this->_current_screen->id, 'side', 'high');
1902
+	}
1903
+    
1904
+    
1905
+	/**
1906
+	 * metabox content for all template pack and variation selection.
1907
+	 *
1908
+	 * @since 4.5.0
1909
+	 *
1910
+	 * @return string
1911
+	 */
1912
+	public function template_pack_meta_box()
1913
+	{
1914
+		$this->_set_message_template_group();
1915
+        
1916
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
+        
1918
+		$tp_select_values = array();
1919
+        
1920
+		foreach ($tp_collection as $tp) {
1921
+			//only include template packs that support this messenger and message type!
1922
+			$supports = $tp->get_supports();
1923
+			if (
1924
+				! isset($supports[$this->_message_template_group->messenger()])
1925
+				|| ! in_array(
1926
+					$this->_message_template_group->message_type(),
1927
+					$supports[$this->_message_template_group->messenger()]
1928
+				)
1929
+			) {
1930
+				//not supported
1931
+				continue;
1932
+			}
1933 1933
             
1934
-            $tp_select_values[] = array(
1935
-                'text' => $tp->label,
1936
-                'id'   => $tp->dbref
1937
-            );
1938
-        }
1939
-        
1940
-        //if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
-        if (empty($tp_select_values)) {
1942
-            $tp_select_values[] = array(
1943
-                'text' => __('Default', 'event_espresso'),
1944
-                'id'   => 'default'
1945
-            );
1946
-        }
1947
-        
1948
-        //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
-            $this->_message_template_group->messenger(),
1951
-            $this->_message_template_group->message_type()
1952
-        );
1953
-        $variations_select_values = array();
1954
-        foreach ($variations as $variation => $label) {
1955
-            $variations_select_values[] = array(
1956
-                'text' => $label,
1957
-                'id'   => $variation
1958
-            );
1959
-        }
1960
-        
1961
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
-        
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
-            'MTP_template_pack',
1965
-            $tp_select_values,
1966
-            $this->_message_template_group->get_template_pack_name()
1967
-        );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
-            'MTP_template_variation',
1970
-            $variations_select_values,
1971
-            $this->_message_template_group->get_template_pack_variation()
1972
-        );
1973
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
-        
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
-        
1980
-        EEH_Template::display_template($template, $template_args);
1981
-    }
1982
-    
1983
-    
1984
-    /**
1985
-     * This meta box holds any extra actions related to Message Templates
1986
-     * For now, this includes Resetting templates to defaults and sending a test email.
1987
-     *
1988
-     * @access  public
1989
-     * @return void
1990
-     * @throws \EE_Error
1991
-     */
1992
-    public function extra_actions_meta_box()
1993
-    {
1994
-        $template_form_fields = array();
1995
-        
1996
-        $extra_args = array(
1997
-            'msgr'   => $this->_message_template_group->messenger(),
1998
-            'mt'     => $this->_message_template_group->message_type(),
1999
-            'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
-        );
2001
-        //first we need to see if there are any fields
2002
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
-        
2004
-        if ( ! empty($fields)) {
2005
-            //yup there be fields
2006
-            foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
-                $default  = isset($config['default']) ? $config['default'] : '';
2010
-                $default  = isset($config['value']) ? $config['value'] : $default;
1934
+			$tp_select_values[] = array(
1935
+				'text' => $tp->label,
1936
+				'id'   => $tp->dbref
1937
+			);
1938
+		}
1939
+        
1940
+		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
+		if (empty($tp_select_values)) {
1942
+			$tp_select_values[] = array(
1943
+				'text' => __('Default', 'event_espresso'),
1944
+				'id'   => 'default'
1945
+			);
1946
+		}
1947
+        
1948
+		//setup variation select values for the currently selected template.
1949
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
+			$this->_message_template_group->messenger(),
1951
+			$this->_message_template_group->message_type()
1952
+		);
1953
+		$variations_select_values = array();
1954
+		foreach ($variations as $variation => $label) {
1955
+			$variations_select_values[] = array(
1956
+				'text' => $label,
1957
+				'id'   => $variation
1958
+			);
1959
+		}
1960
+        
1961
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
+        
1963
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
+			'MTP_template_pack',
1965
+			$tp_select_values,
1966
+			$this->_message_template_group->get_template_pack_name()
1967
+		);
1968
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
+			'MTP_template_variation',
1970
+			$variations_select_values,
1971
+			$this->_message_template_group->get_template_pack_variation()
1972
+		);
1973
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
+        
1978
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
+        
1980
+		EEH_Template::display_template($template, $template_args);
1981
+	}
1982
+    
1983
+    
1984
+	/**
1985
+	 * This meta box holds any extra actions related to Message Templates
1986
+	 * For now, this includes Resetting templates to defaults and sending a test email.
1987
+	 *
1988
+	 * @access  public
1989
+	 * @return void
1990
+	 * @throws \EE_Error
1991
+	 */
1992
+	public function extra_actions_meta_box()
1993
+	{
1994
+		$template_form_fields = array();
1995
+        
1996
+		$extra_args = array(
1997
+			'msgr'   => $this->_message_template_group->messenger(),
1998
+			'mt'     => $this->_message_template_group->message_type(),
1999
+			'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
+		);
2001
+		//first we need to see if there are any fields
2002
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
+        
2004
+		if ( ! empty($fields)) {
2005
+			//yup there be fields
2006
+			foreach ($fields as $field => $config) {
2007
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
+				$default  = isset($config['default']) ? $config['default'] : '';
2010
+				$default  = isset($config['value']) ? $config['value'] : $default;
2011 2011
                 
2012
-                // if type is hidden and the value is empty
2013
-                // something may have gone wrong so let's correct with the defaults
2014
-                $fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
-                    ? $default
2016
-                    : '';
2017
-                $existing[$field] = isset($existing[$field]) && empty($fix)
2018
-                    ? $existing[$field]
2019
-                    : $fix;
2012
+				// if type is hidden and the value is empty
2013
+				// something may have gone wrong so let's correct with the defaults
2014
+				$fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
+					? $default
2016
+					: '';
2017
+				$existing[$field] = isset($existing[$field]) && empty($fix)
2018
+					? $existing[$field]
2019
+					: $fix;
2020 2020
                 
2021
-                $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2023
-                    'label'      => $config['label'],
2024
-                    'input'      => $config['input'],
2025
-                    'type'       => $config['type'],
2026
-                    'required'   => $config['required'],
2027
-                    'validation' => $config['validation'],
2028
-                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
-                    'css_class'  => $config['css_class'],
2030
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2031
-                    'default'    => $default,
2032
-                    'format'     => $config['format']
2033
-                );
2034
-            }
2035
-        }
2036
-        
2037
-        $test_settings_fields = ! empty($template_form_fields)
2038
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
-            : '';
2040
-        
2041
-        $test_settings_html = '';
2042
-        //print out $test_settings_fields
2043
-        if ( ! empty($test_settings_fields)) {
2044
-            echo $test_settings_fields;
2045
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
-            $test_settings_html .= 'name="test_button" value="';
2047
-            $test_settings_html .= __('Test Send', 'event_espresso');
2048
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2049
-        }
2050
-        
2051
-        //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
-        $test_settings_html .= $this->get_action_link_or_button(
2055
-            'reset_to_default',
2056
-            'reset',
2057
-            $extra_args,
2058
-            'button-primary reset-default-button'
2059
-        );
2060
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2061
-        echo $test_settings_html;
2062
-    }
2063
-    
2064
-    
2065
-    /**
2066
-     * This returns the shortcode selector skeleton for a given context and field.
2067
-     *
2068
-     * @since 4.9.rc.000
2069
-     *
2070
-     * @param string $field           The name of the field retrieving shortcodes for.
2071
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
-     *
2073
-     * @return string
2074
-     */
2075
-    protected function _get_shortcode_selector($field, $linked_input_id)
2076
-    {
2077
-        $template_args = array(
2078
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
-            'fieldname'       => $field,
2080
-            'linked_input_id' => $linked_input_id
2081
-        );
2082
-        
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
-            $template_args, true);
2085
-    }
2086
-    
2087
-    
2088
-    /**
2089
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
-     * page)
2091
-     *
2092
-     * @access public
2093
-     * @return void
2094
-     */
2095
-    public function shortcode_meta_box()
2096
-    {
2097
-        $shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
-        //$messenger = $this->_message_template_group->messenger_obj();
2099
-        //now let's set the content depending on the status of the shortcodes array
2100
-        if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
-            echo $content;
2103
-        } else {
2104
-            //$alt = 0;
2105
-            ?>
2021
+				$template_form_fields[$field_id] = array(
2022
+					'name'       => 'test_settings_fld[' . $field . ']',
2023
+					'label'      => $config['label'],
2024
+					'input'      => $config['input'],
2025
+					'type'       => $config['type'],
2026
+					'required'   => $config['required'],
2027
+					'validation' => $config['validation'],
2028
+					'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
+					'css_class'  => $config['css_class'],
2030
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2031
+					'default'    => $default,
2032
+					'format'     => $config['format']
2033
+				);
2034
+			}
2035
+		}
2036
+        
2037
+		$test_settings_fields = ! empty($template_form_fields)
2038
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
+			: '';
2040
+        
2041
+		$test_settings_html = '';
2042
+		//print out $test_settings_fields
2043
+		if ( ! empty($test_settings_fields)) {
2044
+			echo $test_settings_fields;
2045
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
+			$test_settings_html .= 'name="test_button" value="';
2047
+			$test_settings_html .= __('Test Send', 'event_espresso');
2048
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2049
+		}
2050
+        
2051
+		//and button
2052
+		$test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
+		$test_settings_html .= $this->get_action_link_or_button(
2055
+			'reset_to_default',
2056
+			'reset',
2057
+			$extra_args,
2058
+			'button-primary reset-default-button'
2059
+		);
2060
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2061
+		echo $test_settings_html;
2062
+	}
2063
+    
2064
+    
2065
+	/**
2066
+	 * This returns the shortcode selector skeleton for a given context and field.
2067
+	 *
2068
+	 * @since 4.9.rc.000
2069
+	 *
2070
+	 * @param string $field           The name of the field retrieving shortcodes for.
2071
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
+	 *
2073
+	 * @return string
2074
+	 */
2075
+	protected function _get_shortcode_selector($field, $linked_input_id)
2076
+	{
2077
+		$template_args = array(
2078
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
+			'fieldname'       => $field,
2080
+			'linked_input_id' => $linked_input_id
2081
+		);
2082
+        
2083
+		return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
+			$template_args, true);
2085
+	}
2086
+    
2087
+    
2088
+	/**
2089
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
+	 * page)
2091
+	 *
2092
+	 * @access public
2093
+	 * @return void
2094
+	 */
2095
+	public function shortcode_meta_box()
2096
+	{
2097
+		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
+		//$messenger = $this->_message_template_group->messenger_obj();
2099
+		//now let's set the content depending on the status of the shortcodes array
2100
+		if (empty($shortcodes)) {
2101
+			$content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
+			echo $content;
2103
+		} else {
2104
+			//$alt = 0;
2105
+			?>
2106 2106
             <div
2107 2107
                 style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div>
2108 2108
             <p class="small-text"><?php printf(__('You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2109
-                    'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2109
+					'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2110 2110
             <?php
2111
-        }
2112
-        
2113
-        
2114
-    }
2115
-    
2116
-    
2117
-    /**
2118
-     * used to set the $_shortcodes property for when its needed elsewhere.
2119
-     *
2120
-     * @access protected
2121
-     * @return void
2122
-     */
2123
-    protected function _set_shortcodes()
2124
-    {
2125
-        
2126
-        //no need to run this if the property is already set
2127
-        if ( ! empty($this->_shortcodes)) {
2128
-            return;
2129
-        }
2130
-        
2131
-        $this->_shortcodes = $this->_get_shortcodes();
2132
-    }
2133
-    
2134
-    
2135
-    /**
2136
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
-     * property)
2138
-     *
2139
-     * @access  protected
2140
-     *
2141
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
-     *                         for. Defaults to all (for the given context)
2143
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
-     *
2145
-     * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
-     *                        true just an array of shortcode/label pairs.
2147
-     */
2148
-    protected function _get_shortcodes($fields = array(), $merged = true)
2149
-    {
2150
-        $this->_set_message_template_group();
2151
-        
2152
-        //we need the messenger and message template to retrieve the valid shortcodes array.
2153
-        $GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
-        $context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
-        
2156
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
-    }
2158
-    
2159
-    
2160
-    /**
2161
-     * This sets the _message_template property (containing the called message_template object)
2162
-     *
2163
-     * @access protected
2164
-     * @return  void
2165
-     */
2166
-    protected function _set_message_template_group()
2167
-    {
2168
-        
2169
-        if ( ! empty($this->_message_template_group)) {
2170
-            return;
2171
-        } //get out if this is already set.
2172
-        
2173
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
-        
2176
-        //let's get the message templates
2177
-        $MTP = EEM_Message_Template_Group::instance();
2178
-        
2179
-        if (empty($GRP_ID)) {
2180
-            $this->_message_template_group = $MTP->create_default_object();
2181
-        } else {
2182
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
-        }
2184
-        
2185
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2186
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
-        
2188
-    }
2189
-    
2190
-    
2191
-    /**
2192
-     * sets up a context switcher for edit forms
2193
-     *
2194
-     * @access  protected
2195
-     *
2196
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
-     * @param array                      $args                  various things the context switcher needs.
2198
-     *
2199
-     */
2200
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
-    {
2202
-        $context_details = $template_group_object->contexts_config();
2203
-        $context_label   = $template_group_object->context_label();
2204
-        ob_start();
2205
-        ?>
2111
+		}
2112
+        
2113
+        
2114
+	}
2115
+    
2116
+    
2117
+	/**
2118
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2119
+	 *
2120
+	 * @access protected
2121
+	 * @return void
2122
+	 */
2123
+	protected function _set_shortcodes()
2124
+	{
2125
+        
2126
+		//no need to run this if the property is already set
2127
+		if ( ! empty($this->_shortcodes)) {
2128
+			return;
2129
+		}
2130
+        
2131
+		$this->_shortcodes = $this->_get_shortcodes();
2132
+	}
2133
+    
2134
+    
2135
+	/**
2136
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
+	 * property)
2138
+	 *
2139
+	 * @access  protected
2140
+	 *
2141
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
+	 *                         for. Defaults to all (for the given context)
2143
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
+	 *
2145
+	 * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
+	 *                        true just an array of shortcode/label pairs.
2147
+	 */
2148
+	protected function _get_shortcodes($fields = array(), $merged = true)
2149
+	{
2150
+		$this->_set_message_template_group();
2151
+        
2152
+		//we need the messenger and message template to retrieve the valid shortcodes array.
2153
+		$GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
+		$context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
+        
2156
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
+	}
2158
+    
2159
+    
2160
+	/**
2161
+	 * This sets the _message_template property (containing the called message_template object)
2162
+	 *
2163
+	 * @access protected
2164
+	 * @return  void
2165
+	 */
2166
+	protected function _set_message_template_group()
2167
+	{
2168
+        
2169
+		if ( ! empty($this->_message_template_group)) {
2170
+			return;
2171
+		} //get out if this is already set.
2172
+        
2173
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
+        
2176
+		//let's get the message templates
2177
+		$MTP = EEM_Message_Template_Group::instance();
2178
+        
2179
+		if (empty($GRP_ID)) {
2180
+			$this->_message_template_group = $MTP->create_default_object();
2181
+		} else {
2182
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
+		}
2184
+        
2185
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2186
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
+        
2188
+	}
2189
+    
2190
+    
2191
+	/**
2192
+	 * sets up a context switcher for edit forms
2193
+	 *
2194
+	 * @access  protected
2195
+	 *
2196
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
+	 * @param array                      $args                  various things the context switcher needs.
2198
+	 *
2199
+	 */
2200
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
+	{
2202
+		$context_details = $template_group_object->contexts_config();
2203
+		$context_label   = $template_group_object->context_label();
2204
+		ob_start();
2205
+		?>
2206 2206
         <div class="ee-msg-switcher-container">
2207 2207
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2208 2208
                 <?php
2209
-                foreach ($args as $name => $value) {
2210
-                    if ($name == 'context' || empty($value) || $name == 'extra') {
2211
-                        continue;
2212
-                    }
2213
-                    ?>
2209
+				foreach ($args as $name => $value) {
2210
+					if ($name == 'context' || empty($value) || $name == 'extra') {
2211
+						continue;
2212
+					}
2213
+					?>
2214 2214
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2215 2215
                     <?php
2216
-                }
2217
-                //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
-                ?>
2216
+				}
2217
+				//setup nonce_url
2218
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
+				?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
2222
-                    $context_templates = $template_group_object->context_templates();
2223
-                    if (is_array($context_templates)) :
2224
-                        foreach ($context_templates as $context => $template_fields) :
2225
-                            $checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
-                            ?>
2222
+					$context_templates = $template_group_object->context_templates();
2223
+					if (is_array($context_templates)) :
2224
+						foreach ($context_templates as $context => $template_fields) :
2225
+							$checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
+							?>
2227 2227
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2228 2228
                                 <?php echo $context_details[$context]['label']; ?>
2229 2229
                             </option>
@@ -2236,1560 +2236,1560 @@  discard block
 block discarded – undo
2236 2236
             <?php echo $args['extra']; ?>
2237 2237
         </div> <!-- end .ee-msg-switcher-container -->
2238 2238
         <?php
2239
-        $output = ob_get_contents();
2240
-        ob_clean();
2241
-        $this->_context_switcher = $output;
2242
-    }
2243
-    
2244
-    
2245
-    /**
2246
-     * utility for sanitizing new values coming in.
2247
-     * Note: this is only used when updating a context.
2248
-     *
2249
-     * @access protected
2250
-     *
2251
-     * @param int $index This helps us know which template field to select from the request array.
2252
-     *
2253
-     * @return array
2254
-     */
2255
-    protected function _set_message_template_column_values($index)
2256
-    {
2257
-        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
-            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
-                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
-            }
2261
-        } /*else {
2239
+		$output = ob_get_contents();
2240
+		ob_clean();
2241
+		$this->_context_switcher = $output;
2242
+	}
2243
+    
2244
+    
2245
+	/**
2246
+	 * utility for sanitizing new values coming in.
2247
+	 * Note: this is only used when updating a context.
2248
+	 *
2249
+	 * @access protected
2250
+	 *
2251
+	 * @param int $index This helps us know which template field to select from the request array.
2252
+	 *
2253
+	 * @return array
2254
+	 */
2255
+	protected function _set_message_template_column_values($index)
2256
+	{
2257
+		if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
+			foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
+				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
+			}
2261
+		} /*else {
2262 2262
 			$this->_req_data['MTP_template_fields'][$index]['content'] = $this->_req_data['MTP_template_fields'][$index]['content'];
2263 2263
 		}*/
2264 2264
         
2265 2265
         
2266
-        $set_column_values = array(
2267
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
-                ? absint($this->_req_data['MTP_is_global'])
2277
-                : 0,
2278
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
-                ? absint($this->_req_data['MTP_is_override'])
2280
-                : 0,
2281
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
-        );
2284
-        
2285
-        
2286
-        return $set_column_values;
2287
-    }
2288
-    
2289
-    
2290
-    protected function _insert_or_update_message_template($new = false)
2291
-    {
2292
-        
2293
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
-        $success  = 0;
2295
-        $override = false;
2296
-        
2297
-        //setup notices description
2298
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
-        
2300
-        //need the message type and messenger objects to be able to use the labels for the notices
2301
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
-        $messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
-        
2304
-        $message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
-        
2307
-        $message_type_label = $message_type_object instanceof EE_message_type
2308
-            ? ucwords($message_type_object->label['singular'])
2309
-            : '';
2310
-        
2311
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2312
-            ? $this->_req_data['MTP_context']
2313
-            : '';
2314
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2315
-        
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
-        $item_desc .= 'Message Template';
2318
-        $query_args  = array();
2319
-        $edit_array  = array();
2320
-        $action_desc = '';
2321
-        
2322
-        //if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
-        if ($new) {
2324
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
-                if (empty($edit_array)) {
2327
-                    $success = 0;
2328
-                } else {
2329
-                    $success    = 1;
2330
-                    $edit_array = $edit_array[0];
2331
-                    $query_args = array(
2332
-                        'id'      => $edit_array['GRP_ID'],
2333
-                        'context' => $edit_array['MTP_context'],
2334
-                        'action'  => 'edit_message_template'
2335
-                    );
2336
-                }
2337
-            }
2338
-            $action_desc = 'created';
2339
-        } else {
2340
-            $MTPG = EEM_Message_Template_Group::instance();
2341
-            $MTP  = EEM_Message_Template::instance();
2266
+		$set_column_values = array(
2267
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
+				? absint($this->_req_data['MTP_is_global'])
2277
+				: 0,
2278
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
+				? absint($this->_req_data['MTP_is_override'])
2280
+				: 0,
2281
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
+		);
2284
+        
2285
+        
2286
+		return $set_column_values;
2287
+	}
2288
+    
2289
+    
2290
+	protected function _insert_or_update_message_template($new = false)
2291
+	{
2292
+        
2293
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
+		$success  = 0;
2295
+		$override = false;
2296
+        
2297
+		//setup notices description
2298
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
+        
2300
+		//need the message type and messenger objects to be able to use the labels for the notices
2301
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
+		$messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
+        
2304
+		$message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
+        
2307
+		$message_type_label = $message_type_object instanceof EE_message_type
2308
+			? ucwords($message_type_object->label['singular'])
2309
+			: '';
2310
+        
2311
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2312
+			? $this->_req_data['MTP_context']
2313
+			: '';
2314
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2315
+        
2316
+		$item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
+		$item_desc .= 'Message Template';
2318
+		$query_args  = array();
2319
+		$edit_array  = array();
2320
+		$action_desc = '';
2321
+        
2322
+		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
+		if ($new) {
2324
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
+				if (empty($edit_array)) {
2327
+					$success = 0;
2328
+				} else {
2329
+					$success    = 1;
2330
+					$edit_array = $edit_array[0];
2331
+					$query_args = array(
2332
+						'id'      => $edit_array['GRP_ID'],
2333
+						'context' => $edit_array['MTP_context'],
2334
+						'action'  => 'edit_message_template'
2335
+					);
2336
+				}
2337
+			}
2338
+			$action_desc = 'created';
2339
+		} else {
2340
+			$MTPG = EEM_Message_Template_Group::instance();
2341
+			$MTP  = EEM_Message_Template::instance();
2342 2342
             
2343 2343
             
2344
-            //run update for each template field in displayed context
2345
-            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
-                EE_Error::add_error(
2347
-                    __('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
-                        'event_espresso'),
2349
-                    __FILE__, __FUNCTION__, __LINE__
2350
-                );
2351
-                $success = 0;
2344
+			//run update for each template field in displayed context
2345
+			if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
+				EE_Error::add_error(
2347
+					__('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
+						'event_espresso'),
2349
+					__FILE__, __FUNCTION__, __LINE__
2350
+				);
2351
+				$success = 0;
2352 2352
                 
2353
-            } else {
2354
-                //first validate all fields!
2355
-                $validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
-                    $message_type_slug);
2353
+			} else {
2354
+				//first validate all fields!
2355
+				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
+					$message_type_slug);
2357 2357
                 
2358
-                //if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
-                if (is_array($validates) && ! empty($validates)) {
2360
-                    //add the transient so when the form loads we know which fields to highlight
2361
-                    $this->_add_transient('edit_message_template', $validates);
2358
+				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
+				if (is_array($validates) && ! empty($validates)) {
2360
+					//add the transient so when the form loads we know which fields to highlight
2361
+					$this->_add_transient('edit_message_template', $validates);
2362 2362
                     
2363
-                    $success = 0;
2363
+					$success = 0;
2364 2364
                     
2365
-                    //setup notices
2366
-                    foreach ($validates as $field => $error) {
2367
-                        if (isset($error['msg'])) {
2368
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
-                        }
2370
-                    }
2365
+					//setup notices
2366
+					foreach ($validates as $field => $error) {
2367
+						if (isset($error['msg'])) {
2368
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
+						}
2370
+					}
2371 2371
                     
2372
-                } else {
2373
-                    $set_column_values = array();
2374
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2372
+				} else {
2373
+					$set_column_values = array();
2374
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2376 2376
                         
2377
-                        $where_cols_n_values = array(
2378
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
-                        );
2377
+						$where_cols_n_values = array(
2378
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
+						);
2380 2380
                         
2381
-                        $message_template_fields = array(
2382
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2383
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
-                            'MTP_context'        => $set_column_values['MTP_context'],
2385
-                            'MTP_content'        => $set_column_values['MTP_content']
2386
-                        );
2387
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
-                            if ($updated === false) {
2389
-                                EE_Error::add_error(
2390
-                                    sprintf(
2391
-                                        __('%s field was NOT updated for some reason', 'event_espresso'),
2392
-                                        $template_field
2393
-                                    ),
2394
-                                    __FILE__, __FUNCTION__, __LINE__
2395
-                                );
2396
-                            } else {
2397
-                                $success = 1;
2398
-                            }
2399
-                        }
2400
-                        $action_desc = 'updated';
2401
-                    }
2381
+						$message_template_fields = array(
2382
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2383
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
+							'MTP_context'        => $set_column_values['MTP_context'],
2385
+							'MTP_content'        => $set_column_values['MTP_content']
2386
+						);
2387
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
+							if ($updated === false) {
2389
+								EE_Error::add_error(
2390
+									sprintf(
2391
+										__('%s field was NOT updated for some reason', 'event_espresso'),
2392
+										$template_field
2393
+									),
2394
+									__FILE__, __FUNCTION__, __LINE__
2395
+								);
2396
+							} else {
2397
+								$success = 1;
2398
+							}
2399
+						}
2400
+						$action_desc = 'updated';
2401
+					}
2402 2402
                     
2403
-                    //we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
-                    $mtpg_fields = array(
2405
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
-                            : '',
2415
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
-                            : ''
2418
-                    );
2403
+					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
+					$mtpg_fields = array(
2405
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
+							: '',
2415
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
+							: ''
2418
+					);
2419 2419
                     
2420
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
-                    $updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2420
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
+					$updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2422 2422
                     
2423
-                    if ($updated === false) {
2424
-                        EE_Error::add_error(
2425
-                            sprintf(
2426
-                                __('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
-                                $set_column_values['GRP_ID']
2428
-                            ),
2429
-                            __FILE__, __FUNCTION__, __LINE__
2430
-                        );
2431
-                    } else {
2432
-                        //k now we need to ensure the template_pack and template_variation fields are set.
2433
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
-                            ? $this->_req_data['MTP_template_pack']
2435
-                            : 'default';
2423
+					if ($updated === false) {
2424
+						EE_Error::add_error(
2425
+							sprintf(
2426
+								__('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
+								$set_column_values['GRP_ID']
2428
+							),
2429
+							__FILE__, __FUNCTION__, __LINE__
2430
+						);
2431
+					} else {
2432
+						//k now we need to ensure the template_pack and template_variation fields are set.
2433
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
+							? $this->_req_data['MTP_template_pack']
2435
+							: 'default';
2436 2436
                         
2437
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
-                            ? $this->_req_data['MTP_template_variation']
2439
-                            : 'default';
2437
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
+							? $this->_req_data['MTP_template_variation']
2439
+							: 'default';
2440 2440
                         
2441
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
-                            $mtpg_obj->set_template_pack_name($template_pack);
2444
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2445
-                        }
2446
-                        $success = 1;
2447
-                    }
2448
-                }
2449
-            }
2441
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
+							$mtpg_obj->set_template_pack_name($template_pack);
2444
+							$mtpg_obj->set_template_pack_variation($template_variation);
2445
+						}
2446
+						$success = 1;
2447
+					}
2448
+				}
2449
+			}
2450 2450
             
2451
-        }
2452
-        
2453
-        //we return things differently if doing ajax
2454
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2455
-            $this->_template_args['success'] = $success;
2456
-            $this->_template_args['error']   = ! $success ? true : false;
2457
-            $this->_template_args['content'] = '';
2458
-            $this->_template_args['data']    = array(
2459
-                'grpID'        => $edit_array['GRP_ID'],
2460
-                'templateName' => $edit_array['template_name']
2461
-            );
2462
-            if ($success) {
2463
-                EE_Error::overwrite_success();
2464
-                EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2465
-                    'event_espresso'));
2466
-            }
2451
+		}
2452
+        
2453
+		//we return things differently if doing ajax
2454
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2455
+			$this->_template_args['success'] = $success;
2456
+			$this->_template_args['error']   = ! $success ? true : false;
2457
+			$this->_template_args['content'] = '';
2458
+			$this->_template_args['data']    = array(
2459
+				'grpID'        => $edit_array['GRP_ID'],
2460
+				'templateName' => $edit_array['template_name']
2461
+			);
2462
+			if ($success) {
2463
+				EE_Error::overwrite_success();
2464
+				EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2465
+					'event_espresso'));
2466
+			}
2467 2467
             
2468
-            $this->_return_json();
2469
-        }
2470
-        
2471
-        
2472
-        //was a test send triggered?
2473
-        if (isset($this->_req_data['test_button'])) {
2474
-            EE_Error::overwrite_success();
2475
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
-            $override = true;
2477
-        }
2478
-        
2479
-        if (empty($query_args)) {
2480
-            $query_args = array(
2481
-                'id'      => $this->_req_data['GRP_ID'],
2482
-                'context' => $context_slug,
2483
-                'action'  => 'edit_message_template'
2484
-            );
2485
-        }
2486
-        
2487
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
-    }
2489
-    
2490
-    
2491
-    /**
2492
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
-     *
2494
-     * @param  string $context      what context being tested
2495
-     * @param  string $messenger    messenger being tested
2496
-     * @param  string $message_type message type being tested
2497
-     *
2498
-     */
2499
-    protected function _do_test_send($context, $messenger, $message_type)
2500
-    {
2501
-        //set things up for preview
2502
-        $this->_req_data['messenger']    = $messenger;
2503
-        $this->_req_data['message_type'] = $message_type;
2504
-        $this->_req_data['context']      = $context;
2505
-        $this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
-        $active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
-        
2508
-        //let's save any existing fields that might be required by the messenger
2509
-        if (
2510
-            isset($this->_req_data['test_settings_fld'])
2511
-            && $active_messenger instanceof EE_messenger
2512
-            && apply_filters(
2513
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2514
-                true,
2515
-                $this->_req_data['test_settings_fld'],
2516
-                $active_messenger
2517
-            )
2518
-        ) {
2519
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2520
-        }
2521
-        
2522
-        $success = $this->_preview_message(true);
2523
-        
2524
-        if ($success) {
2525
-            EE_Error::add_success(__('Test message sent', 'event_espresso'));
2526
-        } else {
2527
-            EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2528
-                __LINE__);
2529
-        }
2530
-    }
2531
-    
2532
-    
2533
-    /**
2534
-     * _generate_new_templates
2535
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2536
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2537
-     * for the event.
2538
-     *
2539
-     *
2540
-     * @param  string $messenger     the messenger we are generating templates for
2541
-     * @param array   $message_types array of message types that the templates are generated for.
2542
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2543
-     *                               indicate the message_template_group being used as the base.
2544
-     *
2545
-     * @param bool    $global
2546
-     *
2547
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
2548
-     *                               encountering problems.
2549
-     * @throws \EE_Error
2550
-     */
2551
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2552
-    {
2553
-        
2554
-        //if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2555
-        if (empty($message_types)) {
2556
-            return true;
2557
-        }
2558
-        
2559
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2560
-    }
2561
-    
2562
-    
2563
-    /**
2564
-     * [_trash_or_restore_message_template]
2565
-     *
2566
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2567
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2568
-     *                        an individual context (FALSE).
2569
-     *
2570
-     * @return void
2571
-     */
2572
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
2573
-    {
2574
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2575
-        $MTP = EEM_Message_Template_Group::instance();
2576
-        
2577
-        $success = 1;
2578
-        
2579
-        //incoming GRP_IDs
2580
-        if ($all) {
2581
-            //Checkboxes
2582
-            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2583
-                //if array has more than one element then success message should be plural.
2584
-                //todo: what about nonce?
2585
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2468
+			$this->_return_json();
2469
+		}
2470
+        
2471
+        
2472
+		//was a test send triggered?
2473
+		if (isset($this->_req_data['test_button'])) {
2474
+			EE_Error::overwrite_success();
2475
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
+			$override = true;
2477
+		}
2478
+        
2479
+		if (empty($query_args)) {
2480
+			$query_args = array(
2481
+				'id'      => $this->_req_data['GRP_ID'],
2482
+				'context' => $context_slug,
2483
+				'action'  => 'edit_message_template'
2484
+			);
2485
+		}
2486
+        
2487
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
+	}
2489
+    
2490
+    
2491
+	/**
2492
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
+	 *
2494
+	 * @param  string $context      what context being tested
2495
+	 * @param  string $messenger    messenger being tested
2496
+	 * @param  string $message_type message type being tested
2497
+	 *
2498
+	 */
2499
+	protected function _do_test_send($context, $messenger, $message_type)
2500
+	{
2501
+		//set things up for preview
2502
+		$this->_req_data['messenger']    = $messenger;
2503
+		$this->_req_data['message_type'] = $message_type;
2504
+		$this->_req_data['context']      = $context;
2505
+		$this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
+		$active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
+        
2508
+		//let's save any existing fields that might be required by the messenger
2509
+		if (
2510
+			isset($this->_req_data['test_settings_fld'])
2511
+			&& $active_messenger instanceof EE_messenger
2512
+			&& apply_filters(
2513
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2514
+				true,
2515
+				$this->_req_data['test_settings_fld'],
2516
+				$active_messenger
2517
+			)
2518
+		) {
2519
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2520
+		}
2521
+        
2522
+		$success = $this->_preview_message(true);
2523
+        
2524
+		if ($success) {
2525
+			EE_Error::add_success(__('Test message sent', 'event_espresso'));
2526
+		} else {
2527
+			EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2528
+				__LINE__);
2529
+		}
2530
+	}
2531
+    
2532
+    
2533
+	/**
2534
+	 * _generate_new_templates
2535
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2536
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2537
+	 * for the event.
2538
+	 *
2539
+	 *
2540
+	 * @param  string $messenger     the messenger we are generating templates for
2541
+	 * @param array   $message_types array of message types that the templates are generated for.
2542
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2543
+	 *                               indicate the message_template_group being used as the base.
2544
+	 *
2545
+	 * @param bool    $global
2546
+	 *
2547
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2548
+	 *                               encountering problems.
2549
+	 * @throws \EE_Error
2550
+	 */
2551
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2552
+	{
2553
+        
2554
+		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2555
+		if (empty($message_types)) {
2556
+			return true;
2557
+		}
2558
+        
2559
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2560
+	}
2561
+    
2562
+    
2563
+	/**
2564
+	 * [_trash_or_restore_message_template]
2565
+	 *
2566
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2567
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2568
+	 *                        an individual context (FALSE).
2569
+	 *
2570
+	 * @return void
2571
+	 */
2572
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
2573
+	{
2574
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2575
+		$MTP = EEM_Message_Template_Group::instance();
2576
+        
2577
+		$success = 1;
2578
+        
2579
+		//incoming GRP_IDs
2580
+		if ($all) {
2581
+			//Checkboxes
2582
+			if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2583
+				//if array has more than one element then success message should be plural.
2584
+				//todo: what about nonce?
2585
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2586 2586
                 
2587
-                //cycle through checkboxes
2588
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2589
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2590
-                    if ( ! $trashed_or_restored) {
2591
-                        $success = 0;
2592
-                    }
2593
-                }
2594
-            } else {
2595
-                //grab single GRP_ID and handle
2596
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2597
-                if ( ! empty($GRP_ID)) {
2598
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
-                    if ( ! $trashed_or_restored) {
2600
-                        $success = 0;
2601
-                    }
2602
-                } else {
2603
-                    $success = 0;
2604
-                }
2605
-            }
2587
+				//cycle through checkboxes
2588
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2589
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2590
+					if ( ! $trashed_or_restored) {
2591
+						$success = 0;
2592
+					}
2593
+				}
2594
+			} else {
2595
+				//grab single GRP_ID and handle
2596
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2597
+				if ( ! empty($GRP_ID)) {
2598
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
+					if ( ! $trashed_or_restored) {
2600
+						$success = 0;
2601
+					}
2602
+				} else {
2603
+					$success = 0;
2604
+				}
2605
+			}
2606 2606
             
2607
-        }
2607
+		}
2608 2608
         
2609
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2609
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2610 2610
         
2611
-        $action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2611
+		$action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2612 2612
         
2613
-        $item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2614
-            'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2613
+		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2614
+			'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2615 2615
         
2616
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2617
-            'event_espresso') : $item_desc;
2616
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2617
+			'event_espresso') : $item_desc;
2618 2618
         
2619
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
2619
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
2620 2620
         
2621
-    }
2621
+	}
2622 2622
     
2623 2623
     
2624
-    /**
2625
-     * [_delete_message_template]
2626
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2627
-     * @return void
2628
-     */
2629
-    protected function _delete_message_template()
2630
-    {
2631
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2624
+	/**
2625
+	 * [_delete_message_template]
2626
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2627
+	 * @return void
2628
+	 */
2629
+	protected function _delete_message_template()
2630
+	{
2631
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2632 2632
         
2633
-        //checkboxes
2634
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2635
-            //if array has more than one element then success message should be plural
2636
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2633
+		//checkboxes
2634
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2635
+			//if array has more than one element then success message should be plural
2636
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2637 2637
             
2638
-            //cycle through bulk action checkboxes
2639
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2640
-                $success = $this->_delete_mtp_permanently($GRP_ID);
2641
-            }
2642
-        } else {
2643
-            //grab single grp_id and delete
2644
-            $GRP_ID  = absint($this->_req_data['id']);
2645
-            $success = $this->_delete_mtp_permanently($GRP_ID);
2646
-        }
2647
-        
2648
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2649
-        
2650
-    }
2651
-    
2652
-    
2653
-    /**
2654
-     * helper for permanently deleting a mtP group and all related message_templates
2655
-     *
2656
-     * @param  int  $GRP_ID        The group being deleted
2657
-     * @param  bool $include_group whether to delete the Message Template Group as well.
2658
-     *
2659
-     * @return bool        boolean to indicate the success of the deletes or not.
2660
-     */
2661
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2662
-    {
2663
-        $success = 1;
2664
-        $MTPG    = EEM_Message_Template_Group::instance();
2665
-        //first let's GET this group
2666
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
2667
-        //then delete permanently all the related Message Templates
2668
-        $deleted = $MTG->delete_related_permanently('Message_Template');
2669
-        
2670
-        if ($deleted === 0) {
2671
-            $success = 0;
2672
-        }
2673
-        
2674
-        //now delete permanently this particular group
2675
-        
2676
-        if ($include_group && ! $MTG->delete_permanently()) {
2677
-            $success = 0;
2678
-        }
2679
-        
2680
-        return $success;
2681
-    }
2682
-    
2683
-    
2684
-    /**
2685
-     *    _learn_more_about_message_templates_link
2686
-     * @access protected
2687
-     * @return string
2688
-     */
2689
-    protected function _learn_more_about_message_templates_link()
2690
-    {
2691
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2692
-            'event_espresso') . '</a>';
2693
-    }
2694
-    
2695
-    
2696
-    /**
2697
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2698
-     * ajax and other routes.
2699
-     * @return void
2700
-     */
2701
-    protected function _settings()
2702
-    {
2703
-        
2704
-        
2705
-        $this->_set_m_mt_settings();
2706
-        
2707
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2708
-        
2709
-        //let's setup the messenger tabs
2710
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2711
-            'messenger_links', '|', $selected_messenger);
2712
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2713
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2714
-        
2715
-        $this->display_admin_page_with_sidebar();
2716
-        
2717
-    }
2718
-    
2719
-    
2720
-    /**
2721
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2722
-     *
2723
-     * @access protected
2724
-     * @return void
2725
-     */
2726
-    protected function _set_m_mt_settings()
2727
-    {
2728
-        //first if this is already set then lets get out no need to regenerate data.
2729
-        if ( ! empty($this->_m_mt_settings)) {
2730
-            return;
2731
-        }
2732
-        
2733
-        //$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2734
-        
2735
-        //get all installed messengers and message_types
2736
-        /** @type EE_messenger[] $messengers */
2737
-        $messengers = $this->_message_resource_manager->installed_messengers();
2738
-        /** @type EE_message_type[] $message_types */
2739
-        $message_types = $this->_message_resource_manager->installed_message_types();
2740
-        
2741
-        
2742
-        //assemble the array for the _tab_text_links helper
2743
-        
2744
-        foreach ($messengers as $messenger) {
2745
-            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2746
-                'label' => ucwords($messenger->label['singular']),
2747
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2748
-                'href'  => $messenger->name,
2749
-                'title' => __('Modify this Messenger', 'event_espresso'),
2750
-                'slug'  => $messenger->name,
2751
-                'obj'   => $messenger
2752
-            );
2638
+			//cycle through bulk action checkboxes
2639
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2640
+				$success = $this->_delete_mtp_permanently($GRP_ID);
2641
+			}
2642
+		} else {
2643
+			//grab single grp_id and delete
2644
+			$GRP_ID  = absint($this->_req_data['id']);
2645
+			$success = $this->_delete_mtp_permanently($GRP_ID);
2646
+		}
2647
+        
2648
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2649
+        
2650
+	}
2651
+    
2652
+    
2653
+	/**
2654
+	 * helper for permanently deleting a mtP group and all related message_templates
2655
+	 *
2656
+	 * @param  int  $GRP_ID        The group being deleted
2657
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
2658
+	 *
2659
+	 * @return bool        boolean to indicate the success of the deletes or not.
2660
+	 */
2661
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2662
+	{
2663
+		$success = 1;
2664
+		$MTPG    = EEM_Message_Template_Group::instance();
2665
+		//first let's GET this group
2666
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
2667
+		//then delete permanently all the related Message Templates
2668
+		$deleted = $MTG->delete_related_permanently('Message_Template');
2669
+        
2670
+		if ($deleted === 0) {
2671
+			$success = 0;
2672
+		}
2673
+        
2674
+		//now delete permanently this particular group
2675
+        
2676
+		if ($include_group && ! $MTG->delete_permanently()) {
2677
+			$success = 0;
2678
+		}
2679
+        
2680
+		return $success;
2681
+	}
2682
+    
2683
+    
2684
+	/**
2685
+	 *    _learn_more_about_message_templates_link
2686
+	 * @access protected
2687
+	 * @return string
2688
+	 */
2689
+	protected function _learn_more_about_message_templates_link()
2690
+	{
2691
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2692
+			'event_espresso') . '</a>';
2693
+	}
2694
+    
2695
+    
2696
+	/**
2697
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2698
+	 * ajax and other routes.
2699
+	 * @return void
2700
+	 */
2701
+	protected function _settings()
2702
+	{
2703
+        
2704
+        
2705
+		$this->_set_m_mt_settings();
2706
+        
2707
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2708
+        
2709
+		//let's setup the messenger tabs
2710
+		$this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2711
+			'messenger_links', '|', $selected_messenger);
2712
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2713
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2714
+        
2715
+		$this->display_admin_page_with_sidebar();
2716
+        
2717
+	}
2718
+    
2719
+    
2720
+	/**
2721
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2722
+	 *
2723
+	 * @access protected
2724
+	 * @return void
2725
+	 */
2726
+	protected function _set_m_mt_settings()
2727
+	{
2728
+		//first if this is already set then lets get out no need to regenerate data.
2729
+		if ( ! empty($this->_m_mt_settings)) {
2730
+			return;
2731
+		}
2732
+        
2733
+		//$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2734
+        
2735
+		//get all installed messengers and message_types
2736
+		/** @type EE_messenger[] $messengers */
2737
+		$messengers = $this->_message_resource_manager->installed_messengers();
2738
+		/** @type EE_message_type[] $message_types */
2739
+		$message_types = $this->_message_resource_manager->installed_message_types();
2740
+        
2741
+        
2742
+		//assemble the array for the _tab_text_links helper
2743
+        
2744
+		foreach ($messengers as $messenger) {
2745
+			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2746
+				'label' => ucwords($messenger->label['singular']),
2747
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2748
+				'href'  => $messenger->name,
2749
+				'title' => __('Modify this Messenger', 'event_espresso'),
2750
+				'slug'  => $messenger->name,
2751
+				'obj'   => $messenger
2752
+			);
2753 2753
             
2754 2754
             
2755
-            $message_types_for_messenger = $messenger->get_valid_message_types();
2755
+			$message_types_for_messenger = $messenger->get_valid_message_types();
2756 2756
             
2757
-            foreach ($message_types as $message_type) {
2758
-                //first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2759
-                if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2760
-                    continue;
2761
-                }
2757
+			foreach ($message_types as $message_type) {
2758
+				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2759
+				if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2760
+					continue;
2761
+				}
2762 2762
                 
2763
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2764
-                    $message_type->name) ? 'active' : 'inactive';
2763
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2764
+					$message_type->name) ? 'active' : 'inactive';
2765 2765
                 
2766
-                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2767
-                    'label'    => ucwords($message_type->label['singular']),
2768
-                    'class'    => 'message-type-' . $a_or_i,
2769
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2770
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2771
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2772
-                    'title'    => $a_or_i == 'active'
2773
-                        ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2774
-                        : __('Drag this message type to the messenger to activate', 'event_espresso'),
2775
-                    'content'  => $a_or_i == 'active'
2776
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
2777
-                        : $this->_message_type_settings_content($message_type, $messenger),
2778
-                    'slug'     => $message_type->name,
2779
-                    'active'   => $a_or_i == 'active' ? true : false,
2780
-                    'obj'      => $message_type
2781
-                );
2782
-            }
2783
-        }
2784
-    }
2785
-    
2786
-    
2787
-    /**
2788
-     * This just prepares the content for the message type settings
2789
-     *
2790
-     * @param  object  $message_type The message type object
2791
-     * @param  object  $messenger    The messenger object
2792
-     * @param  boolean $active       Whether the message type is active or not
2793
-     *
2794
-     * @return string                html output for the content
2795
-     */
2796
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
2797
-    {
2798
-        //get message type fields
2799
-        $fields                                         = $message_type->get_admin_settings_fields();
2800
-        $settings_template_args['template_form_fields'] = '';
2801
-        
2802
-        if ( ! empty($fields) && $active) {
2766
+				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2767
+					'label'    => ucwords($message_type->label['singular']),
2768
+					'class'    => 'message-type-' . $a_or_i,
2769
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2770
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2771
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2772
+					'title'    => $a_or_i == 'active'
2773
+						? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2774
+						: __('Drag this message type to the messenger to activate', 'event_espresso'),
2775
+					'content'  => $a_or_i == 'active'
2776
+						? $this->_message_type_settings_content($message_type, $messenger, true)
2777
+						: $this->_message_type_settings_content($message_type, $messenger),
2778
+					'slug'     => $message_type->name,
2779
+					'active'   => $a_or_i == 'active' ? true : false,
2780
+					'obj'      => $message_type
2781
+				);
2782
+			}
2783
+		}
2784
+	}
2785
+    
2786
+    
2787
+	/**
2788
+	 * This just prepares the content for the message type settings
2789
+	 *
2790
+	 * @param  object  $message_type The message type object
2791
+	 * @param  object  $messenger    The messenger object
2792
+	 * @param  boolean $active       Whether the message type is active or not
2793
+	 *
2794
+	 * @return string                html output for the content
2795
+	 */
2796
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
2797
+	{
2798
+		//get message type fields
2799
+		$fields                                         = $message_type->get_admin_settings_fields();
2800
+		$settings_template_args['template_form_fields'] = '';
2801
+        
2802
+		if ( ! empty($fields) && $active) {
2803 2803
             
2804
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2804
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2805 2805
             
2806
-            foreach ($fields as $fldname => $fldprops) {
2807
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2808
-                $template_form_field[$field_id] = array(
2809
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2810
-                    'label'      => $fldprops['label'],
2811
-                    'input'      => $fldprops['field_type'],
2812
-                    'type'       => $fldprops['value_type'],
2813
-                    'required'   => $fldprops['required'],
2814
-                    'validation' => $fldprops['validation'],
2815
-                    'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2816
-                    'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2817
-                    'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2818
-                    'css_class'  => 'no-drag',
2819
-                    'format'     => $fldprops['format']
2820
-                );
2821
-            }
2806
+			foreach ($fields as $fldname => $fldprops) {
2807
+				$field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2808
+				$template_form_field[$field_id] = array(
2809
+					'name'       => 'message_type_settings[' . $fldname . ']',
2810
+					'label'      => $fldprops['label'],
2811
+					'input'      => $fldprops['field_type'],
2812
+					'type'       => $fldprops['value_type'],
2813
+					'required'   => $fldprops['required'],
2814
+					'validation' => $fldprops['validation'],
2815
+					'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2816
+					'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2817
+					'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2818
+					'css_class'  => 'no-drag',
2819
+					'format'     => $fldprops['format']
2820
+				);
2821
+			}
2822 2822
             
2823 2823
             
2824
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2825
-                'string', 'ee_mt_activate_form') : '';
2826
-        }
2827
-        
2828
-        $settings_template_args['description'] = $message_type->description;
2829
-        //we also need some hidden fields
2830
-        $settings_template_args['hidden_fields'] = array(
2831
-            'message_type_settings[messenger]'    => array(
2832
-                'type'  => 'hidden',
2833
-                'value' => $messenger->name
2834
-            ),
2835
-            'message_type_settings[message_type]' => array(
2836
-                'type'  => 'hidden',
2837
-                'value' => $message_type->name
2838
-            ),
2839
-            'type'                                => array(
2840
-                'type'  => 'hidden',
2841
-                'value' => 'message_type'
2842
-            )
2843
-        );
2844
-        
2845
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2846
-            'array');
2847
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2848
-        
2849
-        
2850
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2851
-        $content  = EEH_Template::display_template($template, $settings_template_args, true);
2852
-        
2853
-        return $content;
2854
-    }
2855
-    
2856
-    
2857
-    /**
2858
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
2859
-     *
2860
-     * @access protected
2861
-     * @return void
2862
-     */
2863
-    protected function _messages_settings_metaboxes()
2864
-    {
2865
-        $this->_set_m_mt_settings();
2866
-        $m_boxes         = $mt_boxes = array();
2867
-        $m_template_args = $mt_template_args = array();
2868
-        
2869
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2870
-        
2871
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
2872
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2873
-                $hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2874
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2875
-                //messenger meta boxes
2876
-                $active                                 = $selected_messenger == $messenger ? true : false;
2877
-                $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2878
-                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2879
-                    : '';
2880
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2881
-                    __('%s Settings', 'event_espresso'),
2882
-                    $tab_array['label']
2883
-                );
2884
-                $m_template_args[$messenger . '_a_box'] = array(
2885
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2886
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2887
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2888
-                        : '',
2889
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2890
-                    'hidden'                 => $active ? '' : ' hidden',
2891
-                    'hide_on_message'        => $hide_on_message,
2892
-                    'messenger'              => $messenger,
2893
-                    'active'                 => $active
2894
-                );
2895
-                // message type meta boxes
2896
-                // (which is really just the inactive container for each messenger
2897
-                // showing inactive message types for that messenger)
2898
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2899
-                $mt_template_args[$messenger . '_i_box'] = array(
2900
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2901
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2902
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2903
-                        : '',
2904
-                    'hidden'                 => $active ? '' : ' hidden',
2905
-                    'hide_on_message'        => $hide_on_message,
2906
-                    'hide_off_message'       => $hide_off_message,
2907
-                    'messenger'              => $messenger,
2908
-                    'active'                 => $active
2909
-                );
2910
-            }
2911
-        }
2912
-        
2913
-        
2914
-        //register messenger metaboxes
2915
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2916
-        foreach ($m_boxes as $box => $label) {
2917
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2918
-            $msgr          = str_replace('_a_box', '', $box);
2919
-            add_meta_box(
2920
-                'espresso_' . $msgr . '_settings',
2921
-                $label,
2922
-                function ($post, $metabox) {
2923
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2924
-                        $metabox["args"]["template_args"], true);
2925
-                },
2926
-                $this->_current_screen->id,
2927
-                'normal',
2928
-                'high',
2929
-                $callback_args
2930
-            );
2931
-        }
2932
-        
2933
-        //register message type metaboxes
2934
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2935
-        foreach ($mt_boxes as $box => $label) {
2936
-            $callback_args = array(
2937
-                'template_path' => $mt_template_path,
2938
-                'template_args' => $mt_template_args[$box]
2939
-            );
2940
-            $mt            = str_replace('_i_box', '', $box);
2941
-            add_meta_box(
2942
-                'espresso_' . $mt . '_inactive_mts',
2943
-                $label,
2944
-                function ($post, $metabox) {
2945
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2946
-                        $metabox["args"]["template_args"], true);
2947
-                },
2948
-                $this->_current_screen->id,
2949
-                'side',
2950
-                'high',
2951
-                $callback_args
2952
-            );
2953
-        }
2954
-        
2955
-        //register metabox for global messages settings but only when on the main site.  On single site installs this will
2956
-        //always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2957
-        if (is_main_site()) {
2958
-            add_meta_box(
2959
-                'espresso_global_message_settings',
2960
-                __('Global Message Settings', 'event_espresso'),
2961
-                array($this, 'global_messages_settings_metabox_content'),
2962
-                $this->_current_screen->id,
2963
-                'normal',
2964
-                'low',
2965
-                array()
2966
-            );
2967
-        }
2968
-        
2969
-    }
2970
-    
2971
-    
2972
-    /**
2973
-     *  This generates the content for the global messages settings metabox.
2974
-     * @return string
2975
-     */
2976
-    public function global_messages_settings_metabox_content()
2977
-    {
2978
-        $form = $this->_generate_global_settings_form();
2979
-        echo $form->form_open(
2980
-                $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2981
-                'POST'
2982
-            )
2983
-             . $form->get_html()
2984
-             . $form->form_close();
2985
-    }
2986
-    
2987
-    
2988
-    /**
2989
-     * This generates and returns the form object for the global messages settings.
2990
-     * @return EE_Form_Section_Proper
2991
-     */
2992
-    protected function _generate_global_settings_form()
2993
-    {
2994
-        EE_Registry::instance()->load_helper('HTML');
2995
-        /** @var EE_Network_Core_Config $network_config */
2996
-        $network_config = EE_Registry::instance()->NET_CFG->core;
2997
-        
2998
-        return new EE_Form_Section_Proper(
2999
-            array(
3000
-                'name'            => 'global_messages_settings',
3001
-                'html_id'         => 'global_messages_settings',
3002
-                'html_class'      => 'form-table',
3003
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3004
-                'subsections'     => apply_filters(
3005
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3006
-                    array(
3007
-                        'do_messages_on_same_request' => new EE_Select_Input(
3008
-                            array(
3009
-                                true  => __("On the same request", "event_espresso"),
3010
-                                false => __("On a separate request", "event_espresso")
3011
-                            ),
3012
-                            array(
3013
-                                'default'         => $network_config->do_messages_on_same_request,
3014
-                                'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3015
-                                'html_help_text'  => __('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3016
-                                    'event_espresso'),
3017
-                            )
3018
-                        ),
3019
-                        'update_settings'             => new EE_Submit_Input(
3020
-                            array(
3021
-                                'default'         => __('Update', 'event_espresso'),
3022
-                                'html_label_text' => '&nbsp'
3023
-                            )
3024
-                        )
3025
-                    )
3026
-                )
3027
-            )
3028
-        );
3029
-    }
3030
-    
3031
-    
3032
-    /**
3033
-     * This handles updating the global settings set on the admin page.
3034
-     * @throws \EE_Error
3035
-     */
3036
-    protected function _update_global_settings()
3037
-    {
3038
-        /** @var EE_Network_Core_Config $network_config */
3039
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3040
-        $form           = $this->_generate_global_settings_form();
3041
-        if ($form->was_submitted()) {
3042
-            $form->receive_form_submission();
3043
-            if ($form->is_valid()) {
3044
-                $valid_data = $form->valid_data();
3045
-                foreach ($valid_data as $property => $value) {
3046
-                    $setter = 'set_' . $property;
3047
-                    if (method_exists($network_config, $setter)) {
3048
-                        $network_config->{$setter}($value);
3049
-                    } else if (
3050
-                        property_exists($network_config, $property)
3051
-                        && $network_config->{$property} !== $value
3052
-                    ) {
3053
-                        $network_config->{$property} = $value;
3054
-                    }
3055
-                }
3056
-                //only update if the form submission was valid!
3057
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3058
-                EE_Error::overwrite_success();
3059
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3060
-            }
3061
-        }
3062
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3063
-    }
3064
-    
3065
-    
3066
-    /**
3067
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3068
-     *
3069
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3070
-     *
3071
-     * @return string            html formatted tabs
3072
-     */
3073
-    protected function _get_mt_tabs($tab_array)
3074
-    {
3075
-        $tab_array = (array)$tab_array;
3076
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3077
-        $tabs      = '';
3078
-        
3079
-        foreach ($tab_array as $tab) {
3080
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3081
-        }
3082
-        
3083
-        return $tabs;
3084
-    }
3085
-    
3086
-    
3087
-    /**
3088
-     * This prepares the content of the messenger meta box admin settings
3089
-     *
3090
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3091
-     *
3092
-     * @return string            html formatted content
3093
-     */
3094
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3095
-    {
3096
-        
3097
-        $fields                                         = $messenger->get_admin_settings_fields();
3098
-        $settings_template_args['template_form_fields'] = '';
3099
-        
3100
-        //is $messenger active?
3101
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3102
-        
3103
-        
3104
-        if ( ! empty($fields)) {
2824
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2825
+				'string', 'ee_mt_activate_form') : '';
2826
+		}
2827
+        
2828
+		$settings_template_args['description'] = $message_type->description;
2829
+		//we also need some hidden fields
2830
+		$settings_template_args['hidden_fields'] = array(
2831
+			'message_type_settings[messenger]'    => array(
2832
+				'type'  => 'hidden',
2833
+				'value' => $messenger->name
2834
+			),
2835
+			'message_type_settings[message_type]' => array(
2836
+				'type'  => 'hidden',
2837
+				'value' => $message_type->name
2838
+			),
2839
+			'type'                                => array(
2840
+				'type'  => 'hidden',
2841
+				'value' => 'message_type'
2842
+			)
2843
+		);
2844
+        
2845
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2846
+			'array');
2847
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2848
+        
2849
+        
2850
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2851
+		$content  = EEH_Template::display_template($template, $settings_template_args, true);
2852
+        
2853
+		return $content;
2854
+	}
2855
+    
2856
+    
2857
+	/**
2858
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
2859
+	 *
2860
+	 * @access protected
2861
+	 * @return void
2862
+	 */
2863
+	protected function _messages_settings_metaboxes()
2864
+	{
2865
+		$this->_set_m_mt_settings();
2866
+		$m_boxes         = $mt_boxes = array();
2867
+		$m_template_args = $mt_template_args = array();
2868
+        
2869
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2870
+        
2871
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
2872
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2873
+				$hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2874
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2875
+				//messenger meta boxes
2876
+				$active                                 = $selected_messenger == $messenger ? true : false;
2877
+				$active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2878
+					? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2879
+					: '';
2880
+				$m_boxes[$messenger . '_a_box']         = sprintf(
2881
+					__('%s Settings', 'event_espresso'),
2882
+					$tab_array['label']
2883
+				);
2884
+				$m_template_args[$messenger . '_a_box'] = array(
2885
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2886
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2887
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2888
+						: '',
2889
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2890
+					'hidden'                 => $active ? '' : ' hidden',
2891
+					'hide_on_message'        => $hide_on_message,
2892
+					'messenger'              => $messenger,
2893
+					'active'                 => $active
2894
+				);
2895
+				// message type meta boxes
2896
+				// (which is really just the inactive container for each messenger
2897
+				// showing inactive message types for that messenger)
2898
+				$mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2899
+				$mt_template_args[$messenger . '_i_box'] = array(
2900
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2901
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2902
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2903
+						: '',
2904
+					'hidden'                 => $active ? '' : ' hidden',
2905
+					'hide_on_message'        => $hide_on_message,
2906
+					'hide_off_message'       => $hide_off_message,
2907
+					'messenger'              => $messenger,
2908
+					'active'                 => $active
2909
+				);
2910
+			}
2911
+		}
2912
+        
2913
+        
2914
+		//register messenger metaboxes
2915
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2916
+		foreach ($m_boxes as $box => $label) {
2917
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2918
+			$msgr          = str_replace('_a_box', '', $box);
2919
+			add_meta_box(
2920
+				'espresso_' . $msgr . '_settings',
2921
+				$label,
2922
+				function ($post, $metabox) {
2923
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2924
+						$metabox["args"]["template_args"], true);
2925
+				},
2926
+				$this->_current_screen->id,
2927
+				'normal',
2928
+				'high',
2929
+				$callback_args
2930
+			);
2931
+		}
2932
+        
2933
+		//register message type metaboxes
2934
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2935
+		foreach ($mt_boxes as $box => $label) {
2936
+			$callback_args = array(
2937
+				'template_path' => $mt_template_path,
2938
+				'template_args' => $mt_template_args[$box]
2939
+			);
2940
+			$mt            = str_replace('_i_box', '', $box);
2941
+			add_meta_box(
2942
+				'espresso_' . $mt . '_inactive_mts',
2943
+				$label,
2944
+				function ($post, $metabox) {
2945
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2946
+						$metabox["args"]["template_args"], true);
2947
+				},
2948
+				$this->_current_screen->id,
2949
+				'side',
2950
+				'high',
2951
+				$callback_args
2952
+			);
2953
+		}
2954
+        
2955
+		//register metabox for global messages settings but only when on the main site.  On single site installs this will
2956
+		//always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2957
+		if (is_main_site()) {
2958
+			add_meta_box(
2959
+				'espresso_global_message_settings',
2960
+				__('Global Message Settings', 'event_espresso'),
2961
+				array($this, 'global_messages_settings_metabox_content'),
2962
+				$this->_current_screen->id,
2963
+				'normal',
2964
+				'low',
2965
+				array()
2966
+			);
2967
+		}
2968
+        
2969
+	}
2970
+    
2971
+    
2972
+	/**
2973
+	 *  This generates the content for the global messages settings metabox.
2974
+	 * @return string
2975
+	 */
2976
+	public function global_messages_settings_metabox_content()
2977
+	{
2978
+		$form = $this->_generate_global_settings_form();
2979
+		echo $form->form_open(
2980
+				$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2981
+				'POST'
2982
+			)
2983
+			 . $form->get_html()
2984
+			 . $form->form_close();
2985
+	}
2986
+    
2987
+    
2988
+	/**
2989
+	 * This generates and returns the form object for the global messages settings.
2990
+	 * @return EE_Form_Section_Proper
2991
+	 */
2992
+	protected function _generate_global_settings_form()
2993
+	{
2994
+		EE_Registry::instance()->load_helper('HTML');
2995
+		/** @var EE_Network_Core_Config $network_config */
2996
+		$network_config = EE_Registry::instance()->NET_CFG->core;
2997
+        
2998
+		return new EE_Form_Section_Proper(
2999
+			array(
3000
+				'name'            => 'global_messages_settings',
3001
+				'html_id'         => 'global_messages_settings',
3002
+				'html_class'      => 'form-table',
3003
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3004
+				'subsections'     => apply_filters(
3005
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3006
+					array(
3007
+						'do_messages_on_same_request' => new EE_Select_Input(
3008
+							array(
3009
+								true  => __("On the same request", "event_espresso"),
3010
+								false => __("On a separate request", "event_espresso")
3011
+							),
3012
+							array(
3013
+								'default'         => $network_config->do_messages_on_same_request,
3014
+								'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3015
+								'html_help_text'  => __('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3016
+									'event_espresso'),
3017
+							)
3018
+						),
3019
+						'update_settings'             => new EE_Submit_Input(
3020
+							array(
3021
+								'default'         => __('Update', 'event_espresso'),
3022
+								'html_label_text' => '&nbsp'
3023
+							)
3024
+						)
3025
+					)
3026
+				)
3027
+			)
3028
+		);
3029
+	}
3030
+    
3031
+    
3032
+	/**
3033
+	 * This handles updating the global settings set on the admin page.
3034
+	 * @throws \EE_Error
3035
+	 */
3036
+	protected function _update_global_settings()
3037
+	{
3038
+		/** @var EE_Network_Core_Config $network_config */
3039
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3040
+		$form           = $this->_generate_global_settings_form();
3041
+		if ($form->was_submitted()) {
3042
+			$form->receive_form_submission();
3043
+			if ($form->is_valid()) {
3044
+				$valid_data = $form->valid_data();
3045
+				foreach ($valid_data as $property => $value) {
3046
+					$setter = 'set_' . $property;
3047
+					if (method_exists($network_config, $setter)) {
3048
+						$network_config->{$setter}($value);
3049
+					} else if (
3050
+						property_exists($network_config, $property)
3051
+						&& $network_config->{$property} !== $value
3052
+					) {
3053
+						$network_config->{$property} = $value;
3054
+					}
3055
+				}
3056
+				//only update if the form submission was valid!
3057
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3058
+				EE_Error::overwrite_success();
3059
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3060
+			}
3061
+		}
3062
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3063
+	}
3064
+    
3065
+    
3066
+	/**
3067
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3068
+	 *
3069
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3070
+	 *
3071
+	 * @return string            html formatted tabs
3072
+	 */
3073
+	protected function _get_mt_tabs($tab_array)
3074
+	{
3075
+		$tab_array = (array)$tab_array;
3076
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3077
+		$tabs      = '';
3078
+        
3079
+		foreach ($tab_array as $tab) {
3080
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3081
+		}
3082
+        
3083
+		return $tabs;
3084
+	}
3085
+    
3086
+    
3087
+	/**
3088
+	 * This prepares the content of the messenger meta box admin settings
3089
+	 *
3090
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3091
+	 *
3092
+	 * @return string            html formatted content
3093
+	 */
3094
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3095
+	{
3096
+        
3097
+		$fields                                         = $messenger->get_admin_settings_fields();
3098
+		$settings_template_args['template_form_fields'] = '';
3099
+        
3100
+		//is $messenger active?
3101
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3102
+        
3103
+        
3104
+		if ( ! empty($fields)) {
3105 3105
             
3106
-            $existing_settings = $messenger->get_existing_admin_settings();
3106
+			$existing_settings = $messenger->get_existing_admin_settings();
3107 3107
             
3108
-            foreach ($fields as $fldname => $fldprops) {
3109
-                $field_id                       = $messenger->name . '-' . $fldname;
3110
-                $template_form_field[$field_id] = array(
3111
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3112
-                    'label'      => $fldprops['label'],
3113
-                    'input'      => $fldprops['field_type'],
3114
-                    'type'       => $fldprops['value_type'],
3115
-                    'required'   => $fldprops['required'],
3116
-                    'validation' => $fldprops['validation'],
3117
-                    'value'      => isset($existing_settings[$field_id])
3118
-                        ? $existing_settings[$field_id]
3119
-                        : $fldprops['default'],
3120
-                    'css_class'  => '',
3121
-                    'format'     => $fldprops['format']
3122
-                );
3123
-            }
3108
+			foreach ($fields as $fldname => $fldprops) {
3109
+				$field_id                       = $messenger->name . '-' . $fldname;
3110
+				$template_form_field[$field_id] = array(
3111
+					'name'       => 'messenger_settings[' . $field_id . ']',
3112
+					'label'      => $fldprops['label'],
3113
+					'input'      => $fldprops['field_type'],
3114
+					'type'       => $fldprops['value_type'],
3115
+					'required'   => $fldprops['required'],
3116
+					'validation' => $fldprops['validation'],
3117
+					'value'      => isset($existing_settings[$field_id])
3118
+						? $existing_settings[$field_id]
3119
+						: $fldprops['default'],
3120
+					'css_class'  => '',
3121
+					'format'     => $fldprops['format']
3122
+				);
3123
+			}
3124 3124
             
3125 3125
             
3126
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3127
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3128
-                : '';
3129
-        }
3130
-        
3131
-        //we also need some hidden fields
3132
-        $settings_template_args['hidden_fields'] = array(
3133
-            'messenger_settings[messenger]' => array(
3134
-                'type'  => 'hidden',
3135
-                'value' => $messenger->name
3136
-            ),
3137
-            'type'                          => array(
3138
-                'type'  => 'hidden',
3139
-                'value' => 'messenger'
3140
-            )
3141
-        );
3142
-        
3143
-        //make sure any active message types that are existing are included in the hidden fields
3144
-        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3145
-            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3146
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3147
-                    'type'  => 'hidden',
3148
-                    'value' => $mt
3149
-                );
3150
-            }
3151
-        }
3152
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3153
-            $settings_template_args['hidden_fields'],
3154
-            'array'
3155
-        );
3156
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3157
-        
3158
-        $settings_template_args['messenger']           = $messenger->name;
3159
-        $settings_template_args['description']         = $messenger->description;
3160
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3161
-        
3162
-        
3163
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3164
-            ? $settings_template_args['show_hide_edit_form']
3165
-            : ' hidden';
3166
-        
3167
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3168
-            ? ' hidden'
3169
-            : $settings_template_args['show_hide_edit_form'];
3170
-        
3171
-        
3172
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3173
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3174
-        $settings_template_args['on_off_status'] = $active ? true : false;
3175
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3176
-        $content                                 = EEH_Template::display_template($template, $settings_template_args,
3177
-            true);
3178
-        
3179
-        return $content;
3180
-    }
3181
-    
3182
-    
3183
-    /**
3184
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3185
-     */
3186
-    public function activate_messenger_toggle()
3187
-    {
3188
-        $success = true;
3189
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3190
-        //let's check that we have required data
3191
-        if ( ! isset($this->_req_data['messenger'])) {
3192
-            EE_Error::add_error(
3193
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3194
-                __FILE__,
3195
-                __FUNCTION__,
3196
-                __LINE__
3197
-            );
3198
-            $success = false;
3199
-        }
3200
-        
3201
-        //do a nonce check here since we're not arriving via a normal route
3202
-        $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3203
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3204
-        
3205
-        $this->_verify_nonce($nonce, $nonce_ref);
3206
-        
3207
-        
3208
-        if ( ! isset($this->_req_data['status'])) {
3209
-            EE_Error::add_error(
3210
-                __(
3211
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3212
-                    'event_espresso'
3213
-                ),
3214
-                __FILE__,
3215
-                __FUNCTION__,
3216
-                __LINE__
3217
-            );
3218
-            $success = false;
3219
-        }
3220
-        
3221
-        //do check to verify we have a valid status.
3222
-        $status = $this->_req_data['status'];
3223
-        
3224
-        if ($status != 'off' && $status != 'on') {
3225
-            EE_Error::add_error(
3226
-                sprintf(
3227
-                    __('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3228
-                    $this->_req_data['status']
3229
-                ),
3230
-                __FILE__,
3231
-                __FUNCTION__,
3232
-                __LINE__
3233
-            );
3234
-            $success = false;
3235
-        }
3236
-        
3237
-        if ($success) {
3238
-            //made it here?  Stop dawdling then!!
3239
-            $success = $status == 'off'
3240
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3241
-                : $this->_activate_messenger($this->_req_data['messenger']);
3242
-        }
3243
-        
3244
-        $this->_template_args['success'] = $success;
3245
-        
3246
-        //no special instructions so let's just do the json return (which should automatically do all the special stuff).
3247
-        $this->_return_json();
3248
-        
3249
-    }
3250
-    
3251
-    
3252
-    /**
3253
-     * used by ajax from the messages settings page to activate|deactivate a message type
3254
-     *
3255
-     */
3256
-    public function activate_mt_toggle()
3257
-    {
3258
-        $success = true;
3259
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3260
-        
3261
-        //let's make sure we have the necessary data
3262
-        if ( ! isset($this->_req_data['message_type'])) {
3263
-            EE_Error::add_error(
3264
-                __('Message Type name needed to toggle activation. None given', 'event_espresso'),
3265
-                __FILE__, __FUNCTION__, __LINE__
3266
-            );
3267
-            $success = false;
3268
-        }
3269
-        
3270
-        if ( ! isset($this->_req_data['messenger'])) {
3271
-            EE_Error::add_error(
3272
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3273
-                __FILE__, __FUNCTION__, __LINE__
3274
-            );
3275
-            $success = false;
3276
-        }
3277
-        
3278
-        if ( ! isset($this->_req_data['status'])) {
3279
-            EE_Error::add_error(
3280
-                __('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3281
-                    'event_espresso'),
3282
-                __FILE__, __FUNCTION__, __LINE__
3283
-            );
3284
-            $success = false;
3285
-        }
3286
-        
3287
-        
3288
-        //do check to verify we have a valid status.
3289
-        $status = $this->_req_data['status'];
3290
-        
3291
-        if ($status != 'activate' && $status != 'deactivate') {
3292
-            EE_Error::add_error(
3293
-                sprintf(
3294
-                    __('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3295
-                    $this->_req_data['status']
3296
-                ),
3297
-                __FILE__, __FUNCTION__, __LINE__
3298
-            );
3299
-            $success = false;
3300
-        }
3301
-        
3302
-        
3303
-        //do a nonce check here since we're not arriving via a normal route
3304
-        $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3305
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3306
-        
3307
-        $this->_verify_nonce($nonce, $nonce_ref);
3308
-        
3309
-        if ($success) {
3310
-            //made it here? um, what are you waiting for then?
3311
-            $success = $status == 'deactivate'
3312
-                ? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3313
-                    $this->_req_data['message_type'])
3314
-                : $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3315
-                    $this->_req_data['message_type']);
3316
-        }
3317
-        
3318
-        $this->_template_args['success'] = $success;
3319
-        $this->_return_json();
3320
-    }
3321
-    
3322
-    
3323
-    /**
3324
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3325
-     *
3326
-     * @param string $messenger_name The name of the messenger being activated
3327
-     *
3328
-     * @return bool
3329
-     */
3330
-    protected function _activate_messenger($messenger_name)
3331
-    {
3332
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3333
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3334
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3335
-        
3336
-        //ensure is active
3337
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3338
-        
3339
-        //set response_data for reload
3340
-        foreach ($message_types_to_activate as $message_type_name) {
3341
-            /** @var EE_message_type $message_type */
3342
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3343
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3344
-                    $message_type_name)
3345
-                && $message_type instanceof EE_message_type
3346
-            ) {
3347
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3348
-                if ($message_type->get_admin_settings_fields()) {
3349
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3350
-                }
3351
-            }
3352
-        }
3353
-        
3354
-        //add success message for activating messenger
3355
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3356
-        
3357
-    }
3358
-    
3359
-    
3360
-    /**
3361
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3362
-     *
3363
-     * @param string $messenger_name The name of the messenger being activated
3364
-     *
3365
-     * @return bool
3366
-     */
3367
-    protected function _deactivate_messenger($messenger_name)
3368
-    {
3369
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3370
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3371
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
3372
-        
3373
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3374
-    }
3375
-    
3376
-    
3377
-    /**
3378
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3379
-     *
3380
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
3381
-     * @param string $message_type_name The name of the message type being activated for the messenger
3382
-     *
3383
-     * @return bool
3384
-     */
3385
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3386
-    {
3387
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3388
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3389
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3390
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3391
-        
3392
-        //ensure is active
3393
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3394
-        
3395
-        //set response for load
3396
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3397
-            $message_type_name)
3398
-        ) {
3399
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
3400
-            if ($message_type_to_activate->get_admin_settings_fields()) {
3401
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
3402
-            }
3403
-        }
3404
-        
3405
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3406
-            $message_type_to_activate);
3407
-    }
3408
-    
3409
-    
3410
-    /**
3411
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3412
-     *
3413
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3414
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
3415
-     *
3416
-     * @return bool
3417
-     */
3418
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3419
-    {
3420
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3425
-        
3426
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3427
-            $message_type_to_deactivate);
3428
-    }
3429
-    
3430
-    
3431
-    /**
3432
-     * This just initializes the defaults for activating messenger and message type responses.
3433
-     */
3434
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
3435
-    {
3436
-        $this->_template_args['data']['active_mts'] = array();
3437
-        $this->_template_args['data']['mt_reload']  = array();
3438
-    }
3439
-    
3440
-    
3441
-    /**
3442
-     * Setup appropriate response for activating a messenger and/or message types
3443
-     *
3444
-     * @param EE_messenger         $messenger
3445
-     * @param EE_message_type|null $message_type
3446
-     *
3447
-     * @return bool
3448
-     * @throws EE_Error
3449
-     */
3450
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
3451
-        $messenger,
3452
-        EE_Message_Type $message_type = null
3453
-    ) {
3454
-        //if $messenger isn't a valid messenger object then get out.
3455
-        if ( ! $messenger instanceof EE_Messenger) {
3456
-            EE_Error::add_error(
3457
-                __('The messenger being activated is not a valid messenger', 'event_espresso'),
3458
-                __FILE__,
3459
-                __FUNCTION__,
3460
-                __LINE__
3461
-            );
3126
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3127
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3128
+				: '';
3129
+		}
3130
+        
3131
+		//we also need some hidden fields
3132
+		$settings_template_args['hidden_fields'] = array(
3133
+			'messenger_settings[messenger]' => array(
3134
+				'type'  => 'hidden',
3135
+				'value' => $messenger->name
3136
+			),
3137
+			'type'                          => array(
3138
+				'type'  => 'hidden',
3139
+				'value' => 'messenger'
3140
+			)
3141
+		);
3142
+        
3143
+		//make sure any active message types that are existing are included in the hidden fields
3144
+		if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3145
+			foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3146
+				$settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3147
+					'type'  => 'hidden',
3148
+					'value' => $mt
3149
+				);
3150
+			}
3151
+		}
3152
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3153
+			$settings_template_args['hidden_fields'],
3154
+			'array'
3155
+		);
3156
+		$active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3157
+        
3158
+		$settings_template_args['messenger']           = $messenger->name;
3159
+		$settings_template_args['description']         = $messenger->description;
3160
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3161
+        
3162
+        
3163
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3164
+			? $settings_template_args['show_hide_edit_form']
3165
+			: ' hidden';
3166
+        
3167
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3168
+			? ' hidden'
3169
+			: $settings_template_args['show_hide_edit_form'];
3170
+        
3171
+        
3172
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3173
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3174
+		$settings_template_args['on_off_status'] = $active ? true : false;
3175
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3176
+		$content                                 = EEH_Template::display_template($template, $settings_template_args,
3177
+			true);
3178
+        
3179
+		return $content;
3180
+	}
3181
+    
3182
+    
3183
+	/**
3184
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3185
+	 */
3186
+	public function activate_messenger_toggle()
3187
+	{
3188
+		$success = true;
3189
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3190
+		//let's check that we have required data
3191
+		if ( ! isset($this->_req_data['messenger'])) {
3192
+			EE_Error::add_error(
3193
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3194
+				__FILE__,
3195
+				__FUNCTION__,
3196
+				__LINE__
3197
+			);
3198
+			$success = false;
3199
+		}
3200
+        
3201
+		//do a nonce check here since we're not arriving via a normal route
3202
+		$nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3203
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3204
+        
3205
+		$this->_verify_nonce($nonce, $nonce_ref);
3206
+        
3207
+        
3208
+		if ( ! isset($this->_req_data['status'])) {
3209
+			EE_Error::add_error(
3210
+				__(
3211
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3212
+					'event_espresso'
3213
+				),
3214
+				__FILE__,
3215
+				__FUNCTION__,
3216
+				__LINE__
3217
+			);
3218
+			$success = false;
3219
+		}
3220
+        
3221
+		//do check to verify we have a valid status.
3222
+		$status = $this->_req_data['status'];
3223
+        
3224
+		if ($status != 'off' && $status != 'on') {
3225
+			EE_Error::add_error(
3226
+				sprintf(
3227
+					__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3228
+					$this->_req_data['status']
3229
+				),
3230
+				__FILE__,
3231
+				__FUNCTION__,
3232
+				__LINE__
3233
+			);
3234
+			$success = false;
3235
+		}
3236
+        
3237
+		if ($success) {
3238
+			//made it here?  Stop dawdling then!!
3239
+			$success = $status == 'off'
3240
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3241
+				: $this->_activate_messenger($this->_req_data['messenger']);
3242
+		}
3243
+        
3244
+		$this->_template_args['success'] = $success;
3245
+        
3246
+		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
3247
+		$this->_return_json();
3248
+        
3249
+	}
3250
+    
3251
+    
3252
+	/**
3253
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3254
+	 *
3255
+	 */
3256
+	public function activate_mt_toggle()
3257
+	{
3258
+		$success = true;
3259
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3260
+        
3261
+		//let's make sure we have the necessary data
3262
+		if ( ! isset($this->_req_data['message_type'])) {
3263
+			EE_Error::add_error(
3264
+				__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3265
+				__FILE__, __FUNCTION__, __LINE__
3266
+			);
3267
+			$success = false;
3268
+		}
3269
+        
3270
+		if ( ! isset($this->_req_data['messenger'])) {
3271
+			EE_Error::add_error(
3272
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3273
+				__FILE__, __FUNCTION__, __LINE__
3274
+			);
3275
+			$success = false;
3276
+		}
3277
+        
3278
+		if ( ! isset($this->_req_data['status'])) {
3279
+			EE_Error::add_error(
3280
+				__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3281
+					'event_espresso'),
3282
+				__FILE__, __FUNCTION__, __LINE__
3283
+			);
3284
+			$success = false;
3285
+		}
3286
+        
3287
+        
3288
+		//do check to verify we have a valid status.
3289
+		$status = $this->_req_data['status'];
3290
+        
3291
+		if ($status != 'activate' && $status != 'deactivate') {
3292
+			EE_Error::add_error(
3293
+				sprintf(
3294
+					__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3295
+					$this->_req_data['status']
3296
+				),
3297
+				__FILE__, __FUNCTION__, __LINE__
3298
+			);
3299
+			$success = false;
3300
+		}
3301
+        
3302
+        
3303
+		//do a nonce check here since we're not arriving via a normal route
3304
+		$nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3305
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3306
+        
3307
+		$this->_verify_nonce($nonce, $nonce_ref);
3308
+        
3309
+		if ($success) {
3310
+			//made it here? um, what are you waiting for then?
3311
+			$success = $status == 'deactivate'
3312
+				? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3313
+					$this->_req_data['message_type'])
3314
+				: $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3315
+					$this->_req_data['message_type']);
3316
+		}
3317
+        
3318
+		$this->_template_args['success'] = $success;
3319
+		$this->_return_json();
3320
+	}
3321
+    
3322
+    
3323
+	/**
3324
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3325
+	 *
3326
+	 * @param string $messenger_name The name of the messenger being activated
3327
+	 *
3328
+	 * @return bool
3329
+	 */
3330
+	protected function _activate_messenger($messenger_name)
3331
+	{
3332
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3333
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3334
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3335
+        
3336
+		//ensure is active
3337
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3338
+        
3339
+		//set response_data for reload
3340
+		foreach ($message_types_to_activate as $message_type_name) {
3341
+			/** @var EE_message_type $message_type */
3342
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3343
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3344
+					$message_type_name)
3345
+				&& $message_type instanceof EE_message_type
3346
+			) {
3347
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3348
+				if ($message_type->get_admin_settings_fields()) {
3349
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3350
+				}
3351
+			}
3352
+		}
3353
+        
3354
+		//add success message for activating messenger
3355
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3356
+        
3357
+	}
3358
+    
3359
+    
3360
+	/**
3361
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3362
+	 *
3363
+	 * @param string $messenger_name The name of the messenger being activated
3364
+	 *
3365
+	 * @return bool
3366
+	 */
3367
+	protected function _deactivate_messenger($messenger_name)
3368
+	{
3369
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3370
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3371
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
3372
+        
3373
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3374
+	}
3375
+    
3376
+    
3377
+	/**
3378
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3379
+	 *
3380
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
3381
+	 * @param string $message_type_name The name of the message type being activated for the messenger
3382
+	 *
3383
+	 * @return bool
3384
+	 */
3385
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3386
+	{
3387
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3388
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3389
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3390
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3391
+        
3392
+		//ensure is active
3393
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3394
+        
3395
+		//set response for load
3396
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3397
+			$message_type_name)
3398
+		) {
3399
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
3400
+			if ($message_type_to_activate->get_admin_settings_fields()) {
3401
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3402
+			}
3403
+		}
3404
+        
3405
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3406
+			$message_type_to_activate);
3407
+	}
3408
+    
3409
+    
3410
+	/**
3411
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3412
+	 *
3413
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3414
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
3415
+	 *
3416
+	 * @return bool
3417
+	 */
3418
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3419
+	{
3420
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3425
+        
3426
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3427
+			$message_type_to_deactivate);
3428
+	}
3429
+    
3430
+    
3431
+	/**
3432
+	 * This just initializes the defaults for activating messenger and message type responses.
3433
+	 */
3434
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
3435
+	{
3436
+		$this->_template_args['data']['active_mts'] = array();
3437
+		$this->_template_args['data']['mt_reload']  = array();
3438
+	}
3439
+    
3440
+    
3441
+	/**
3442
+	 * Setup appropriate response for activating a messenger and/or message types
3443
+	 *
3444
+	 * @param EE_messenger         $messenger
3445
+	 * @param EE_message_type|null $message_type
3446
+	 *
3447
+	 * @return bool
3448
+	 * @throws EE_Error
3449
+	 */
3450
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
3451
+		$messenger,
3452
+		EE_Message_Type $message_type = null
3453
+	) {
3454
+		//if $messenger isn't a valid messenger object then get out.
3455
+		if ( ! $messenger instanceof EE_Messenger) {
3456
+			EE_Error::add_error(
3457
+				__('The messenger being activated is not a valid messenger', 'event_espresso'),
3458
+				__FILE__,
3459
+				__FUNCTION__,
3460
+				__LINE__
3461
+			);
3462 3462
             
3463
-            return false;
3464
-        }
3465
-        //activated
3466
-        if ($this->_template_args['data']['active_mts']) {
3467
-            EE_Error::overwrite_success();
3468
-            //activated a message type with the messenger
3469
-            if ($message_type instanceof EE_message_type) {
3470
-                EE_Error::add_success(
3471
-                    sprintf(
3472
-                        __('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3473
-                        ucwords($message_type->label['singular']),
3474
-                        ucwords($messenger->label['singular'])
3475
-                    )
3476
-                );
3463
+			return false;
3464
+		}
3465
+		//activated
3466
+		if ($this->_template_args['data']['active_mts']) {
3467
+			EE_Error::overwrite_success();
3468
+			//activated a message type with the messenger
3469
+			if ($message_type instanceof EE_message_type) {
3470
+				EE_Error::add_success(
3471
+					sprintf(
3472
+						__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3473
+						ucwords($message_type->label['singular']),
3474
+						ucwords($messenger->label['singular'])
3475
+					)
3476
+				);
3477 3477
                 
3478
-                //if message type was invoice then let's make sure we activate the invoice payment method.
3479
-                if ($message_type->name == 'invoice') {
3480
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
3481
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3482
-                    if ($pm instanceof EE_Payment_Method) {
3483
-                        EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3484
-                            'event_espresso'));
3485
-                    }
3486
-                }
3487
-                //just toggles the entire messenger
3488
-            } else {
3489
-                EE_Error::add_success(
3490
-                    sprintf(
3491
-                        __('%s messenger has been successfully activated', 'event_espresso'),
3492
-                        ucwords($messenger->label['singular'])
3493
-                    )
3494
-                );
3495
-            }
3478
+				//if message type was invoice then let's make sure we activate the invoice payment method.
3479
+				if ($message_type->name == 'invoice') {
3480
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
3481
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3482
+					if ($pm instanceof EE_Payment_Method) {
3483
+						EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3484
+							'event_espresso'));
3485
+					}
3486
+				}
3487
+				//just toggles the entire messenger
3488
+			} else {
3489
+				EE_Error::add_success(
3490
+					sprintf(
3491
+						__('%s messenger has been successfully activated', 'event_espresso'),
3492
+						ucwords($messenger->label['singular'])
3493
+					)
3494
+				);
3495
+			}
3496 3496
             
3497
-            return true;
3497
+			return true;
3498 3498
             
3499
-            //possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3500
-            //message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3501
-            //in which case we just give a success message for the messenger being successfully activated.
3502
-        } else {
3503
-            if ( ! $messenger->get_default_message_types()) {
3504
-                //messenger doesn't have any default message types so still a success.
3505
-                EE_Error::add_success(
3506
-                    sprintf(
3507
-                        __('%s messenger was successfully activated.', 'event_espresso'),
3508
-                        ucwords($messenger->label['singular'])
3509
-                    )
3510
-                );
3499
+			//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3500
+			//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3501
+			//in which case we just give a success message for the messenger being successfully activated.
3502
+		} else {
3503
+			if ( ! $messenger->get_default_message_types()) {
3504
+				//messenger doesn't have any default message types so still a success.
3505
+				EE_Error::add_success(
3506
+					sprintf(
3507
+						__('%s messenger was successfully activated.', 'event_espresso'),
3508
+						ucwords($messenger->label['singular'])
3509
+					)
3510
+				);
3511 3511
                 
3512
-                return true;
3513
-            } else {
3514
-                EE_Error::add_error(
3515
-                    $message_type instanceof EE_message_type
3516
-                        ? sprintf(
3517
-                        __('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3518
-                        ucwords($message_type->label['singular']),
3519
-                        ucwords($messenger->label['singular'])
3520
-                    )
3521
-                        : sprintf(
3522
-                        __('%s messenger was not successfully activated', 'event_espresso'),
3523
-                        ucwords($messenger->label['singular'])
3524
-                    ),
3525
-                    __FILE__,
3526
-                    __FUNCTION__,
3527
-                    __LINE__
3528
-                );
3512
+				return true;
3513
+			} else {
3514
+				EE_Error::add_error(
3515
+					$message_type instanceof EE_message_type
3516
+						? sprintf(
3517
+						__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3518
+						ucwords($message_type->label['singular']),
3519
+						ucwords($messenger->label['singular'])
3520
+					)
3521
+						: sprintf(
3522
+						__('%s messenger was not successfully activated', 'event_espresso'),
3523
+						ucwords($messenger->label['singular'])
3524
+					),
3525
+					__FILE__,
3526
+					__FUNCTION__,
3527
+					__LINE__
3528
+				);
3529 3529
                 
3530
-                return false;
3531
-            }
3532
-        }
3533
-    }
3534
-    
3535
-    
3536
-    /**
3537
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
3538
-     *
3539
-     * @param EE_messenger         $messenger
3540
-     * @param EE_message_type|null $message_type
3541
-     *
3542
-     * @return bool
3543
-     */
3544
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3545
-        $messenger,
3546
-        EE_message_type $message_type = null
3547
-    ) {
3548
-        EE_Error::overwrite_success();
3549
-        
3550
-        //if $messenger isn't a valid messenger object then get out.
3551
-        if ( ! $messenger instanceof EE_Messenger) {
3552
-            EE_Error::add_error(
3553
-                __('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3554
-                __FILE__,
3555
-                __FUNCTION__,
3556
-                __LINE__
3557
-            );
3530
+				return false;
3531
+			}
3532
+		}
3533
+	}
3534
+    
3535
+    
3536
+	/**
3537
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
3538
+	 *
3539
+	 * @param EE_messenger         $messenger
3540
+	 * @param EE_message_type|null $message_type
3541
+	 *
3542
+	 * @return bool
3543
+	 */
3544
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3545
+		$messenger,
3546
+		EE_message_type $message_type = null
3547
+	) {
3548
+		EE_Error::overwrite_success();
3549
+        
3550
+		//if $messenger isn't a valid messenger object then get out.
3551
+		if ( ! $messenger instanceof EE_Messenger) {
3552
+			EE_Error::add_error(
3553
+				__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3554
+				__FILE__,
3555
+				__FUNCTION__,
3556
+				__LINE__
3557
+			);
3558 3558
             
3559
-            return false;
3560
-        }
3561
-        
3562
-        if ($message_type instanceof EE_message_type) {
3563
-            $message_type_name = $message_type->name;
3564
-            EE_Error::add_success(
3565
-                sprintf(
3566
-                    __('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3567
-                    ucwords($message_type->label['singular']),
3568
-                    ucwords($messenger->label['singular'])
3569
-                )
3570
-            );
3571
-        } else {
3572
-            $message_type_name = '';
3573
-            EE_Error::add_success(
3574
-                sprintf(
3575
-                    __('%s messenger has been successfully deactivated.', 'event_espresso'),
3576
-                    ucwords($messenger->label['singular'])
3577
-                )
3578
-            );
3579
-        }
3580
-        
3581
-        //if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3582
-        if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3583
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
3584
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3585
-            if ($count_updated > 0) {
3586
-                $msg = $message_type_name == 'invoice'
3587
-                    ? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3588
-                        'event_espresso')
3589
-                    : __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3590
-                        'event_espresso');
3591
-                EE_Error::add_attention($msg);
3592
-            }
3593
-        }
3594
-        
3595
-        return true;
3596
-    }
3597
-    
3598
-    
3599
-    /**
3600
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3601
-     */
3602
-    public function update_mt_form()
3603
-    {
3604
-        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3605
-            EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3606
-                __LINE__);
3607
-            $this->_return_json();
3608
-        }
3609
-        
3610
-        $message_types = $this->get_installed_message_types();
3611
-        
3612
-        $message_type = $message_types[$this->_req_data['message_type']];
3613
-        $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3614
-        
3615
-        $content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3616
-        $this->_template_args['success'] = true;
3617
-        $this->_template_args['content'] = $content;
3618
-        $this->_return_json();
3619
-    }
3620
-    
3621
-    
3622
-    /**
3623
-     * this handles saving the settings for a messenger or message type
3624
-     *
3625
-     */
3626
-    public function save_settings()
3627
-    {
3628
-        if ( ! isset($this->_req_data['type'])) {
3629
-            EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3630
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3631
-            $this->_template_args['error'] = true;
3632
-            $this->_return_json();
3633
-        }
3634
-        
3635
-        
3636
-        if ($this->_req_data['type'] == 'messenger') {
3637
-            $settings  = $this->_req_data['messenger_settings']; //this should be an array.
3638
-            $messenger = $settings['messenger'];
3639
-            //let's setup the settings data
3640
-            foreach ($settings as $key => $value) {
3641
-                switch ($key) {
3642
-                    case 'messenger' :
3643
-                        unset($settings['messenger']);
3644
-                        break;
3645
-                    case 'message_types' :
3646
-                        unset($settings['message_types']);
3647
-                        break;
3648
-                    default :
3649
-                        $settings[$key] = $value;
3650
-                        break;
3651
-                }
3652
-            }
3653
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3654
-        } else if ($this->_req_data['type'] == 'message_type') {
3655
-            $settings     = $this->_req_data['message_type_settings'];
3656
-            $messenger    = $settings['messenger'];
3657
-            $message_type = $settings['message_type'];
3559
+			return false;
3560
+		}
3561
+        
3562
+		if ($message_type instanceof EE_message_type) {
3563
+			$message_type_name = $message_type->name;
3564
+			EE_Error::add_success(
3565
+				sprintf(
3566
+					__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3567
+					ucwords($message_type->label['singular']),
3568
+					ucwords($messenger->label['singular'])
3569
+				)
3570
+			);
3571
+		} else {
3572
+			$message_type_name = '';
3573
+			EE_Error::add_success(
3574
+				sprintf(
3575
+					__('%s messenger has been successfully deactivated.', 'event_espresso'),
3576
+					ucwords($messenger->label['singular'])
3577
+				)
3578
+			);
3579
+		}
3580
+        
3581
+		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3582
+		if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3583
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
3584
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3585
+			if ($count_updated > 0) {
3586
+				$msg = $message_type_name == 'invoice'
3587
+					? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3588
+						'event_espresso')
3589
+					: __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3590
+						'event_espresso');
3591
+				EE_Error::add_attention($msg);
3592
+			}
3593
+		}
3594
+        
3595
+		return true;
3596
+	}
3597
+    
3598
+    
3599
+	/**
3600
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3601
+	 */
3602
+	public function update_mt_form()
3603
+	{
3604
+		if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3605
+			EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3606
+				__LINE__);
3607
+			$this->_return_json();
3608
+		}
3609
+        
3610
+		$message_types = $this->get_installed_message_types();
3611
+        
3612
+		$message_type = $message_types[$this->_req_data['message_type']];
3613
+		$messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3614
+        
3615
+		$content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3616
+		$this->_template_args['success'] = true;
3617
+		$this->_template_args['content'] = $content;
3618
+		$this->_return_json();
3619
+	}
3620
+    
3621
+    
3622
+	/**
3623
+	 * this handles saving the settings for a messenger or message type
3624
+	 *
3625
+	 */
3626
+	public function save_settings()
3627
+	{
3628
+		if ( ! isset($this->_req_data['type'])) {
3629
+			EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3630
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3631
+			$this->_template_args['error'] = true;
3632
+			$this->_return_json();
3633
+		}
3634
+        
3635
+        
3636
+		if ($this->_req_data['type'] == 'messenger') {
3637
+			$settings  = $this->_req_data['messenger_settings']; //this should be an array.
3638
+			$messenger = $settings['messenger'];
3639
+			//let's setup the settings data
3640
+			foreach ($settings as $key => $value) {
3641
+				switch ($key) {
3642
+					case 'messenger' :
3643
+						unset($settings['messenger']);
3644
+						break;
3645
+					case 'message_types' :
3646
+						unset($settings['message_types']);
3647
+						break;
3648
+					default :
3649
+						$settings[$key] = $value;
3650
+						break;
3651
+				}
3652
+			}
3653
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3654
+		} else if ($this->_req_data['type'] == 'message_type') {
3655
+			$settings     = $this->_req_data['message_type_settings'];
3656
+			$messenger    = $settings['messenger'];
3657
+			$message_type = $settings['message_type'];
3658 3658
             
3659
-            foreach ($settings as $key => $value) {
3660
-                switch ($key) {
3661
-                    case 'messenger' :
3662
-                        unset($settings['messenger']);
3663
-                        break;
3664
-                    case 'message_type' :
3665
-                        unset($settings['message_type']);
3666
-                        break;
3667
-                    default :
3668
-                        $settings[$key] = $value;
3669
-                        break;
3670
-                }
3671
-            }
3659
+			foreach ($settings as $key => $value) {
3660
+				switch ($key) {
3661
+					case 'messenger' :
3662
+						unset($settings['messenger']);
3663
+						break;
3664
+					case 'message_type' :
3665
+						unset($settings['message_type']);
3666
+						break;
3667
+					default :
3668
+						$settings[$key] = $value;
3669
+						break;
3670
+				}
3671
+			}
3672 3672
             
3673
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3674
-        }
3675
-        
3676
-        //okay we should have the data all setup.  Now we just update!
3677
-        $success = $this->_message_resource_manager->update_active_messengers_option();
3678
-        
3679
-        if ($success) {
3680
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
3681
-        } else {
3682
-            EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3683
-        }
3684
-        
3685
-        $this->_template_args['success'] = $success;
3686
-        $this->_return_json();
3687
-    }
3688
-    
3689
-    
3690
-    
3691
-    
3692
-    /**  EE MESSAGE PROCESSING ACTIONS **/
3693
-    
3694
-    
3695
-    /**
3696
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3697
-     * However, this does not send immediately, it just queues for sending.
3698
-     *
3699
-     * @since 4.9.0
3700
-     */
3701
-    protected function _generate_now()
3702
-    {
3703
-        $msg_ids = $this->_get_msg_ids_from_request();
3704
-        EED_Messages::generate_now($msg_ids);
3705
-        $this->_redirect_after_action(false, '', '', array(), true);
3706
-    }
3707
-    
3708
-    
3709
-    /**
3710
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3711
-     * are EEM_Message::status_resend or EEM_Message::status_idle
3712
-     *
3713
-     * @since 4.9.0
3714
-     *
3715
-     */
3716
-    protected function _generate_and_send_now()
3717
-    {
3718
-        $this->_generate_now();
3719
-        $this->_send_now();
3720
-        $this->_redirect_after_action(false, '', '', array(), true);
3721
-    }
3722
-    
3723
-    
3724
-    /**
3725
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3726
-     *
3727
-     * @since 4.9.0
3728
-     */
3729
-    protected function _queue_for_resending()
3730
-    {
3731
-        $msg_ids = $this->_get_msg_ids_from_request();
3732
-        EED_Messages::queue_for_resending($msg_ids);
3733
-        $this->_redirect_after_action(false, '', '', array(), true);
3734
-    }
3735
-    
3736
-    
3737
-    /**
3738
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3739
-     *
3740
-     * @since 4.9.0
3741
-     */
3742
-    protected function _send_now()
3743
-    {
3744
-        $msg_ids = $this->_get_msg_ids_from_request();
3745
-        EED_Messages::send_now($msg_ids);
3746
-        $this->_redirect_after_action(false, '', '', array(), true);
3747
-    }
3748
-    
3749
-    
3750
-    /**
3751
-     * Deletes EE_messages for IDs in the request.
3752
-     *
3753
-     * @since 4.9.0
3754
-     */
3755
-    protected function _delete_ee_messages()
3756
-    {
3757
-        $msg_ids       = $this->_get_msg_ids_from_request();
3758
-        $deleted_count = 0;
3759
-        foreach ($msg_ids as $msg_id) {
3760
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3761
-                $deleted_count++;
3762
-            }
3763
-        }
3764
-        if ($deleted_count) {
3765
-            $this->_redirect_after_action(
3766
-                true,
3767
-                _n('message', 'messages', $deleted_count, 'event_espresso'),
3768
-                __('deleted', 'event_espresso')
3769
-            );
3770
-        } else {
3771
-            EE_Error::add_error(
3772
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3773
-                __FILE__, __FUNCTION__, __LINE__
3774
-            );
3775
-            $this->_redirect_after_action(false, '', '', array(), true);
3776
-        }
3777
-    }
3778
-    
3779
-    
3780
-    /**
3781
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3782
-     * @since 4.9.0
3783
-     * @return array
3784
-     */
3785
-    protected function _get_msg_ids_from_request()
3786
-    {
3787
-        if ( ! isset($this->_req_data['MSG_ID'])) {
3788
-            return array();
3789
-        }
3790
-        
3791
-        return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3792
-    }
3673
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3674
+		}
3675
+        
3676
+		//okay we should have the data all setup.  Now we just update!
3677
+		$success = $this->_message_resource_manager->update_active_messengers_option();
3678
+        
3679
+		if ($success) {
3680
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
3681
+		} else {
3682
+			EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3683
+		}
3684
+        
3685
+		$this->_template_args['success'] = $success;
3686
+		$this->_return_json();
3687
+	}
3688
+    
3689
+    
3690
+    
3691
+    
3692
+	/**  EE MESSAGE PROCESSING ACTIONS **/
3693
+    
3694
+    
3695
+	/**
3696
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3697
+	 * However, this does not send immediately, it just queues for sending.
3698
+	 *
3699
+	 * @since 4.9.0
3700
+	 */
3701
+	protected function _generate_now()
3702
+	{
3703
+		$msg_ids = $this->_get_msg_ids_from_request();
3704
+		EED_Messages::generate_now($msg_ids);
3705
+		$this->_redirect_after_action(false, '', '', array(), true);
3706
+	}
3707
+    
3708
+    
3709
+	/**
3710
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3711
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
3712
+	 *
3713
+	 * @since 4.9.0
3714
+	 *
3715
+	 */
3716
+	protected function _generate_and_send_now()
3717
+	{
3718
+		$this->_generate_now();
3719
+		$this->_send_now();
3720
+		$this->_redirect_after_action(false, '', '', array(), true);
3721
+	}
3722
+    
3723
+    
3724
+	/**
3725
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3726
+	 *
3727
+	 * @since 4.9.0
3728
+	 */
3729
+	protected function _queue_for_resending()
3730
+	{
3731
+		$msg_ids = $this->_get_msg_ids_from_request();
3732
+		EED_Messages::queue_for_resending($msg_ids);
3733
+		$this->_redirect_after_action(false, '', '', array(), true);
3734
+	}
3735
+    
3736
+    
3737
+	/**
3738
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3739
+	 *
3740
+	 * @since 4.9.0
3741
+	 */
3742
+	protected function _send_now()
3743
+	{
3744
+		$msg_ids = $this->_get_msg_ids_from_request();
3745
+		EED_Messages::send_now($msg_ids);
3746
+		$this->_redirect_after_action(false, '', '', array(), true);
3747
+	}
3748
+    
3749
+    
3750
+	/**
3751
+	 * Deletes EE_messages for IDs in the request.
3752
+	 *
3753
+	 * @since 4.9.0
3754
+	 */
3755
+	protected function _delete_ee_messages()
3756
+	{
3757
+		$msg_ids       = $this->_get_msg_ids_from_request();
3758
+		$deleted_count = 0;
3759
+		foreach ($msg_ids as $msg_id) {
3760
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3761
+				$deleted_count++;
3762
+			}
3763
+		}
3764
+		if ($deleted_count) {
3765
+			$this->_redirect_after_action(
3766
+				true,
3767
+				_n('message', 'messages', $deleted_count, 'event_espresso'),
3768
+				__('deleted', 'event_espresso')
3769
+			);
3770
+		} else {
3771
+			EE_Error::add_error(
3772
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3773
+				__FILE__, __FUNCTION__, __LINE__
3774
+			);
3775
+			$this->_redirect_after_action(false, '', '', array(), true);
3776
+		}
3777
+	}
3778
+    
3779
+    
3780
+	/**
3781
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3782
+	 * @since 4.9.0
3783
+	 * @return array
3784
+	 */
3785
+	protected function _get_msg_ids_from_request()
3786
+	{
3787
+		if ( ! isset($this->_req_data['MSG_ID'])) {
3788
+			return array();
3789
+		}
3790
+        
3791
+		return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3792
+	}
3793 3793
     
3794 3794
     
3795 3795
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Template.helper.php 3 patches
Indentation   +928 added lines, -928 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 /**
6 6
  * Event Espresso
@@ -16,35 +16,35 @@  discard block
 block discarded – undo
16 16
 
17 17
 
18 18
 if ( ! function_exists('espresso_get_template_part')) {
19
-    /**
20
-     * espresso_get_template_part
21
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
-     * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
-     *
24
-     * @param string $slug The slug name for the generic template.
25
-     * @param string $name The name of the specialised template.
26
-     * @return string        the html output for the formatted money value
27
-     */
28
-    function espresso_get_template_part($slug = null, $name = null)
29
-    {
30
-        EEH_Template::get_template_part($slug, $name);
31
-    }
19
+	/**
20
+	 * espresso_get_template_part
21
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead, and doesn't add base versions of files
22
+	 * so not a very useful function at all except that it adds familiarity PLUS filtering based off of the entire template part name
23
+	 *
24
+	 * @param string $slug The slug name for the generic template.
25
+	 * @param string $name The name of the specialised template.
26
+	 * @return string        the html output for the formatted money value
27
+	 */
28
+	function espresso_get_template_part($slug = null, $name = null)
29
+	{
30
+		EEH_Template::get_template_part($slug, $name);
31
+	}
32 32
 }
33 33
 
34 34
 
35 35
 if ( ! function_exists('espresso_get_object_css_class')) {
36
-    /**
37
-     * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
-     *
39
-     * @param EE_Base_Class $object the EE object the css class is being generated for
40
-     * @param  string       $prefix added to the beginning of the generated class
41
-     * @param  string       $suffix added to the end of the generated class
42
-     * @return string
43
-     */
44
-    function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
-    {
46
-        return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
-    }
36
+	/**
37
+	 * espresso_get_object_css_class - attempts to generate a css class based on the type of EE object passed
38
+	 *
39
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
40
+	 * @param  string       $prefix added to the beginning of the generated class
41
+	 * @param  string       $suffix added to the end of the generated class
42
+	 * @return string
43
+	 */
44
+	function espresso_get_object_css_class($object = null, $prefix = '', $suffix = '')
45
+	{
46
+		return EEH_Template::get_object_css_class($object, $prefix, $suffix);
47
+	}
48 48
 }
49 49
 
50 50
 
@@ -59,648 +59,648 @@  discard block
 block discarded – undo
59 59
 class EEH_Template
60 60
 {
61 61
 
62
-    private static $_espresso_themes = array();
63
-
64
-
65
-    /**
66
-     *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
-     *
68
-     * @return boolean
69
-     */
70
-    public static function is_espresso_theme()
71
-    {
72
-        return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
-    }
74
-
75
-    /**
76
-     *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
-     *    load it's functions.php file ( if not already loaded )
78
-     *
79
-     * @return void
80
-     */
81
-    public static function load_espresso_theme_functions()
82
-    {
83
-        if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
-            }
87
-        }
88
-    }
89
-
90
-
91
-    /**
92
-     *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
-     *
94
-     * @return array
95
-     */
96
-    public static function get_espresso_themes()
97
-    {
98
-        if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
-            if (empty($espresso_themes)) {
101
-                return array();
102
-            }
103
-            if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
-                unset($espresso_themes[$key]);
105
-            }
106
-            EEH_Template::$_espresso_themes = array();
107
-            foreach ($espresso_themes as $espresso_theme) {
108
-                EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
-            }
110
-        }
111
-        return EEH_Template::$_espresso_themes;
112
-    }
113
-
114
-
115
-    /**
116
-     * EEH_Template::get_template_part
117
-     * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
-     * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
-     * filtering based off of the entire template part name
120
-     *
121
-     * @param string $slug The slug name for the generic template.
122
-     * @param string $name The name of the specialised template.
123
-     * @param array  $template_args
124
-     * @param bool   $return_string
125
-     * @return string        the html output for the formatted money value
126
-     */
127
-    public static function get_template_part(
128
-        $slug = null,
129
-        $name = null,
130
-        $template_args = array(),
131
-        $return_string = false
132
-    ) {
133
-        do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
-        $templates = array();
135
-        $name      = (string)$name;
136
-        if ($name != '') {
137
-            $templates[] = "{$slug}-{$name}.php";
138
-        }
139
-        // allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
-        if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
-            EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
-        }
143
-    }
144
-
145
-
146
-    /**
147
-     *    locate_template
148
-     *    locate a template file by looking in the following places, in the following order:
149
-     *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
-     *        <assumed full absolute server path>
151
-     *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
-     *        <server path up to>/wp-content/uploads/espresso/templates/
153
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
-     *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
-     *    as soon as the template is found in one of these locations, it will be returned or loaded
157
-     *        Example:
158
-     *          You are using the WordPress Twenty Sixteen theme,
159
-     *        and you want to customize the "some-event.template.php" template,
160
-     *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
-     *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
-     *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
-     *        /relative/path/to/some-event.template.php
165
-     *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
-     *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
-     *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
-     *          Had you passed an absolute path to your template that was in some other location,
171
-     *        ie: "/absolute/path/to/some-event.template.php"
172
-     *          then the search would have been :
173
-     *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
-     *        /absolute/path/to/some-event.template.php
175
-     *          and stopped there upon finding it in the second location
176
-     *
177
-     * @param array|string $templates       array of template file names including extension (or just a single string)
178
-     * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
-     * @param  boolean     $load            whether to pass the located template path on to the
180
-     *                                      EEH_Template::display_template() method or simply return it
181
-     * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
-     *                                      string
183
-     * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
-     *                                      generate a custom template or not. Used in places where you don't actually
185
-     *                                      load the template, you just want to know if there's a custom version of it.
186
-     * @return mixed
187
-     */
188
-    public static function locate_template(
189
-        $templates = array(),
190
-        $template_args = array(),
191
-        $load = true,
192
-        $return_string = true,
193
-        $check_if_custom = false
194
-    ) {
195
-        // first use WP locate_template to check for template in the current theme folder
196
-        $template_path = locate_template($templates);
197
-
198
-        if ($check_if_custom && ! empty($template_path)) {
199
-            return true;
200
-        }
201
-
202
-        // not in the theme
203
-        if (empty($template_path)) {
204
-            // not even a template to look for ?
205
-            if (empty($templates)) {
206
-                // get post_type
207
-                $post_type = EE_Registry::instance()->REQ->get('post_type');
208
-                // get array of EE Custom Post Types
209
-                $EE_CPTs = EE_Register_CPTs::get_CPTs();
210
-                // build template name based on request
211
-                if (isset($EE_CPTs[$post_type])) {
212
-                    $archive_or_single = is_archive() ? 'archive' : '';
213
-                    $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
215
-                }
216
-            }
217
-            // currently active EE template theme
218
-            $current_theme = EE_Config::get_current_theme();
219
-
220
-            // array of paths to folders that may contain templates
221
-            $template_folder_paths = array(
222
-                // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
-                // then in the root of the /wp-content/uploads/espresso/templates/ folder
225
-                EVENT_ESPRESSO_TEMPLATE_DIR,
226
-            );
227
-
228
-            //add core plugin folders for checking only if we're not $check_if_custom
229
-            if ( ! $check_if_custom) {
230
-                $core_paths            = array(
231
-                    // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
233
-                    // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
235
-                    // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
-                    EE_PLUGIN_DIR_PATH,
237
-                );
238
-                $template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
-            }
240
-
241
-            // now filter that array
242
-            $template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
-                $template_folder_paths);
244
-            $templates             = is_array($templates) ? $templates : array($templates);
245
-            $template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
-            // array to hold all possible template paths
247
-            $full_template_paths = array();
248
-
249
-            // loop through $templates
250
-            foreach ($templates as $template) {
251
-                // normalize directory separators
252
-                $template                      = EEH_File::standardise_directory_separators($template);
253
-                $file_name                     = basename($template);
254
-                $template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
-                // while looping through all template folder paths
256
-                foreach ($template_folder_paths as $template_folder_path) {
257
-                    // normalize directory separators
258
-                    $template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
-                    // determine if any common base path exists between the two paths
260
-                    $common_base_path = EEH_Template::_find_common_base_path(
261
-                        array($template_folder_path, $template_path_minus_file_name)
262
-                    );
263
-                    if ($common_base_path !== '') {
264
-                        // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
-                    } else {
267
-                        // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
-                    }
270
-                    // build up our template locations array by adding our resolved paths
271
-                    $full_template_paths[] = $resolved_path;
272
-                }
273
-                // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
-                array_unshift($full_template_paths, $template);
275
-                // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
-            }
278
-            // filter final array of full template paths
279
-            $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
-                $full_template_paths, $file_name);
281
-            // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
283
-                if (is_readable($full_template_path)) {
284
-                    $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
-                    // hook that can be used to display the full template path that will be used
286
-                    do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
287
-                    break;
288
-                }
289
-            }
290
-        }
291
-        // if we got it and you want to see it...
292
-        if ($template_path && $load && ! $check_if_custom) {
293
-            if ($return_string) {
294
-                return EEH_Template::display_template($template_path, $template_args, true);
295
-            } else {
296
-                EEH_Template::display_template($template_path, $template_args, false);
297
-            }
298
-        }
299
-        return $check_if_custom && ! empty($template_path) ? true : $template_path;
300
-    }
301
-
302
-
303
-    /**
304
-     * _find_common_base_path
305
-     * given two paths, this determines if there is a common base path between the two
306
-     *
307
-     * @param array $paths
308
-     * @return string
309
-     */
310
-    protected static function _find_common_base_path($paths)
311
-    {
312
-        $last_offset      = 0;
313
-        $common_base_path = '';
314
-        while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
315
-            $dir_length = $index - $last_offset + 1;
316
-            $directory  = substr($paths[0], $last_offset, $dir_length);
317
-            foreach ($paths as $path) {
318
-                if (substr($path, $last_offset, $dir_length) != $directory) {
319
-                    return $common_base_path;
320
-                }
321
-            }
322
-            $common_base_path .= $directory;
323
-            $last_offset = $index + 1;
324
-        }
325
-        return substr($common_base_path, 0, -1);
326
-    }
327
-
328
-
329
-    /**
330
-     * load and display a template
331
-     *
332
-     * @param bool|string $template_path server path to the file to be loaded, including file name and extension
333
-     * @param  array      $template_args an array of arguments to be extracted for use in the template
334
-     * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
335
-     * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
336
-     *                                      not found or is not readable
337
-     * @return mixed string
338
-     * @throws \DomainException
339
-     */
62
+	private static $_espresso_themes = array();
63
+
64
+
65
+	/**
66
+	 *    is_espresso_theme - returns TRUE or FALSE on whether the currently active WP theme is an espresso theme
67
+	 *
68
+	 * @return boolean
69
+	 */
70
+	public static function is_espresso_theme()
71
+	{
72
+		return wp_get_theme()->get('TextDomain') == 'event_espresso' ? true : false;
73
+	}
74
+
75
+	/**
76
+	 *    load_espresso_theme_functions - if current theme is an espresso theme, or uses ee theme template parts, then
77
+	 *    load it's functions.php file ( if not already loaded )
78
+	 *
79
+	 * @return void
80
+	 */
81
+	public static function load_espresso_theme_functions()
82
+	{
83
+		if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
+			if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
+				require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
86
+			}
87
+		}
88
+	}
89
+
90
+
91
+	/**
92
+	 *    get_espresso_themes - returns an array of Espresso Child themes located in the /templates/ directory
93
+	 *
94
+	 * @return array
95
+	 */
96
+	public static function get_espresso_themes()
97
+	{
98
+		if (empty(EEH_Template::$_espresso_themes)) {
99
+			$espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
100
+			if (empty($espresso_themes)) {
101
+				return array();
102
+			}
103
+			if (($key = array_search('global_assets', $espresso_themes)) !== false) {
104
+				unset($espresso_themes[$key]);
105
+			}
106
+			EEH_Template::$_espresso_themes = array();
107
+			foreach ($espresso_themes as $espresso_theme) {
108
+				EEH_Template::$_espresso_themes[basename($espresso_theme)] = $espresso_theme;
109
+			}
110
+		}
111
+		return EEH_Template::$_espresso_themes;
112
+	}
113
+
114
+
115
+	/**
116
+	 * EEH_Template::get_template_part
117
+	 * basically a copy of the WordPress get_template_part() function but uses EEH_Template::locate_template() instead,
118
+	 * and doesn't add base versions of files so not a very useful function at all except that it adds familiarity PLUS
119
+	 * filtering based off of the entire template part name
120
+	 *
121
+	 * @param string $slug The slug name for the generic template.
122
+	 * @param string $name The name of the specialised template.
123
+	 * @param array  $template_args
124
+	 * @param bool   $return_string
125
+	 * @return string        the html output for the formatted money value
126
+	 */
127
+	public static function get_template_part(
128
+		$slug = null,
129
+		$name = null,
130
+		$template_args = array(),
131
+		$return_string = false
132
+	) {
133
+		do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134
+		$templates = array();
135
+		$name      = (string)$name;
136
+		if ($name != '') {
137
+			$templates[] = "{$slug}-{$name}.php";
138
+		}
139
+		// allow template parts to be turned off via something like: add_filter( 'FHEE__content_espresso_events_tickets_template__display_datetimes', '__return_false' );
140
+		if (apply_filters("FHEE__EEH_Template__get_template_part__display__{$slug}_{$name}", true)) {
141
+			EEH_Template::locate_template($templates, $template_args, true, $return_string);
142
+		}
143
+	}
144
+
145
+
146
+	/**
147
+	 *    locate_template
148
+	 *    locate a template file by looking in the following places, in the following order:
149
+	 *        <server path up to>/wp-content/themes/<current active WordPress theme>/
150
+	 *        <assumed full absolute server path>
151
+	 *        <server path up to>/wp-content/uploads/espresso/templates/<current EE theme>/
152
+	 *        <server path up to>/wp-content/uploads/espresso/templates/
153
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/public/<current EE theme>/
154
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/core/templates/<current EE theme>/
155
+	 *        <server path up to>/wp-content/plugins/<EE4 folder>/
156
+	 *    as soon as the template is found in one of these locations, it will be returned or loaded
157
+	 *        Example:
158
+	 *          You are using the WordPress Twenty Sixteen theme,
159
+	 *        and you want to customize the "some-event.template.php" template,
160
+	 *          which is located in the "/relative/path/to/" folder relative to the main EE plugin folder.
161
+	 *          Assuming WP is installed on your server in the "/home/public_html/" folder,
162
+	 *        EEH_Template::locate_template() will look at the following paths in order until the template is found:
163
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
164
+	 *        /relative/path/to/some-event.template.php
165
+	 *        /home/public_html/wp-content/uploads/espresso/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
166
+	 *        /home/public_html/wp-content/uploads/espresso/templates/relative/path/to/some-event.template.php
167
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/public/Espresso_Arabica_2014/relative/path/to/some-event.template.php
168
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/core/templates/Espresso_Arabica_2014/relative/path/to/some-event.template.php
169
+	 *        /home/public_html/wp-content/plugins/event-espresso-core-reg/relative/path/to/some-event.template.php
170
+	 *          Had you passed an absolute path to your template that was in some other location,
171
+	 *        ie: "/absolute/path/to/some-event.template.php"
172
+	 *          then the search would have been :
173
+	 *        /home/public_html/wp-content/themes/twentysixteen/some-event.template.php
174
+	 *        /absolute/path/to/some-event.template.php
175
+	 *          and stopped there upon finding it in the second location
176
+	 *
177
+	 * @param array|string $templates       array of template file names including extension (or just a single string)
178
+	 * @param  array       $template_args   an array of arguments to be extracted for use in the template
179
+	 * @param  boolean     $load            whether to pass the located template path on to the
180
+	 *                                      EEH_Template::display_template() method or simply return it
181
+	 * @param  boolean     $return_string   whether to send output immediately to screen, or capture and return as a
182
+	 *                                      string
183
+	 * @param boolean      $check_if_custom If TRUE, this flags this method to return boolean for whether this will
184
+	 *                                      generate a custom template or not. Used in places where you don't actually
185
+	 *                                      load the template, you just want to know if there's a custom version of it.
186
+	 * @return mixed
187
+	 */
188
+	public static function locate_template(
189
+		$templates = array(),
190
+		$template_args = array(),
191
+		$load = true,
192
+		$return_string = true,
193
+		$check_if_custom = false
194
+	) {
195
+		// first use WP locate_template to check for template in the current theme folder
196
+		$template_path = locate_template($templates);
197
+
198
+		if ($check_if_custom && ! empty($template_path)) {
199
+			return true;
200
+		}
201
+
202
+		// not in the theme
203
+		if (empty($template_path)) {
204
+			// not even a template to look for ?
205
+			if (empty($templates)) {
206
+				// get post_type
207
+				$post_type = EE_Registry::instance()->REQ->get('post_type');
208
+				// get array of EE Custom Post Types
209
+				$EE_CPTs = EE_Register_CPTs::get_CPTs();
210
+				// build template name based on request
211
+				if (isset($EE_CPTs[$post_type])) {
212
+					$archive_or_single = is_archive() ? 'archive' : '';
213
+					$archive_or_single = is_single() ? 'single' : $archive_or_single;
214
+					$templates         = $archive_or_single . '-' . $post_type . '.php';
215
+				}
216
+			}
217
+			// currently active EE template theme
218
+			$current_theme = EE_Config::get_current_theme();
219
+
220
+			// array of paths to folders that may contain templates
221
+			$template_folder_paths = array(
222
+				// first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
+				EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
224
+				// then in the root of the /wp-content/uploads/espresso/templates/ folder
225
+				EVENT_ESPRESSO_TEMPLATE_DIR,
226
+			);
227
+
228
+			//add core plugin folders for checking only if we're not $check_if_custom
229
+			if ( ! $check_if_custom) {
230
+				$core_paths            = array(
231
+					// in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
+					EE_PUBLIC . $current_theme,
233
+					// in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
+					EE_TEMPLATES . $current_theme,
235
+					// or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236
+					EE_PLUGIN_DIR_PATH,
237
+				);
238
+				$template_folder_paths = array_merge($template_folder_paths, $core_paths);
239
+			}
240
+
241
+			// now filter that array
242
+			$template_folder_paths = apply_filters('FHEE__EEH_Template__locate_template__template_folder_paths',
243
+				$template_folder_paths);
244
+			$templates             = is_array($templates) ? $templates : array($templates);
245
+			$template_folder_paths = is_array($template_folder_paths) ? $template_folder_paths : array($template_folder_paths);
246
+			// array to hold all possible template paths
247
+			$full_template_paths = array();
248
+
249
+			// loop through $templates
250
+			foreach ($templates as $template) {
251
+				// normalize directory separators
252
+				$template                      = EEH_File::standardise_directory_separators($template);
253
+				$file_name                     = basename($template);
254
+				$template_path_minus_file_name = substr($template, 0, (strlen($file_name) * -1));
255
+				// while looping through all template folder paths
256
+				foreach ($template_folder_paths as $template_folder_path) {
257
+					// normalize directory separators
258
+					$template_folder_path = EEH_File::standardise_directory_separators($template_folder_path);
259
+					// determine if any common base path exists between the two paths
260
+					$common_base_path = EEH_Template::_find_common_base_path(
261
+						array($template_folder_path, $template_path_minus_file_name)
262
+					);
263
+					if ($common_base_path !== '') {
264
+						// both paths have a common base, so just tack the filename onto our search path
265
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
266
+					} else {
267
+						// no common base path, so let's just concatenate
268
+						$resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
269
+					}
270
+					// build up our template locations array by adding our resolved paths
271
+					$full_template_paths[] = $resolved_path;
272
+				}
273
+				// if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274
+				array_unshift($full_template_paths, $template);
275
+				// path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
+				array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
277
+			}
278
+			// filter final array of full template paths
279
+			$full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280
+				$full_template_paths, $file_name);
281
+			// now loop through our final array of template location paths and check each location
282
+			foreach ((array)$full_template_paths as $full_template_path) {
283
+				if (is_readable($full_template_path)) {
284
+					$template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285
+					// hook that can be used to display the full template path that will be used
286
+					do_action('AHEE__EEH_Template__locate_template__full_template_path', $template_path);
287
+					break;
288
+				}
289
+			}
290
+		}
291
+		// if we got it and you want to see it...
292
+		if ($template_path && $load && ! $check_if_custom) {
293
+			if ($return_string) {
294
+				return EEH_Template::display_template($template_path, $template_args, true);
295
+			} else {
296
+				EEH_Template::display_template($template_path, $template_args, false);
297
+			}
298
+		}
299
+		return $check_if_custom && ! empty($template_path) ? true : $template_path;
300
+	}
301
+
302
+
303
+	/**
304
+	 * _find_common_base_path
305
+	 * given two paths, this determines if there is a common base path between the two
306
+	 *
307
+	 * @param array $paths
308
+	 * @return string
309
+	 */
310
+	protected static function _find_common_base_path($paths)
311
+	{
312
+		$last_offset      = 0;
313
+		$common_base_path = '';
314
+		while (($index = strpos($paths[0], DS, $last_offset)) !== false) {
315
+			$dir_length = $index - $last_offset + 1;
316
+			$directory  = substr($paths[0], $last_offset, $dir_length);
317
+			foreach ($paths as $path) {
318
+				if (substr($path, $last_offset, $dir_length) != $directory) {
319
+					return $common_base_path;
320
+				}
321
+			}
322
+			$common_base_path .= $directory;
323
+			$last_offset = $index + 1;
324
+		}
325
+		return substr($common_base_path, 0, -1);
326
+	}
327
+
328
+
329
+	/**
330
+	 * load and display a template
331
+	 *
332
+	 * @param bool|string $template_path server path to the file to be loaded, including file name and extension
333
+	 * @param  array      $template_args an array of arguments to be extracted for use in the template
334
+	 * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
335
+	 * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
336
+	 *                                      not found or is not readable
337
+	 * @return mixed string
338
+	 * @throws \DomainException
339
+	 */
340 340
 	public static function display_template(
341
-        $template_path    = false,
342
-        $template_args    = array(),
343
-        $return_string    = false,
344
-        $throw_exceptions = false
345
-    ) {
346
-
347
-        /**
348
-         * These two filters are intended for last minute changes to templates being loaded and/or template arg
349
-         * modifications.  NOTE... modifying these things can cause breakage as most templates running through
350
-         * the display_template method are templates we DON'T want modified (usually because of js
351
-         * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
352
-         * using this.
353
-         *
354
-         * @since 4.6.0
355
-         */
356
-        $template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
357
-        $template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
358
-
359
-        // you gimme nuttin - YOU GET NUTTIN !!
360
-        if ( ! $template_path || ! is_readable($template_path)) {
361
-            return '';
362
-        }
363
-        // if $template_args are not in an array, then make it so
364
-        if ( ! is_array($template_args) && ! is_object($template_args)) {
365
-            $template_args = array($template_args);
366
-        }
367
-        extract( $template_args, EXTR_SKIP );
368
-        // ignore whether template is accessible ?
369
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
370
-            throw new \DomainException(
371
-                    esc_html__(
372
-                            'Invalid, unreadable, or missing file.',
373
-                            'event_espresso'
374
-                    )
375
-            );
376
-        }
377
-
378
-
379
-        if ($return_string) {
380
-            // because we want to return a string, we are going to capture the output
381
-            ob_start();
382
-            include($template_path);
383
-            return ob_get_clean();
384
-        } else {
385
-            include($template_path);
386
-        }
387
-        return '';
388
-    }
389
-
390
-
391
-    /**
392
-     * get_object_css_class - attempts to generate a css class based on the type of EE object passed
393
-     *
394
-     * @param EE_Base_Class $object the EE object the css class is being generated for
395
-     * @param  string       $prefix added to the beginning of the generated class
396
-     * @param  string       $suffix added to the end of the generated class
397
-     * @return string
398
-     */
399
-    public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
400
-    {
401
-        // in the beginning...
402
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
403
-        // da muddle
404
-        $class = '';
405
-        // the end
406
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
407
-        // is the passed object an EE object ?
408
-        if ($object instanceof EE_Base_Class) {
409
-            // grab the exact type of object
410
-            $obj_class = get_class($object);
411
-            // depending on the type of object...
412
-            switch ($obj_class) {
413
-                // no specifics just yet...
414
-                default :
415
-                    $class = strtolower(str_replace('_', '-', $obj_class));
416
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
417
-
418
-            }
419
-        }
420
-        return $prefix . $class . $suffix;
421
-    }
422
-
423
-
424
-
425
-    /**
426
-     * EEH_Template::format_currency
427
-     * This helper takes a raw float value and formats it according to the default config country currency settings, or
428
-     * the country currency settings from the supplied country ISO code
429
-     *
430
-     * @param  float   $amount       raw money value
431
-     * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
432
-     * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
433
-     * @param string   $CNT_ISO      2 letter ISO code for a country
434
-     * @param string   $cur_code_span_class
435
-     * @return string        the html output for the formatted money value
436
-     * @throws \EE_Error
437
-     */
438
-    public static function format_currency(
439
-        $amount = null,
440
-        $return_raw = false,
441
-        $display_code = true,
442
-        $CNT_ISO = '',
443
-        $cur_code_span_class = 'currency-code'
444
-    ) {
445
-        // ensure amount was received
446
-        if ($amount === null) {
447
-            $msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
448
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
449
-            return '';
450
-        }
451
-        //ensure amount is float
452
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
453
-        $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
454
-        // filter raw amount (allows 0.00 to be changed to "free" for example)
455
-        $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
456
-        // still a number or was amount converted to a string like "free" ?
457
-        if (is_float($amount_formatted)) {
458
-            // was a country ISO code passed ? if so generate currency config object for that country
459
-            $mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
460
-            // verify results
461
-            if ( ! $mny instanceof EE_Currency_Config) {
462
-                // set default config country currency settings
463
-                $mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
464
-                    ? EE_Registry::instance()->CFG->currency
465
-                    : new EE_Currency_Config();
466
-            }
467
-            // format float
468
-            $amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
469
-            // add formatting ?
470
-            if ( ! $return_raw) {
471
-                // add currency sign
472
-                if ($mny->sign_b4) {
473
-                    if ($amount >= 0) {
474
-                        $amount_formatted = $mny->sign . $amount_formatted;
475
-                    } else {
476
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
477
-                    }
478
-
479
-                } else {
480
-                    $amount_formatted = $amount_formatted . $mny->sign;
481
-                }
482
-
483
-                // filter to allow global setting of display_code
484
-                $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
485
-
486
-                // add currency code ?
487
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
488
-            }
489
-            // filter results
490
-            $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
491
-                $amount_formatted, $mny, $return_raw);
492
-        }
493
-        // clean up vars
494
-        unset($mny);
495
-        // return formatted currency amount
496
-        return $amount_formatted;
497
-    }
498
-
499
-
500
-    /**
501
-     * This function is used for outputting the localized label for a given status id in the schema requested (and
502
-     * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
503
-     * related status model or model object (i.e. in documentation etc.)
504
-     *
505
-     * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
506
-     *                            match, then 'Unknown' will be returned.
507
-     * @param  boolean $plural    Whether to return plural or not
508
-     * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
509
-     * @return string             The localized label for the status id.
510
-     */
511
-    public static function pretty_status($status_id, $plural = false, $schema = 'upper')
512
-    {
513
-        /** @type EEM_Status $EEM_Status */
514
-        $EEM_Status = EE_Registry::instance()->load_model('Status');
515
-        $status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
516
-            $schema);
517
-        return $status[$status_id];
518
-    }
519
-
520
-
521
-    /**
522
-     * This helper just returns a button or link for the given parameters
523
-     *
524
-     * @param  string $url   the url for the link
525
-     * @param  string $label What is the label you want displayed for the button
526
-     * @param  string $class what class is used for the button (defaults to 'button-primary')
527
-     * @param string  $icon
528
-     * @param string  $title
529
-     * @return string the html output for the button
530
-     */
531
-    public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
532
-    {
533
-        $icon_html = '';
534
-        if ( ! empty($icon)) {
535
-            $dashicons = preg_split("(ee-icon |dashicons )", $icon);
536
-            $dashicons = array_filter($dashicons);
537
-            $count     = count($dashicons);
538
-            $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
539
-            foreach ($dashicons as $dashicon) {
540
-                $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
541
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
542
-            }
543
-            $icon_html .= $count > 1 ? '</span>' : '';
544
-        }
545
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
546
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . $url . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
547
-        return $button;
548
-    }
549
-
550
-
551
-    /**
552
-     * This returns a generated link that will load the related help tab on admin pages.
553
-     *
554
-     * @param  string     $help_tab_id the id for the connected help tab
555
-     * @param bool|string $page        The page identifier for the page the help tab is on
556
-     * @param bool|string $action      The action (route) for the admin page the help tab is on.
557
-     * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
558
-     * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
559
-     * @return string              generated link
560
-     */
561
-    public static function get_help_tab_link(
562
-        $help_tab_id,
563
-        $page = false,
564
-        $action = false,
565
-        $icon_style = false,
566
-        $help_text = false
567
-    ) {
568
-
569
-        if ( ! $page) {
570
-            $page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
571
-        }
572
-
573
-        if ( ! $action) {
574
-            $action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
575
-        }
576
-
577
-        $action = empty($action) ? 'default' : $action;
578
-
579
-
580
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
581
-        $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
582
-        $help_text    = ! $help_text ? '' : $help_text;
583
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
584
-                'event_espresso') . '" > ' . $help_text . ' </a>';
585
-    }
586
-
587
-
588
-    /**
589
-     * This helper generates the html structure for the jquery joyride plugin with the given params.
590
-     *
591
-     * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
592
-     * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
593
-     * @param EE_Help_Tour
594
-     * @return string         html
595
-     */
596
-    public static function help_tour_stops_generator(EE_Help_Tour $tour)
597
-    {
598
-        $id    = $tour->get_slug();
599
-        $stops = $tour->get_stops();
600
-
601
-        $content = '<ol style="display:none" id="' . $id . '">';
602
-
603
-        foreach ($stops as $stop) {
604
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
605
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
606
-
607
-            //if container is set to modal then let's make sure we set the options accordingly
608
-            if (empty($data_id) && empty($data_class)) {
609
-                $stop['options']['modal']  = true;
610
-                $stop['options']['expose'] = true;
611
-            }
612
-
613
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
614
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
615
-            $inner_content = isset($stop['content']) ? $stop['content'] : '';
616
-
617
-            //options
618
-            if (isset($stop['options']) && is_array($stop['options'])) {
619
-                $options = ' data-options="';
620
-                foreach ($stop['options'] as $option => $value) {
621
-                    $options .= $option . ':' . $value . ';';
622
-                }
623
-                $options .= '"';
624
-            } else {
625
-                $options = '';
626
-            }
627
-
628
-            //let's put all together
629
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
630
-        }
631
-
632
-        $content .= '</ol>';
633
-        return $content;
634
-    }
635
-
636
-
637
-    /**
638
-     * This is a helper method to generate a status legend for a given status array.
639
-     * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
640
-     * status_array.
641
-     *
642
-     * @param  array  $status_array  array of statuses that will make up the legend. In format:
643
-     *                               array(
644
-     *                               'status_item' => 'status_name'
645
-     *                               )
646
-     * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
647
-     *                               the legend.
648
-     * @throws EE_Error
649
-     * @return string               html structure for status.
650
-     */
651
-    public static function status_legend($status_array, $active_status = '')
652
-    {
653
-        if ( ! is_array($status_array)) {
654
-            throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
655
-                'event_espresso'));
656
-        }
657
-
658
-        $setup_array = array();
659
-        foreach ($status_array as $item => $status) {
660
-            $setup_array[$item] = array(
661
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
662
-                'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
663
-                'status' => $status,
664
-            );
665
-        }
666
-
667
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
668
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
669
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
670
-        foreach ($setup_array as $item => $details) {
671
-            $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
672
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
673
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
674
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
675
-            $content .= '</dt>' . "\n";
676
-        }
677
-        $content .= '</dl>' . "\n";
678
-        $content .= '</div>' . "\n";
679
-        return $content;
680
-    }
681
-
682
-
683
-    /**
684
-     * Gets HTML for laying out a deeply-nested array (and objects) in a format
685
-     * that's nice for presenting in the wp admin
686
-     *
687
-     * @param mixed $data
688
-     * @return string
689
-     */
690
-    public static function layout_array_as_table($data)
691
-    {
692
-        if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
693
-            $data = (array)$data;
694
-        }
695
-        ob_start();
696
-        if (is_array($data)) {
697
-            if (EEH_Array::is_associative_array($data)) {
698
-                ?>
341
+		$template_path    = false,
342
+		$template_args    = array(),
343
+		$return_string    = false,
344
+		$throw_exceptions = false
345
+	) {
346
+
347
+		/**
348
+		 * These two filters are intended for last minute changes to templates being loaded and/or template arg
349
+		 * modifications.  NOTE... modifying these things can cause breakage as most templates running through
350
+		 * the display_template method are templates we DON'T want modified (usually because of js
351
+		 * dependencies etc).  So unless you know what you are doing, do NOT filter templates or template args
352
+		 * using this.
353
+		 *
354
+		 * @since 4.6.0
355
+		 */
356
+		$template_path = (string) apply_filters('FHEE__EEH_Template__display_template__template_path', $template_path);
357
+		$template_args = (array) apply_filters('FHEE__EEH_Template__display_template__template_args', $template_args);
358
+
359
+		// you gimme nuttin - YOU GET NUTTIN !!
360
+		if ( ! $template_path || ! is_readable($template_path)) {
361
+			return '';
362
+		}
363
+		// if $template_args are not in an array, then make it so
364
+		if ( ! is_array($template_args) && ! is_object($template_args)) {
365
+			$template_args = array($template_args);
366
+		}
367
+		extract( $template_args, EXTR_SKIP );
368
+		// ignore whether template is accessible ?
369
+		if ( $throw_exceptions && ! is_readable( $template_path ) ) {
370
+			throw new \DomainException(
371
+					esc_html__(
372
+							'Invalid, unreadable, or missing file.',
373
+							'event_espresso'
374
+					)
375
+			);
376
+		}
377
+
378
+
379
+		if ($return_string) {
380
+			// because we want to return a string, we are going to capture the output
381
+			ob_start();
382
+			include($template_path);
383
+			return ob_get_clean();
384
+		} else {
385
+			include($template_path);
386
+		}
387
+		return '';
388
+	}
389
+
390
+
391
+	/**
392
+	 * get_object_css_class - attempts to generate a css class based on the type of EE object passed
393
+	 *
394
+	 * @param EE_Base_Class $object the EE object the css class is being generated for
395
+	 * @param  string       $prefix added to the beginning of the generated class
396
+	 * @param  string       $suffix added to the end of the generated class
397
+	 * @return string
398
+	 */
399
+	public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
400
+	{
401
+		// in the beginning...
402
+		$prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
403
+		// da muddle
404
+		$class = '';
405
+		// the end
406
+		$suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
407
+		// is the passed object an EE object ?
408
+		if ($object instanceof EE_Base_Class) {
409
+			// grab the exact type of object
410
+			$obj_class = get_class($object);
411
+			// depending on the type of object...
412
+			switch ($obj_class) {
413
+				// no specifics just yet...
414
+				default :
415
+					$class = strtolower(str_replace('_', '-', $obj_class));
416
+					$class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
417
+
418
+			}
419
+		}
420
+		return $prefix . $class . $suffix;
421
+	}
422
+
423
+
424
+
425
+	/**
426
+	 * EEH_Template::format_currency
427
+	 * This helper takes a raw float value and formats it according to the default config country currency settings, or
428
+	 * the country currency settings from the supplied country ISO code
429
+	 *
430
+	 * @param  float   $amount       raw money value
431
+	 * @param  boolean $return_raw   whether to return the formatted float value only with no currency sign or code
432
+	 * @param  boolean $display_code whether to display the country code (USD). Default = TRUE
433
+	 * @param string   $CNT_ISO      2 letter ISO code for a country
434
+	 * @param string   $cur_code_span_class
435
+	 * @return string        the html output for the formatted money value
436
+	 * @throws \EE_Error
437
+	 */
438
+	public static function format_currency(
439
+		$amount = null,
440
+		$return_raw = false,
441
+		$display_code = true,
442
+		$CNT_ISO = '',
443
+		$cur_code_span_class = 'currency-code'
444
+	) {
445
+		// ensure amount was received
446
+		if ($amount === null) {
447
+			$msg = __('In order to format currency, an amount needs to be passed.', 'event_espresso');
448
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
449
+			return '';
450
+		}
451
+		//ensure amount is float
452
+		$amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
453
+		$CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
454
+		// filter raw amount (allows 0.00 to be changed to "free" for example)
455
+		$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
456
+		// still a number or was amount converted to a string like "free" ?
457
+		if (is_float($amount_formatted)) {
458
+			// was a country ISO code passed ? if so generate currency config object for that country
459
+			$mny = $CNT_ISO !== '' ? new EE_Currency_Config($CNT_ISO) : null;
460
+			// verify results
461
+			if ( ! $mny instanceof EE_Currency_Config) {
462
+				// set default config country currency settings
463
+				$mny = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
464
+					? EE_Registry::instance()->CFG->currency
465
+					: new EE_Currency_Config();
466
+			}
467
+			// format float
468
+			$amount_formatted = number_format($amount, $mny->dec_plc, $mny->dec_mrk, $mny->thsnds);
469
+			// add formatting ?
470
+			if ( ! $return_raw) {
471
+				// add currency sign
472
+				if ($mny->sign_b4) {
473
+					if ($amount >= 0) {
474
+						$amount_formatted = $mny->sign . $amount_formatted;
475
+					} else {
476
+						$amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
477
+					}
478
+
479
+				} else {
480
+					$amount_formatted = $amount_formatted . $mny->sign;
481
+				}
482
+
483
+				// filter to allow global setting of display_code
484
+				$display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
485
+
486
+				// add currency code ?
487
+				$amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
488
+			}
489
+			// filter results
490
+			$amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
491
+				$amount_formatted, $mny, $return_raw);
492
+		}
493
+		// clean up vars
494
+		unset($mny);
495
+		// return formatted currency amount
496
+		return $amount_formatted;
497
+	}
498
+
499
+
500
+	/**
501
+	 * This function is used for outputting the localized label for a given status id in the schema requested (and
502
+	 * possibly plural).  The intended use of this function is only for cases where wanting a label outside of a
503
+	 * related status model or model object (i.e. in documentation etc.)
504
+	 *
505
+	 * @param  string  $status_id Status ID matching a registered status in the esp_status table.  If there is no
506
+	 *                            match, then 'Unknown' will be returned.
507
+	 * @param  boolean $plural    Whether to return plural or not
508
+	 * @param  string  $schema    'UPPER', 'lower', or 'Sentence'
509
+	 * @return string             The localized label for the status id.
510
+	 */
511
+	public static function pretty_status($status_id, $plural = false, $schema = 'upper')
512
+	{
513
+		/** @type EEM_Status $EEM_Status */
514
+		$EEM_Status = EE_Registry::instance()->load_model('Status');
515
+		$status     = $EEM_Status->localized_status(array($status_id => __('unknown', 'event_espresso')), $plural,
516
+			$schema);
517
+		return $status[$status_id];
518
+	}
519
+
520
+
521
+	/**
522
+	 * This helper just returns a button or link for the given parameters
523
+	 *
524
+	 * @param  string $url   the url for the link
525
+	 * @param  string $label What is the label you want displayed for the button
526
+	 * @param  string $class what class is used for the button (defaults to 'button-primary')
527
+	 * @param string  $icon
528
+	 * @param string  $title
529
+	 * @return string the html output for the button
530
+	 */
531
+	public static function get_button_or_link($url, $label, $class = 'button-primary', $icon = '', $title = '')
532
+	{
533
+		$icon_html = '';
534
+		if ( ! empty($icon)) {
535
+			$dashicons = preg_split("(ee-icon |dashicons )", $icon);
536
+			$dashicons = array_filter($dashicons);
537
+			$count     = count($dashicons);
538
+			$icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
539
+			foreach ($dashicons as $dashicon) {
540
+				$type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
541
+				$icon_html .= '<span class="' . $type . $dashicon . '"></span>';
542
+			}
543
+			$icon_html .= $count > 1 ? '</span>' : '';
544
+		}
545
+		$label  = ! empty($icon) ? $icon_html . $label : $label;
546
+		$button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . $url . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
547
+		return $button;
548
+	}
549
+
550
+
551
+	/**
552
+	 * This returns a generated link that will load the related help tab on admin pages.
553
+	 *
554
+	 * @param  string     $help_tab_id the id for the connected help tab
555
+	 * @param bool|string $page        The page identifier for the page the help tab is on
556
+	 * @param bool|string $action      The action (route) for the admin page the help tab is on.
557
+	 * @param bool|string $icon_style  (optional) include css class for the style you want to use for the help icon.
558
+	 * @param bool|string $help_text   (optional) send help text you want to use for the link if default not to be used
559
+	 * @return string              generated link
560
+	 */
561
+	public static function get_help_tab_link(
562
+		$help_tab_id,
563
+		$page = false,
564
+		$action = false,
565
+		$icon_style = false,
566
+		$help_text = false
567
+	) {
568
+
569
+		if ( ! $page) {
570
+			$page = isset($_REQUEST['page']) && ! empty($_REQUEST['page']) ? sanitize_key($_REQUEST['page']) : $page;
571
+		}
572
+
573
+		if ( ! $action) {
574
+			$action = isset($_REQUEST['action']) && ! empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : $action;
575
+		}
576
+
577
+		$action = empty($action) ? 'default' : $action;
578
+
579
+
580
+		$help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
581
+		$icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
582
+		$help_text    = ! $help_text ? '' : $help_text;
583
+		return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
584
+				'event_espresso') . '" > ' . $help_text . ' </a>';
585
+	}
586
+
587
+
588
+	/**
589
+	 * This helper generates the html structure for the jquery joyride plugin with the given params.
590
+	 *
591
+	 * @link http://zurb.com/playground/jquery-joyride-feature-tour-plugin
592
+	 * @see  EE_Admin_Page->_stop_callback() for the construct expected for the $stops param.
593
+	 * @param EE_Help_Tour
594
+	 * @return string         html
595
+	 */
596
+	public static function help_tour_stops_generator(EE_Help_Tour $tour)
597
+	{
598
+		$id    = $tour->get_slug();
599
+		$stops = $tour->get_stops();
600
+
601
+		$content = '<ol style="display:none" id="' . $id . '">';
602
+
603
+		foreach ($stops as $stop) {
604
+			$data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
605
+			$data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
606
+
607
+			//if container is set to modal then let's make sure we set the options accordingly
608
+			if (empty($data_id) && empty($data_class)) {
609
+				$stop['options']['modal']  = true;
610
+				$stop['options']['expose'] = true;
611
+			}
612
+
613
+			$custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
614
+			$button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
615
+			$inner_content = isset($stop['content']) ? $stop['content'] : '';
616
+
617
+			//options
618
+			if (isset($stop['options']) && is_array($stop['options'])) {
619
+				$options = ' data-options="';
620
+				foreach ($stop['options'] as $option => $value) {
621
+					$options .= $option . ':' . $value . ';';
622
+				}
623
+				$options .= '"';
624
+			} else {
625
+				$options = '';
626
+			}
627
+
628
+			//let's put all together
629
+			$content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
630
+		}
631
+
632
+		$content .= '</ol>';
633
+		return $content;
634
+	}
635
+
636
+
637
+	/**
638
+	 * This is a helper method to generate a status legend for a given status array.
639
+	 * Note this will only work if the incoming statuses have a key in the EEM_Status->localized_status() methods
640
+	 * status_array.
641
+	 *
642
+	 * @param  array  $status_array  array of statuses that will make up the legend. In format:
643
+	 *                               array(
644
+	 *                               'status_item' => 'status_name'
645
+	 *                               )
646
+	 * @param  string $active_status This is used to indicate what the active status is IF that is to be highlighted in
647
+	 *                               the legend.
648
+	 * @throws EE_Error
649
+	 * @return string               html structure for status.
650
+	 */
651
+	public static function status_legend($status_array, $active_status = '')
652
+	{
653
+		if ( ! is_array($status_array)) {
654
+			throw new EE_Error(esc_html__('The EEH_Template::status_legend helper required the incoming status_array argument to be an array!',
655
+				'event_espresso'));
656
+		}
657
+
658
+		$setup_array = array();
659
+		foreach ($status_array as $item => $status) {
660
+			$setup_array[$item] = array(
661
+				'class'  => 'ee-status-legend ee-status-legend-' . $status,
662
+				'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
663
+				'status' => $status,
664
+			);
665
+		}
666
+
667
+		$content = '<div class="ee-list-table-legend-container">' . "\n";
668
+		$content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
669
+		$content .= '<dl class="ee-list-table-legend">' . "\n\t";
670
+		foreach ($setup_array as $item => $details) {
671
+			$active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
672
+			$content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
673
+			$content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
674
+			$content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
675
+			$content .= '</dt>' . "\n";
676
+		}
677
+		$content .= '</dl>' . "\n";
678
+		$content .= '</div>' . "\n";
679
+		return $content;
680
+	}
681
+
682
+
683
+	/**
684
+	 * Gets HTML for laying out a deeply-nested array (and objects) in a format
685
+	 * that's nice for presenting in the wp admin
686
+	 *
687
+	 * @param mixed $data
688
+	 * @return string
689
+	 */
690
+	public static function layout_array_as_table($data)
691
+	{
692
+		if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
693
+			$data = (array)$data;
694
+		}
695
+		ob_start();
696
+		if (is_array($data)) {
697
+			if (EEH_Array::is_associative_array($data)) {
698
+				?>
699 699
                 <table class="widefat">
700 700
                     <tbody>
701 701
                     <?php
702
-                    foreach ($data as $data_key => $data_values) {
703
-                        ?>
702
+					foreach ($data as $data_key => $data_values) {
703
+						?>
704 704
                         <tr>
705 705
                             <td>
706 706
                                 <?php echo $data_key; ?>
@@ -710,248 +710,248 @@  discard block
 block discarded – undo
710 710
                             </td>
711 711
                         </tr>
712 712
                         <?php
713
-                    } ?>
713
+					} ?>
714 714
                     </tbody>
715 715
                 </table>
716 716
                 <?php
717
-            } else {
718
-                ?>
717
+			} else {
718
+				?>
719 719
                 <ul>
720 720
                     <?php
721
-                    foreach ($data as $datum) {
722
-                        echo "<li>";
723
-                        echo self::layout_array_as_table($datum);
724
-                        echo "</li>";
725
-                    } ?>
721
+					foreach ($data as $datum) {
722
+						echo "<li>";
723
+						echo self::layout_array_as_table($datum);
724
+						echo "</li>";
725
+					} ?>
726 726
                 </ul>
727 727
                 <?php
728
-            }
729
-        } else {
730
-            //simple value
731
-            echo esc_html($data);
732
-        }
733
-        return ob_get_clean();
734
-    }
735
-
736
-
737
-    /**
738
-     * wrapper for self::get_paging_html() that simply echos the generated paging html
739
-     *
740
-     * @since 4.4.0
741
-     * @see   self:get_paging_html() for argument docs.
742
-     * @param        $total_items
743
-     * @param        $current
744
-     * @param        $per_page
745
-     * @param        $url
746
-     * @param bool   $show_num_field
747
-     * @param string $paged_arg_name
748
-     * @param array  $items_label
749
-     * @return string
750
-     */
751
-    public static function paging_html(
752
-        $total_items,
753
-        $current,
754
-        $per_page,
755
-        $url,
756
-        $show_num_field = true,
757
-        $paged_arg_name = 'paged',
758
-        $items_label = array()
759
-    ) {
760
-        echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
761
-            $items_label);
762
-    }
763
-
764
-
765
-    /**
766
-     * A method for generating paging similar to WP_List_Table
767
-     *
768
-     * @since    4.4.0
769
-     * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
770
-     * @param  integer $total_items     How many total items there are to page.
771
-     * @param  integer $current         What the current page is.
772
-     * @param  integer $per_page        How many items per page.
773
-     * @param  string  $url             What the base url for page links is.
774
-     * @param  boolean $show_num_field  Whether to show the input for changing page number.
775
-     * @param  string  $paged_arg_name  The name of the key for the paged query argument.
776
-     * @param  array   $items_label     An array of singular/plural values for the items label:
777
-     *                                  array(
778
-     *                                  'single' => 'item',
779
-     *                                  'plural' => 'items'
780
-     *                                  )
781
-     * @return  string
782
-     */
783
-    public static function get_paging_html(
784
-        $total_items,
785
-        $current,
786
-        $per_page,
787
-        $url,
788
-        $show_num_field = true,
789
-        $paged_arg_name = 'paged',
790
-        $items_label = array()
791
-    ) {
792
-        $page_links     = array();
793
-        $disable_first  = $disable_last = '';
794
-        $total_items    = (int)$total_items;
795
-        $per_page       = (int)$per_page;
796
-        $current        = (int)$current;
797
-        $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
798
-
799
-        //filter items_label
800
-        $items_label = apply_filters(
801
-            'FHEE__EEH_Template__get_paging_html__items_label',
802
-            $items_label
803
-        );
804
-
805
-        if (empty($items_label)
806
-            || ! is_array($items_label)
807
-            || ! isset($items_label['single'])
808
-            || ! isset($items_label['plural'])
809
-        ) {
810
-            $items_label = array(
811
-                'single' => __('1 item', 'event_espresso'),
812
-                'plural' => __('%s items', 'event_espresso'),
813
-            );
814
-        } else {
815
-            $items_label = array(
816
-                'single' => '1 ' . esc_html($items_label['single']),
817
-                'plural' => '%s ' . esc_html($items_label['plural']),
818
-            );
819
-        }
820
-
821
-        $total_pages = ceil($total_items / $per_page);
822
-
823
-        if ($total_pages <= 1) {
824
-            return '';
825
-        }
826
-
827
-        $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
828
-
829
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
830
-
831
-        if ($current === 1) {
832
-            $disable_first = ' disabled';
833
-        }
834
-        if ($current == $total_pages) {
835
-            $disable_last = ' disabled';
836
-        }
837
-
838
-        $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
839
-            'first-page' . $disable_first,
840
-            esc_attr__('Go to the first page'),
841
-            esc_url(remove_query_arg($paged_arg_name, $url)),
842
-            '&laquo;'
843
-        );
844
-
845
-        $page_links[] = sprintf(
846
-            '<a class="%s" title="%s" href="%s">%s</a>',
847
-            'prev-page' . $disable_first,
848
-            esc_attr__('Go to the previous page'),
849
-            esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
850
-            '&lsaquo;'
851
-        );
852
-
853
-        if ( ! $show_num_field) {
854
-            $html_current_page = $current;
855
-        } else {
856
-            $html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
857
-                esc_attr__('Current page'),
858
-                $current,
859
-                strlen($total_pages)
860
-            );
861
-        }
862
-
863
-        $html_total_pages = sprintf(
864
-            '<span class="total-pages">%s</span>',
865
-            number_format_i18n($total_pages)
866
-        );
867
-        $page_links[]     = sprintf(
868
-            _x('%3$s%1$s of %2$s%4$s', 'paging'),
869
-            $html_current_page,
870
-            $html_total_pages,
871
-            '<span class="paging-input">',
872
-            '</span>'
873
-        );
874
-
875
-        $page_links[] = sprintf(
876
-            '<a class="%s" title="%s" href="%s">%s</a>',
877
-            'next-page' . $disable_last,
878
-            esc_attr__('Go to the next page'),
879
-            esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
880
-            '&rsaquo;'
881
-        );
882
-
883
-        $page_links[] = sprintf(
884
-            '<a class="%s" title="%s" href="%s">%s</a>',
885
-            'last-page' . $disable_last,
886
-            esc_attr__('Go to the last page'),
887
-            esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
888
-            '&raquo;'
889
-        );
890
-
891
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
892
-        // set page class
893
-        if ($total_pages) {
894
-            $page_class = $total_pages < 2 ? ' one-page' : '';
895
-        } else {
896
-            $page_class = ' no-pages';
897
-        }
898
-
899
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
900
-    }
901
-
902
-
903
-    /**
904
-     * @param string $wrap_class
905
-     * @param string $wrap_id
906
-     * @return string
907
-     */
908
-    public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
909
-    {
910
-        $admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
911
-        if (
912
-            ! $admin &&
913
-            ! apply_filters(
914
-                'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
915
-                EE_Registry::instance()->CFG->admin->show_reg_footer
916
-            )
917
-        ) {
918
-            return '';
919
-        }
920
-        $tag        = $admin ? 'span' : 'div';
921
-        $attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
922
-        $wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
923
-        $attributes .= ! empty($wrap_class)
924
-            ? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
925
-            : ' class="powered-by-event-espresso-credit"';
926
-        $query_args = array_merge(
927
-            array(
928
-                'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
929
-                'utm_source'   => 'powered_by_event_espresso',
930
-                'utm_medium'   => 'link',
931
-                'utm_campaign' => 'powered_by',
932
-            ),
933
-            $query_args
934
-        );
935
-        $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
936
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
937
-        $url        = add_query_arg($query_args, 'https://eventespresso.com/');
938
-        $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
939
-        return (string)apply_filters(
940
-            'FHEE__EEH_Template__powered_by_event_espresso__html',
941
-            sprintf(
942
-                esc_html_x(
943
-                    '%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
944
-                    'Online event registration and ticketing powered by [link to eventespresso.com]',
945
-                    'event_espresso'
946
-                ),
947
-                "<{$tag}{$attributes}>",
948
-                "<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
949
-                $admin ? '' : '<br />'
950
-            ),
951
-            $wrap_class,
952
-            $wrap_id
953
-        );
954
-    }
728
+			}
729
+		} else {
730
+			//simple value
731
+			echo esc_html($data);
732
+		}
733
+		return ob_get_clean();
734
+	}
735
+
736
+
737
+	/**
738
+	 * wrapper for self::get_paging_html() that simply echos the generated paging html
739
+	 *
740
+	 * @since 4.4.0
741
+	 * @see   self:get_paging_html() for argument docs.
742
+	 * @param        $total_items
743
+	 * @param        $current
744
+	 * @param        $per_page
745
+	 * @param        $url
746
+	 * @param bool   $show_num_field
747
+	 * @param string $paged_arg_name
748
+	 * @param array  $items_label
749
+	 * @return string
750
+	 */
751
+	public static function paging_html(
752
+		$total_items,
753
+		$current,
754
+		$per_page,
755
+		$url,
756
+		$show_num_field = true,
757
+		$paged_arg_name = 'paged',
758
+		$items_label = array()
759
+	) {
760
+		echo self::get_paging_html($total_items, $current, $per_page, $url, $show_num_field, $paged_arg_name,
761
+			$items_label);
762
+	}
763
+
764
+
765
+	/**
766
+	 * A method for generating paging similar to WP_List_Table
767
+	 *
768
+	 * @since    4.4.0
769
+	 * @see      wp-admin/includes/class-wp-list-table.php WP_List_Table::pagination()
770
+	 * @param  integer $total_items     How many total items there are to page.
771
+	 * @param  integer $current         What the current page is.
772
+	 * @param  integer $per_page        How many items per page.
773
+	 * @param  string  $url             What the base url for page links is.
774
+	 * @param  boolean $show_num_field  Whether to show the input for changing page number.
775
+	 * @param  string  $paged_arg_name  The name of the key for the paged query argument.
776
+	 * @param  array   $items_label     An array of singular/plural values for the items label:
777
+	 *                                  array(
778
+	 *                                  'single' => 'item',
779
+	 *                                  'plural' => 'items'
780
+	 *                                  )
781
+	 * @return  string
782
+	 */
783
+	public static function get_paging_html(
784
+		$total_items,
785
+		$current,
786
+		$per_page,
787
+		$url,
788
+		$show_num_field = true,
789
+		$paged_arg_name = 'paged',
790
+		$items_label = array()
791
+	) {
792
+		$page_links     = array();
793
+		$disable_first  = $disable_last = '';
794
+		$total_items    = (int)$total_items;
795
+		$per_page       = (int)$per_page;
796
+		$current        = (int)$current;
797
+		$paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
798
+
799
+		//filter items_label
800
+		$items_label = apply_filters(
801
+			'FHEE__EEH_Template__get_paging_html__items_label',
802
+			$items_label
803
+		);
804
+
805
+		if (empty($items_label)
806
+			|| ! is_array($items_label)
807
+			|| ! isset($items_label['single'])
808
+			|| ! isset($items_label['plural'])
809
+		) {
810
+			$items_label = array(
811
+				'single' => __('1 item', 'event_espresso'),
812
+				'plural' => __('%s items', 'event_espresso'),
813
+			);
814
+		} else {
815
+			$items_label = array(
816
+				'single' => '1 ' . esc_html($items_label['single']),
817
+				'plural' => '%s ' . esc_html($items_label['plural']),
818
+			);
819
+		}
820
+
821
+		$total_pages = ceil($total_items / $per_page);
822
+
823
+		if ($total_pages <= 1) {
824
+			return '';
825
+		}
826
+
827
+		$item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
828
+
829
+		$output = '<span class="displaying-num">' . $item_label . '</span>';
830
+
831
+		if ($current === 1) {
832
+			$disable_first = ' disabled';
833
+		}
834
+		if ($current == $total_pages) {
835
+			$disable_last = ' disabled';
836
+		}
837
+
838
+		$page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
839
+			'first-page' . $disable_first,
840
+			esc_attr__('Go to the first page'),
841
+			esc_url(remove_query_arg($paged_arg_name, $url)),
842
+			'&laquo;'
843
+		);
844
+
845
+		$page_links[] = sprintf(
846
+			'<a class="%s" title="%s" href="%s">%s</a>',
847
+			'prev-page' . $disable_first,
848
+			esc_attr__('Go to the previous page'),
849
+			esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
850
+			'&lsaquo;'
851
+		);
852
+
853
+		if ( ! $show_num_field) {
854
+			$html_current_page = $current;
855
+		} else {
856
+			$html_current_page = sprintf("<input class='current-page' title='%s' type='text' name=$paged_arg_name value='%s' size='%d' />",
857
+				esc_attr__('Current page'),
858
+				$current,
859
+				strlen($total_pages)
860
+			);
861
+		}
862
+
863
+		$html_total_pages = sprintf(
864
+			'<span class="total-pages">%s</span>',
865
+			number_format_i18n($total_pages)
866
+		);
867
+		$page_links[]     = sprintf(
868
+			_x('%3$s%1$s of %2$s%4$s', 'paging'),
869
+			$html_current_page,
870
+			$html_total_pages,
871
+			'<span class="paging-input">',
872
+			'</span>'
873
+		);
874
+
875
+		$page_links[] = sprintf(
876
+			'<a class="%s" title="%s" href="%s">%s</a>',
877
+			'next-page' . $disable_last,
878
+			esc_attr__('Go to the next page'),
879
+			esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
880
+			'&rsaquo;'
881
+		);
882
+
883
+		$page_links[] = sprintf(
884
+			'<a class="%s" title="%s" href="%s">%s</a>',
885
+			'last-page' . $disable_last,
886
+			esc_attr__('Go to the last page'),
887
+			esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
888
+			'&raquo;'
889
+		);
890
+
891
+		$output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
892
+		// set page class
893
+		if ($total_pages) {
894
+			$page_class = $total_pages < 2 ? ' one-page' : '';
895
+		} else {
896
+			$page_class = ' no-pages';
897
+		}
898
+
899
+		return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
900
+	}
901
+
902
+
903
+	/**
904
+	 * @param string $wrap_class
905
+	 * @param string $wrap_id
906
+	 * @return string
907
+	 */
908
+	public static function powered_by_event_espresso($wrap_class = '', $wrap_id = '', array $query_args = array())
909
+	{
910
+		$admin = is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX);
911
+		if (
912
+			! $admin &&
913
+			! apply_filters(
914
+				'FHEE__EEH_Template__powered_by_event_espresso__show_reg_footer',
915
+				EE_Registry::instance()->CFG->admin->show_reg_footer
916
+			)
917
+		) {
918
+			return '';
919
+		}
920
+		$tag        = $admin ? 'span' : 'div';
921
+		$attributes = ! empty($wrap_id) ? " id=\"{$wrap_id}\"" : '';
922
+		$wrap_class = $admin ? "{$wrap_class} float-left" : $wrap_class;
923
+		$attributes .= ! empty($wrap_class)
924
+			? " class=\"{$wrap_class} powered-by-event-espresso-credit\""
925
+			: ' class="powered-by-event-espresso-credit"';
926
+		$query_args = array_merge(
927
+			array(
928
+				'ap_id'        => EE_Registry::instance()->CFG->admin->affiliate_id(),
929
+				'utm_source'   => 'powered_by_event_espresso',
930
+				'utm_medium'   => 'link',
931
+				'utm_campaign' => 'powered_by',
932
+			),
933
+			$query_args
934
+		);
935
+		$powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
936
+			$admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
937
+		$url        = add_query_arg($query_args, 'https://eventespresso.com/');
938
+		$url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
939
+		return (string)apply_filters(
940
+			'FHEE__EEH_Template__powered_by_event_espresso__html',
941
+			sprintf(
942
+				esc_html_x(
943
+					'%3$s%1$sOnline event registration and ticketing powered by %2$s%3$s',
944
+					'Online event registration and ticketing powered by [link to eventespresso.com]',
945
+					'event_espresso'
946
+				),
947
+				"<{$tag}{$attributes}>",
948
+				"<a href=\"{$url}\" target=\"_blank\" rel=\"nofollow\">{$powered_by}</a></{$tag}>",
949
+				$admin ? '' : '<br />'
950
+			),
951
+			$wrap_class,
952
+			$wrap_id
953
+		);
954
+	}
955 955
 
956 956
 
957 957
 } //end EEH_Template class
@@ -960,33 +960,33 @@  discard block
 block discarded – undo
960 960
 
961 961
 
962 962
 if ( ! function_exists('espresso_pagination')) {
963
-    /**
964
-     *    espresso_pagination
965
-     *
966
-     * @access    public
967
-     * @return    void
968
-     */
969
-    function espresso_pagination()
970
-    {
971
-        global $wp_query;
972
-        $big        = 999999999; // need an unlikely integer
973
-        $pagination = paginate_links(
974
-            array(
975
-                'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
976
-                'format'       => '?paged=%#%',
977
-                'current'      => max(1, get_query_var('paged')),
978
-                'total'        => $wp_query->max_num_pages,
979
-                'show_all'     => true,
980
-                'end_size'     => 10,
981
-                'mid_size'     => 6,
982
-                'prev_next'    => true,
983
-                'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
984
-                'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
985
-                'type'         => 'plain',
986
-                'add_args'     => false,
987
-                'add_fragment' => '',
988
-            )
989
-        );
990
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv clear">' . $pagination . '</div>' : '';
991
-    }
963
+	/**
964
+	 *    espresso_pagination
965
+	 *
966
+	 * @access    public
967
+	 * @return    void
968
+	 */
969
+	function espresso_pagination()
970
+	{
971
+		global $wp_query;
972
+		$big        = 999999999; // need an unlikely integer
973
+		$pagination = paginate_links(
974
+			array(
975
+				'base'         => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
976
+				'format'       => '?paged=%#%',
977
+				'current'      => max(1, get_query_var('paged')),
978
+				'total'        => $wp_query->max_num_pages,
979
+				'show_all'     => true,
980
+				'end_size'     => 10,
981
+				'mid_size'     => 6,
982
+				'prev_next'    => true,
983
+				'prev_text'    => __('&lsaquo; PREV', 'event_espresso'),
984
+				'next_text'    => __('NEXT &rsaquo;', 'event_espresso'),
985
+				'type'         => 'plain',
986
+				'add_args'     => false,
987
+				'add_fragment' => '',
988
+			)
989
+		);
990
+		echo ! empty($pagination) ? '<div class="ee-pagination-dv clear">' . $pagination . '</div>' : '';
991
+	}
992 992
 }
993 993
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 /**
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
     public static function load_espresso_theme_functions()
82 82
     {
83 83
         if ( ! defined('EE_THEME_FUNCTIONS_LOADED')) {
84
-            if (is_readable(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php')) {
85
-                require_once(EE_PUBLIC . EE_Config::get_current_theme() . DS . 'functions.php');
84
+            if (is_readable(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php')) {
85
+                require_once(EE_PUBLIC.EE_Config::get_current_theme().DS.'functions.php');
86 86
             }
87 87
         }
88 88
     }
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
     public static function get_espresso_themes()
97 97
     {
98 98
         if (empty(EEH_Template::$_espresso_themes)) {
99
-            $espresso_themes = glob(EE_PUBLIC . '*', GLOB_ONLYDIR);
99
+            $espresso_themes = glob(EE_PUBLIC.'*', GLOB_ONLYDIR);
100 100
             if (empty($espresso_themes)) {
101 101
                 return array();
102 102
             }
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
     ) {
133 133
         do_action("get_template_part_{$slug}-{$name}", $slug, $name);
134 134
         $templates = array();
135
-        $name      = (string)$name;
135
+        $name      = (string) $name;
136 136
         if ($name != '') {
137 137
             $templates[] = "{$slug}-{$name}.php";
138 138
         }
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
                 if (isset($EE_CPTs[$post_type])) {
212 212
                     $archive_or_single = is_archive() ? 'archive' : '';
213 213
                     $archive_or_single = is_single() ? 'single' : $archive_or_single;
214
-                    $templates         = $archive_or_single . '-' . $post_type . '.php';
214
+                    $templates         = $archive_or_single.'-'.$post_type.'.php';
215 215
                 }
216 216
             }
217 217
             // currently active EE template theme
@@ -220,18 +220,18 @@  discard block
 block discarded – undo
220 220
             // array of paths to folders that may contain templates
221 221
             $template_folder_paths = array(
222 222
                 // first check the /wp-content/uploads/espresso/templates/(current EE theme)/  folder for an EE theme template file
223
-                EVENT_ESPRESSO_TEMPLATE_DIR . $current_theme,
223
+                EVENT_ESPRESSO_TEMPLATE_DIR.$current_theme,
224 224
                 // then in the root of the /wp-content/uploads/espresso/templates/ folder
225 225
                 EVENT_ESPRESSO_TEMPLATE_DIR,
226 226
             );
227 227
 
228 228
             //add core plugin folders for checking only if we're not $check_if_custom
229 229
             if ( ! $check_if_custom) {
230
-                $core_paths            = array(
230
+                $core_paths = array(
231 231
                     // in the  /wp-content/plugins/(EE4 folder)/public/(current EE theme)/ folder within the plugin
232
-                    EE_PUBLIC . $current_theme,
232
+                    EE_PUBLIC.$current_theme,
233 233
                     // in the  /wp-content/plugins/(EE4 folder)/core/templates/(current EE theme)/ folder within the plugin
234
-                    EE_TEMPLATES . $current_theme,
234
+                    EE_TEMPLATES.$current_theme,
235 235
                     // or maybe relative from the plugin root: /wp-content/plugins/(EE4 folder)/
236 236
                     EE_PLUGIN_DIR_PATH,
237 237
                 );
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
                     );
263 263
                     if ($common_base_path !== '') {
264 264
                         // both paths have a common base, so just tack the filename onto our search path
265
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $file_name;
265
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$file_name;
266 266
                     } else {
267 267
                         // no common base path, so let's just concatenate
268
-                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path) . $template;
268
+                        $resolved_path = EEH_File::end_with_directory_separator($template_folder_path).$template;
269 269
                     }
270 270
                     // build up our template locations array by adding our resolved paths
271 271
                     $full_template_paths[] = $resolved_path;
@@ -273,13 +273,13 @@  discard block
 block discarded – undo
273 273
                 // if $template is an absolute path, then we'll tack it onto the start of our array so that it gets searched first
274 274
                 array_unshift($full_template_paths, $template);
275 275
                 // path to the directory of the current theme: /wp-content/themes/(current WP theme)/
276
-                array_unshift($full_template_paths, get_stylesheet_directory() . DS . $file_name);
276
+                array_unshift($full_template_paths, get_stylesheet_directory().DS.$file_name);
277 277
             }
278 278
             // filter final array of full template paths
279 279
             $full_template_paths = apply_filters('FHEE__EEH_Template__locate_template__full_template_paths',
280 280
                 $full_template_paths, $file_name);
281 281
             // now loop through our final array of template location paths and check each location
282
-            foreach ((array)$full_template_paths as $full_template_path) {
282
+            foreach ((array) $full_template_paths as $full_template_path) {
283 283
                 if (is_readable($full_template_path)) {
284 284
                     $template_path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $full_template_path);
285 285
                     // hook that can be used to display the full template path that will be used
@@ -364,9 +364,9 @@  discard block
 block discarded – undo
364 364
         if ( ! is_array($template_args) && ! is_object($template_args)) {
365 365
             $template_args = array($template_args);
366 366
         }
367
-        extract( $template_args, EXTR_SKIP );
367
+        extract($template_args, EXTR_SKIP);
368 368
         // ignore whether template is accessible ?
369
-        if ( $throw_exceptions && ! is_readable( $template_path ) ) {
369
+        if ($throw_exceptions && ! is_readable($template_path)) {
370 370
             throw new \DomainException(
371 371
                     esc_html__(
372 372
                             'Invalid, unreadable, or missing file.',
@@ -399,11 +399,11 @@  discard block
 block discarded – undo
399 399
     public static function get_object_css_class($object = null, $prefix = '', $suffix = '')
400 400
     {
401 401
         // in the beginning...
402
-        $prefix = ! empty($prefix) ? rtrim($prefix, '-') . '-' : '';
402
+        $prefix = ! empty($prefix) ? rtrim($prefix, '-').'-' : '';
403 403
         // da muddle
404 404
         $class = '';
405 405
         // the end
406
-        $suffix = ! empty($suffix) ? '-' . ltrim($suffix, '-') : '';
406
+        $suffix = ! empty($suffix) ? '-'.ltrim($suffix, '-') : '';
407 407
         // is the passed object an EE object ?
408 408
         if ($object instanceof EE_Base_Class) {
409 409
             // grab the exact type of object
@@ -413,11 +413,11 @@  discard block
 block discarded – undo
413 413
                 // no specifics just yet...
414 414
                 default :
415 415
                     $class = strtolower(str_replace('_', '-', $obj_class));
416
-                    $class .= method_exists($obj_class, 'name') ? '-' . sanitize_title($object->name()) : '';
416
+                    $class .= method_exists($obj_class, 'name') ? '-'.sanitize_title($object->name()) : '';
417 417
 
418 418
             }
419 419
         }
420
-        return $prefix . $class . $suffix;
420
+        return $prefix.$class.$suffix;
421 421
     }
422 422
 
423 423
 
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
             return '';
450 450
         }
451 451
         //ensure amount is float
452
-        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float)$amount);
452
+        $amount  = apply_filters('FHEE__EEH_Template__format_currency__raw_amount', (float) $amount);
453 453
         $CNT_ISO = apply_filters('FHEE__EEH_Template__format_currency__CNT_ISO', $CNT_ISO, $amount);
454 454
         // filter raw amount (allows 0.00 to be changed to "free" for example)
455 455
         $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount', $amount, $return_raw);
@@ -471,20 +471,20 @@  discard block
 block discarded – undo
471 471
                 // add currency sign
472 472
                 if ($mny->sign_b4) {
473 473
                     if ($amount >= 0) {
474
-                        $amount_formatted = $mny->sign . $amount_formatted;
474
+                        $amount_formatted = $mny->sign.$amount_formatted;
475 475
                     } else {
476
-                        $amount_formatted = '-' . $mny->sign . str_replace('-', '', $amount_formatted);
476
+                        $amount_formatted = '-'.$mny->sign.str_replace('-', '', $amount_formatted);
477 477
                     }
478 478
 
479 479
                 } else {
480
-                    $amount_formatted = $amount_formatted . $mny->sign;
480
+                    $amount_formatted = $amount_formatted.$mny->sign;
481 481
                 }
482 482
 
483 483
                 // filter to allow global setting of display_code
484 484
                 $display_code = apply_filters('FHEE__EEH_Template__format_currency__display_code', $display_code);
485 485
 
486 486
                 // add currency code ?
487
-                $amount_formatted = $display_code ? $amount_formatted . ' <span class="' . $cur_code_span_class . '">(' . $mny->code . ')</span>' : $amount_formatted;
487
+                $amount_formatted = $display_code ? $amount_formatted.' <span class="'.$cur_code_span_class.'">('.$mny->code.')</span>' : $amount_formatted;
488 488
             }
489 489
             // filter results
490 490
             $amount_formatted = apply_filters('FHEE__EEH_Template__format_currency__amount_formatted',
@@ -538,12 +538,12 @@  discard block
 block discarded – undo
538 538
             $icon_html .= $count > 1 ? '<span class="ee-composite-dashicon">' : '';
539 539
             foreach ($dashicons as $dashicon) {
540 540
                 $type = strpos($dashicon, 'ee-icon') !== false ? 'ee-icon ' : 'dashicons ';
541
-                $icon_html .= '<span class="' . $type . $dashicon . '"></span>';
541
+                $icon_html .= '<span class="'.$type.$dashicon.'"></span>';
542 542
             }
543 543
             $icon_html .= $count > 1 ? '</span>' : '';
544 544
         }
545
-        $label  = ! empty($icon) ? $icon_html . $label : $label;
546
-        $button = '<a id="' . sanitize_title_with_dashes($label) . '" href="' . $url . '" class="' . $class . '" title="' . $title . '">' . $label . '</a>';
545
+        $label  = ! empty($icon) ? $icon_html.$label : $label;
546
+        $button = '<a id="'.sanitize_title_with_dashes($label).'" href="'.$url.'" class="'.$class.'" title="'.$title.'">'.$label.'</a>';
547 547
         return $button;
548 548
     }
549 549
 
@@ -577,11 +577,11 @@  discard block
 block discarded – undo
577 577
         $action = empty($action) ? 'default' : $action;
578 578
 
579 579
 
580
-        $help_tab_lnk = $page . '-' . $action . '-' . $help_tab_id;
580
+        $help_tab_lnk = $page.'-'.$action.'-'.$help_tab_id;
581 581
         $icon         = ! $icon_style ? ' dashicons-editor-help' : $icon_style;
582 582
         $help_text    = ! $help_text ? '' : $help_text;
583
-        return '<a id="' . $help_tab_lnk . '" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22' . $icon . '" title="' . esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
584
-                'event_espresso') . '" > ' . $help_text . ' </a>';
583
+        return '<a id="'.$help_tab_lnk.'" class="ee-clickable dashicons espresso-help-tab-lnk ee-icon-size-22'.$icon.'" title="'.esc_attr__('Click to open the \'Help\' tab for more information about this feature.',
584
+                'event_espresso').'" > '.$help_text.' </a>';
585 585
     }
586 586
 
587 587
 
@@ -598,11 +598,11 @@  discard block
 block discarded – undo
598 598
         $id    = $tour->get_slug();
599 599
         $stops = $tour->get_stops();
600 600
 
601
-        $content = '<ol style="display:none" id="' . $id . '">';
601
+        $content = '<ol style="display:none" id="'.$id.'">';
602 602
 
603 603
         foreach ($stops as $stop) {
604
-            $data_id    = ! empty($stop['id']) ? ' data-id="' . $stop['id'] . '"' : '';
605
-            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="' . $stop['class'] . '"' : '';
604
+            $data_id    = ! empty($stop['id']) ? ' data-id="'.$stop['id'].'"' : '';
605
+            $data_class = empty($data_id) && ! empty($stop['class']) ? ' data-class="'.$stop['class'].'"' : '';
606 606
 
607 607
             //if container is set to modal then let's make sure we set the options accordingly
608 608
             if (empty($data_id) && empty($data_class)) {
@@ -610,15 +610,15 @@  discard block
 block discarded – undo
610 610
                 $stop['options']['expose'] = true;
611 611
             }
612 612
 
613
-            $custom_class  = ! empty($stop['custom_class']) ? ' class="' . $stop['custom_class'] . '"' : '';
614
-            $button_text   = ! empty($stop['button_text']) ? ' data-button="' . $stop['button_text'] . '"' : '';
613
+            $custom_class  = ! empty($stop['custom_class']) ? ' class="'.$stop['custom_class'].'"' : '';
614
+            $button_text   = ! empty($stop['button_text']) ? ' data-button="'.$stop['button_text'].'"' : '';
615 615
             $inner_content = isset($stop['content']) ? $stop['content'] : '';
616 616
 
617 617
             //options
618 618
             if (isset($stop['options']) && is_array($stop['options'])) {
619 619
                 $options = ' data-options="';
620 620
                 foreach ($stop['options'] as $option => $value) {
621
-                    $options .= $option . ':' . $value . ';';
621
+                    $options .= $option.':'.$value.';';
622 622
                 }
623 623
                 $options .= '"';
624 624
             } else {
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
             }
627 627
 
628 628
             //let's put all together
629
-            $content .= '<li' . $data_id . $data_class . $custom_class . $button_text . $options . '>' . $inner_content . '</li>';
629
+            $content .= '<li'.$data_id.$data_class.$custom_class.$button_text.$options.'>'.$inner_content.'</li>';
630 630
         }
631 631
 
632 632
         $content .= '</ol>';
@@ -658,24 +658,24 @@  discard block
 block discarded – undo
658 658
         $setup_array = array();
659 659
         foreach ($status_array as $item => $status) {
660 660
             $setup_array[$item] = array(
661
-                'class'  => 'ee-status-legend ee-status-legend-' . $status,
661
+                'class'  => 'ee-status-legend ee-status-legend-'.$status,
662 662
                 'desc'   => EEH_Template::pretty_status($status, false, 'sentence'),
663 663
                 'status' => $status,
664 664
             );
665 665
         }
666 666
 
667
-        $content = '<div class="ee-list-table-legend-container">' . "\n";
668
-        $content .= '<h4 class="status-legend-title">' . esc_html__('Status Legend', 'event_espresso') . '</h4>' . "\n";
669
-        $content .= '<dl class="ee-list-table-legend">' . "\n\t";
667
+        $content = '<div class="ee-list-table-legend-container">'."\n";
668
+        $content .= '<h4 class="status-legend-title">'.esc_html__('Status Legend', 'event_espresso').'</h4>'."\n";
669
+        $content .= '<dl class="ee-list-table-legend">'."\n\t";
670 670
         foreach ($setup_array as $item => $details) {
671 671
             $active_class = $active_status == $details['status'] ? ' class="ee-is-active-status"' : '';
672
-            $content .= '<dt id="ee-legend-item-tooltip-' . $item . '"' . $active_class . '>' . "\n\t\t";
673
-            $content .= '<span class="' . $details['class'] . '"></span>' . "\n\t\t";
674
-            $content .= '<span class="ee-legend-description">' . $details['desc'] . '</span>' . "\n\t";
675
-            $content .= '</dt>' . "\n";
672
+            $content .= '<dt id="ee-legend-item-tooltip-'.$item.'"'.$active_class.'>'."\n\t\t";
673
+            $content .= '<span class="'.$details['class'].'"></span>'."\n\t\t";
674
+            $content .= '<span class="ee-legend-description">'.$details['desc'].'</span>'."\n\t";
675
+            $content .= '</dt>'."\n";
676 676
         }
677
-        $content .= '</dl>' . "\n";
678
-        $content .= '</div>' . "\n";
677
+        $content .= '</dl>'."\n";
678
+        $content .= '</div>'."\n";
679 679
         return $content;
680 680
     }
681 681
 
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
     public static function layout_array_as_table($data)
691 691
     {
692 692
         if (is_object($data) || $data instanceof __PHP_Incomplete_Class) {
693
-            $data = (array)$data;
693
+            $data = (array) $data;
694 694
         }
695 695
         ob_start();
696 696
         if (is_array($data)) {
@@ -791,9 +791,9 @@  discard block
 block discarded – undo
791 791
     ) {
792 792
         $page_links     = array();
793 793
         $disable_first  = $disable_last = '';
794
-        $total_items    = (int)$total_items;
795
-        $per_page       = (int)$per_page;
796
-        $current        = (int)$current;
794
+        $total_items    = (int) $total_items;
795
+        $per_page       = (int) $per_page;
796
+        $current        = (int) $current;
797 797
         $paged_arg_name = empty($paged_arg_name) ? 'paged' : sanitize_key($paged_arg_name);
798 798
 
799 799
         //filter items_label
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
             );
814 814
         } else {
815 815
             $items_label = array(
816
-                'single' => '1 ' . esc_html($items_label['single']),
817
-                'plural' => '%s ' . esc_html($items_label['plural']),
816
+                'single' => '1 '.esc_html($items_label['single']),
817
+                'plural' => '%s '.esc_html($items_label['plural']),
818 818
             );
819 819
         }
820 820
 
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 
827 827
         $item_label = $total_items > 1 ? sprintf($items_label['plural'], $total_items) : $items_label['single'];
828 828
 
829
-        $output = '<span class="displaying-num">' . $item_label . '</span>';
829
+        $output = '<span class="displaying-num">'.$item_label.'</span>';
830 830
 
831 831
         if ($current === 1) {
832 832
             $disable_first = ' disabled';
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
         }
837 837
 
838 838
         $page_links[] = sprintf("<a class='%s' title='%s' href='%s'>%s</a>",
839
-            'first-page' . $disable_first,
839
+            'first-page'.$disable_first,
840 840
             esc_attr__('Go to the first page'),
841 841
             esc_url(remove_query_arg($paged_arg_name, $url)),
842 842
             '&laquo;'
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
 
845 845
         $page_links[] = sprintf(
846 846
             '<a class="%s" title="%s" href="%s">%s</a>',
847
-            'prev-page' . $disable_first,
847
+            'prev-page'.$disable_first,
848 848
             esc_attr__('Go to the previous page'),
849 849
             esc_url(add_query_arg($paged_arg_name, max(1, $current - 1), $url)),
850 850
             '&lsaquo;'
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
             '<span class="total-pages">%s</span>',
865 865
             number_format_i18n($total_pages)
866 866
         );
867
-        $page_links[]     = sprintf(
867
+        $page_links[] = sprintf(
868 868
             _x('%3$s%1$s of %2$s%4$s', 'paging'),
869 869
             $html_current_page,
870 870
             $html_total_pages,
@@ -874,7 +874,7 @@  discard block
 block discarded – undo
874 874
 
875 875
         $page_links[] = sprintf(
876 876
             '<a class="%s" title="%s" href="%s">%s</a>',
877
-            'next-page' . $disable_last,
877
+            'next-page'.$disable_last,
878 878
             esc_attr__('Go to the next page'),
879 879
             esc_url(add_query_arg($paged_arg_name, min($total_pages, $current + 1), $url)),
880 880
             '&rsaquo;'
@@ -882,13 +882,13 @@  discard block
 block discarded – undo
882 882
 
883 883
         $page_links[] = sprintf(
884 884
             '<a class="%s" title="%s" href="%s">%s</a>',
885
-            'last-page' . $disable_last,
885
+            'last-page'.$disable_last,
886 886
             esc_attr__('Go to the last page'),
887 887
             esc_url(add_query_arg($paged_arg_name, $total_pages, $url)),
888 888
             '&raquo;'
889 889
         );
890 890
 
891
-        $output .= "\n" . '<span class="pagination-links">' . join("\n", $page_links) . '</span>';
891
+        $output .= "\n".'<span class="pagination-links">'.join("\n", $page_links).'</span>';
892 892
         // set page class
893 893
         if ($total_pages) {
894 894
             $page_class = $total_pages < 2 ? ' one-page' : '';
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
             $page_class = ' no-pages';
897 897
         }
898 898
 
899
-        return '<div class="tablenav"><div class="tablenav-pages' . $page_class . '">' . $output . '</div></div>';
899
+        return '<div class="tablenav"><div class="tablenav-pages'.$page_class.'">'.$output.'</div></div>';
900 900
     }
901 901
 
902 902
 
@@ -933,10 +933,10 @@  discard block
 block discarded – undo
933 933
             $query_args
934 934
         );
935 935
         $powered_by = apply_filters('FHEE__EEH_Template__powered_by_event_espresso_text',
936
-            $admin ? 'Event Espresso - ' . EVENT_ESPRESSO_VERSION : 'Event Espresso');
936
+            $admin ? 'Event Espresso - '.EVENT_ESPRESSO_VERSION : 'Event Espresso');
937 937
         $url        = add_query_arg($query_args, 'https://eventespresso.com/');
938 938
         $url        = apply_filters('FHEE__EEH_Template__powered_by_event_espresso__url', $url);
939
-        return (string)apply_filters(
939
+        return (string) apply_filters(
940 940
             'FHEE__EEH_Template__powered_by_event_espresso__html',
941 941
             sprintf(
942 942
                 esc_html_x(
@@ -987,6 +987,6 @@  discard block
 block discarded – undo
987 987
                 'add_fragment' => '',
988 988
             )
989 989
         );
990
-        echo ! empty($pagination) ? '<div class="ee-pagination-dv clear">' . $pagination . '</div>' : '';
990
+        echo ! empty($pagination) ? '<div class="ee-pagination-dv clear">'.$pagination.'</div>' : '';
991 991
     }
992 992
 }
993 993
\ No newline at end of file
Please login to merge, or discard this patch.
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
      * _find_common_base_path
305 305
      * given two paths, this determines if there is a common base path between the two
306 306
      *
307
-     * @param array $paths
307
+     * @param string[] $paths
308 308
      * @return string
309 309
      */
310 310
     protected static function _find_common_base_path($paths)
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
      * @param  boolean    $return_string whether to send output immediately to screen, or capture and return as a string
335 335
      * @param bool        $throw_exceptions if set to true, will throw an exception if the template is either
336 336
      *                                      not found or is not readable
337
-     * @return mixed string
337
+     * @return string string
338 338
      * @throws \DomainException
339 339
      */
340 340
 	public static function display_template(
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Form_Section_Proper.form.php 1 patch
Indentation   +1348 added lines, -1348 removed lines patch added patch discarded remove patch
@@ -13,1354 +13,1354 @@
 block discarded – undo
13 13
 class EE_Form_Section_Proper extends EE_Form_Section_Validatable
14 14
 {
15 15
 
16
-    const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
17
-
18
-    /**
19
-     * Subsections
20
-     *
21
-     * @var EE_Form_Section_Validatable[]
22
-     */
23
-    protected $_subsections = array();
24
-
25
-    /**
26
-     * Strategy for laying out the form
27
-     *
28
-     * @var EE_Form_Section_Layout_Base
29
-     */
30
-    protected $_layout_strategy;
31
-
32
-    /**
33
-     * Whether or not this form has received and validated a form submission yet
34
-     *
35
-     * @var boolean
36
-     */
37
-    protected $_received_submission = false;
38
-
39
-    /**
40
-     * message displayed to users upon successful form submission
41
-     *
42
-     * @var string
43
-     */
44
-    protected $_form_submission_success_message = '';
45
-
46
-    /**
47
-     * message displayed to users upon unsuccessful form submission
48
-     *
49
-     * @var string
50
-     */
51
-    protected $_form_submission_error_message = '';
52
-
53
-    /**
54
-     * Stores all the data that will localized for form validation
55
-     *
56
-     * @var array
57
-     */
58
-    static protected $_js_localization = array();
59
-
60
-    /**
61
-     * whether or not the form's localized validation JS vars have been set
62
-     *
63
-     * @type boolean
64
-     */
65
-    static protected $_scripts_localized = false;
66
-
67
-
68
-
69
-    /**
70
-     * when constructing a proper form section, calls _construct_finalize on children
71
-     * so that they know who their parent is, and what name they've been given.
72
-     *
73
-     * @param array $options_array   {
74
-     * @type        $subsections     EE_Form_Section_Validatable[] where keys are the section's name
75
-     * @type        $include         string[] numerically-indexed where values are section names to be included,
76
-     *                               and in that order. This is handy if you want
77
-     *                               the subsections to be ordered differently than the default, and if you override
78
-     *                               which fields are shown
79
-     * @type        $exclude         string[] values are subsections to be excluded. This is handy if you want
80
-     *                               to remove certain default subsections (note: if you specify BOTH 'include' AND
81
-     *                               'exclude', the inclusions will be applied first, and the exclusions will exclude
82
-     *                               items from that list of inclusions)
83
-     * @type        $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
84
-     *                               } @see EE_Form_Section_Validatable::__construct()
85
-     * @throws \EE_Error
86
-     */
87
-    public function __construct($options_array = array())
88
-    {
89
-        $options_array = (array)apply_filters('FHEE__EE_Form_Section_Proper___construct__options_array', $options_array,
90
-            $this);
91
-        //call parent first, as it may be setting the name
92
-        parent::__construct($options_array);
93
-        //if they've included subsections in the constructor, add them now
94
-        if (isset($options_array['include'])) {
95
-            //we are going to make sure we ONLY have those subsections to include
96
-            //AND we are going to make sure they're in that specified order
97
-            $reordered_subsections = array();
98
-            foreach ($options_array['include'] as $input_name) {
99
-                if (isset($this->_subsections[$input_name])) {
100
-                    $reordered_subsections[$input_name] = $this->_subsections[$input_name];
101
-                }
102
-            }
103
-            $this->_subsections = $reordered_subsections;
104
-        }
105
-        if (isset($options_array['exclude'])) {
106
-            $exclude = $options_array['exclude'];
107
-            $this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
108
-        }
109
-        if (isset($options_array['layout_strategy'])) {
110
-            $this->_layout_strategy = $options_array['layout_strategy'];
111
-        }
112
-        if ( ! $this->_layout_strategy) {
113
-            $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
114
-        }
115
-        $this->_layout_strategy->_construct_finalize($this);
116
-        //ok so we are definitely going to want the forms JS,
117
-        //so enqueue it or remember to enqueue it during wp_enqueue_scripts
118
-        if (did_action('wp_enqueue_scripts')
119
-            || did_action('admin_enqueue_scripts')
120
-        ) {
121
-            //ok so they've constructed this object after when they should have.
122
-            //just enqueue the generic form scripts and initialize the form immediately in the JS
123
-            \EE_Form_Section_Proper::wp_enqueue_scripts(true);
124
-        } else {
125
-            add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
126
-            add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
127
-        }
128
-        add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
129
-        if (isset($options_array['name'])) {
130
-            $this->_construct_finalize(null, $options_array['name']);
131
-        }
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * Finishes construction given the parent form section and this form section's name
138
-     *
139
-     * @param EE_Form_Section_Proper $parent_form_section
140
-     * @param string                 $name
141
-     * @throws \EE_Error
142
-     */
143
-    public function _construct_finalize($parent_form_section, $name)
144
-    {
145
-        parent::_construct_finalize($parent_form_section, $name);
146
-        $this->_set_default_name_if_empty();
147
-        $this->_set_default_html_id_if_empty();
148
-        foreach ($this->_subsections as $subsection_name => $subsection) {
149
-            if ($subsection instanceof EE_Form_Section_Base) {
150
-                $subsection->_construct_finalize($this, $subsection_name);
151
-            } else {
152
-                throw new EE_Error(
153
-                    sprintf(
154
-                        __('Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
155
-                            'event_espresso'),
156
-                        $subsection_name,
157
-                        get_class($this),
158
-                        $subsection ? get_class($subsection) : __('NULL', 'event_espresso')
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        do_action('AHEE__EE_Form_Section_Proper___construct_finalize__end', $this, $parent_form_section, $name);
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * Gets the layout strategy for this form section
170
-     *
171
-     * @return EE_Form_Section_Layout_Base
172
-     */
173
-    public function get_layout_strategy()
174
-    {
175
-        return $this->_layout_strategy;
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     * Gets the HTML for a single input for this form section according
182
-     * to the layout strategy
183
-     *
184
-     * @param EE_Form_Input_Base $input
185
-     * @return string
186
-     */
187
-    public function get_html_for_input($input)
188
-    {
189
-        return $this->_layout_strategy->layout_input($input);
190
-    }
191
-
192
-
193
-
194
-    /**
195
-     * was_submitted - checks if form inputs are present in request data
196
-     * Basically an alias for form_data_present_in() (which is used by both
197
-     * proper form sections and form inputs)
198
-     *
199
-     * @param null $form_data
200
-     * @return boolean
201
-     */
202
-    public function was_submitted($form_data = null)
203
-    {
204
-        return $this->form_data_present_in($form_data);
205
-    }
206
-
207
-
208
-
209
-    /**
210
-     * After the form section is initially created, call this to sanitize the data in the submission
211
-     * which relates to this form section, validate it, and set it as properties on the form.
212
-     *
213
-     * @param array|null $req_data should usually be $_POST (the default).
214
-     *                             However, you CAN supply a different array.
215
-     *                             Consider using set_defaults() instead however.
216
-     *                             (If you rendered the form in the page using echo $form_x->get_html()
217
-     *                             the inputs will have the correct name in the request data for this function
218
-     *                             to find them and populate the form with them.
219
-     *                             If you have a flat form (with only input subsections),
220
-     *                             you can supply a flat array where keys
221
-     *                             are the form input names and values are their values)
222
-     * @param boolean    $validate whether or not to perform validation on this data. Default is,
223
-     *                             of course, to validate that data, and set errors on the invalid values.
224
-     *                             But if the data has already been validated
225
-     *                             (eg you validated the data then stored it in the DB)
226
-     *                             you may want to skip this step.
227
-     */
228
-    public function receive_form_submission($req_data = null, $validate = true)
229
-    {
230
-        $req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__req_data', $req_data, $this,
231
-            $validate);
232
-        if ($req_data === null) {
233
-            $req_data = array_merge($_GET, $_POST);
234
-        }
235
-        $req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data', $req_data,
236
-            $this);
237
-        $this->_normalize($req_data);
238
-        if ($validate) {
239
-            $this->_validate();
240
-            //if it's invalid, we're going to want to re-display so remember what they submitted
241
-            if ( ! $this->is_valid()) {
242
-                $this->store_submitted_form_data_in_session();
243
-            }
244
-        }
245
-        do_action('AHEE__EE_Form_Section_Proper__receive_form_submission__end', $req_data, $this, $validate);
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * caches the originally submitted input values in the session
252
-     * so that they can be used to repopulate the form if it failed validation
253
-     *
254
-     * @return boolean whether or not the data was successfully stored in the session
255
-     */
256
-    protected function store_submitted_form_data_in_session()
257
-    {
258
-        return EE_Registry::instance()->SSN->set_session_data(
259
-            array(
260
-                \EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
261
-            )
262
-        );
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * retrieves the originally submitted input values in the session
269
-     * so that they can be used to repopulate the form if it failed validation
270
-     *
271
-     * @return array
272
-     */
273
-    protected function get_submitted_form_data_from_session()
274
-    {
275
-        $session = EE_Registry::instance()->SSN;
276
-        if ($session instanceof EE_Session) {
277
-            return $session->get_session_data(
278
-                \EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
279
-            );
280
-        } else {
281
-            return array();
282
-        }
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * flushed the originally submitted input values from the session
289
-     *
290
-     * @return boolean whether or not the data was successfully removed from the session
291
-     */
292
-    protected function flush_submitted_form_data_from_session()
293
-    {
294
-        return EE_Registry::instance()->SSN->reset_data(
295
-            array(\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
296
-        );
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     * Populates this form and its subsections with data from the session.
303
-     * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
304
-     * validation errors when displaying too)
305
-     * Returns true if the form was populated from the session, false otherwise
306
-     *
307
-     * @return boolean
308
-     */
309
-    public function populate_from_session()
310
-    {
311
-        $form_data_in_session = $this->get_submitted_form_data_from_session();
312
-        if (empty($form_data_in_session)) {
313
-            return false;
314
-        }
315
-        $this->receive_form_submission($form_data_in_session);
316
-        $this->flush_submitted_form_data_from_session();
317
-        if ($this->form_data_present_in($form_data_in_session)) {
318
-            return true;
319
-        } else {
320
-            return false;
321
-        }
322
-    }
323
-
324
-
325
-
326
-    /**
327
-     * Populates the default data for the form, given an array where keys are
328
-     * the input names, and values are their values (preferably normalized to be their
329
-     * proper PHP types, not all strings... although that should be ok too).
330
-     * Proper subsections are sub-arrays, the key being the subsection's name, and
331
-     * the value being an array formatted in teh same way
332
-     *
333
-     * @param array $default_data
334
-     */
335
-    public function populate_defaults($default_data)
336
-    {
337
-        foreach ($this->subsections() as $subsection_name => $subsection) {
338
-            if (isset($default_data[$subsection_name])) {
339
-                if ($subsection instanceof EE_Form_Input_Base) {
340
-                    $subsection->set_default($default_data[$subsection_name]);
341
-                } elseif ($subsection instanceof EE_Form_Section_Proper) {
342
-                    $subsection->populate_defaults($default_data[$subsection_name]);
343
-                }
344
-            }
345
-        }
346
-    }
347
-
348
-
349
-
350
-    /**
351
-     * returns true if subsection exists
352
-     *
353
-     * @param string $name
354
-     * @return boolean
355
-     */
356
-    public function subsection_exists($name)
357
-    {
358
-        return isset($this->_subsections[$name]) ? true : false;
359
-    }
360
-
361
-
362
-
363
-    /**
364
-     * Gets the subsection specified by its name
365
-     *
366
-     * @param string  $name
367
-     * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
368
-     *                                                      so that the inputs will be properly configured.
369
-     *                                                      However, some client code may be ok
370
-     *                                                      with construction finalize being called later
371
-     *                                                      (realizing that the subsections' html names
372
-     *                                                      might not be set yet, etc.)
373
-     * @return EE_Form_Section_Base
374
-     * @throws \EE_Error
375
-     */
376
-    public function get_subsection($name, $require_construction_to_be_finalized = true)
377
-    {
378
-        if ($require_construction_to_be_finalized) {
379
-            $this->ensure_construct_finalized_called();
380
-        }
381
-        return $this->subsection_exists($name) ? $this->_subsections[$name] : null;
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * Gets all the validatable subsections of this form section
388
-     *
389
-     * @return EE_Form_Section_Validatable[]
390
-     */
391
-    public function get_validatable_subsections()
392
-    {
393
-        $validatable_subsections = array();
394
-        foreach ($this->subsections() as $name => $obj) {
395
-            if ($obj instanceof EE_Form_Section_Validatable) {
396
-                $validatable_subsections[$name] = $obj;
397
-            }
398
-        }
399
-        return $validatable_subsections;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
406
-     * throw an EE_Error.
407
-     *
408
-     * @param string  $name
409
-     * @param boolean $require_construction_to_be_finalized most client code should
410
-     *                                                      leave this as TRUE so that the inputs will be properly
411
-     *                                                      configured. However, some client code may be ok with
412
-     *                                                      construction finalize being called later
413
-     *                                                      (realizing that the subsections' html names might not be
414
-     *                                                      set yet, etc.)
415
-     * @return EE_Form_Input_Base
416
-     * @throws EE_Error
417
-     */
418
-    public function get_input($name, $require_construction_to_be_finalized = true)
419
-    {
420
-        $subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
421
-        if ( ! $subsection instanceof EE_Form_Input_Base) {
422
-            throw new EE_Error(
423
-                sprintf(
424
-                    __(
425
-                        "Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
426
-                        'event_espresso'
427
-                    ),
428
-                    $name,
429
-                    get_class($this),
430
-                    $subsection ? get_class($subsection) : __("NULL", 'event_espresso')
431
-                )
432
-            );
433
-        }
434
-        return $subsection;
435
-    }
436
-
437
-
438
-
439
-    /**
440
-     * Like get_input(), gets the proper subsection of the form given the name,
441
-     * otherwise throws an EE_Error
442
-     *
443
-     * @param string  $name
444
-     * @param boolean $require_construction_to_be_finalized most client code should
445
-     *                                                      leave this as TRUE so that the inputs will be properly
446
-     *                                                      configured. However, some client code may be ok with
447
-     *                                                      construction finalize being called later
448
-     *                                                      (realizing that the subsections' html names might not be
449
-     *                                                      set yet, etc.)
450
-     * @return EE_Form_Section_Proper
451
-     * @throws EE_Error
452
-     */
453
-    public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
454
-    {
455
-        $subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
456
-        if ( ! $subsection instanceof EE_Form_Section_Proper) {
457
-            throw new EE_Error(
458
-                sprintf(
459
-                    __("Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'", 'event_espresso'),
460
-                    $name,
461
-                    get_class($this)
462
-                )
463
-            );
464
-        }
465
-        return $subsection;
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * Gets the value of the specified input. Should be called after receive_form_submission()
472
-     * or populate_defaults() on the form, where the normalized value on the input is set.
473
-     *
474
-     * @param string $name
475
-     * @return mixed depending on the input's type and its normalization strategy
476
-     * @throws \EE_Error
477
-     */
478
-    public function get_input_value($name)
479
-    {
480
-        $input = $this->get_input($name);
481
-        return $input->normalized_value();
482
-    }
483
-
484
-
485
-
486
-    /**
487
-     * Checks if this form section itself is valid, and then checks its subsections
488
-     *
489
-     * @throws EE_Error
490
-     * @return boolean
491
-     */
492
-    public function is_valid()
493
-    {
494
-        if ( ! $this->has_received_submission()) {
495
-            throw new EE_Error(
496
-                sprintf(
497
-                    __(
498
-                        "You cannot check if a form is valid before receiving the form submission using receive_form_submission",
499
-                        "event_espresso"
500
-                    )
501
-                )
502
-            );
503
-        }
504
-        if ( ! parent::is_valid()) {
505
-            return false;
506
-        }
507
-        // ok so no general errors to this entire form section.
508
-        // so let's check the subsections, but only set errors if that hasn't been done yet
509
-        $set_submission_errors = $this->submission_error_message() === '' ? true : false;
510
-        foreach ($this->get_validatable_subsections() as $subsection) {
511
-            if ( ! $subsection->is_valid() || $subsection->get_validation_error_string() !== '') {
512
-                if ($set_submission_errors) {
513
-                    $this->set_submission_error_message($subsection->get_validation_error_string());
514
-                }
515
-                return false;
516
-            }
517
-        }
518
-        return true;
519
-    }
520
-
521
-
522
-
523
-    /**
524
-     * gets teh default name of this form section if none is specified
525
-     *
526
-     * @return string
527
-     */
528
-    protected function _set_default_name_if_empty()
529
-    {
530
-        if ( ! $this->_name) {
531
-            $classname = get_class($this);
532
-            $default_name = str_replace("EE_", "", $classname);
533
-            $this->_name = $default_name;
534
-        }
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Returns the HTML for the form, except for the form opening and closing tags
541
-     * (as the form section doesn't know where you necessarily want to send the information to),
542
-     * and except for a submit button. Enqueus JS and CSS; if called early enough we will
543
-     * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
544
-     * Not doing_it_wrong because theoretically this CAN be used properly,
545
-     * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
546
-     * any CSS.
547
-     *
548
-     * @throws \EE_Error
549
-     */
550
-    public function get_html_and_js()
551
-    {
552
-        $this->enqueue_js();
553
-        return $this->get_html();
554
-    }
555
-
556
-
557
-
558
-    /**
559
-     * returns HTML for displaying this form section. recursively calls display_section() on all subsections
560
-     *
561
-     * @param bool $display_previously_submitted_data
562
-     * @return string
563
-     */
564
-    public function get_html($display_previously_submitted_data = true)
565
-    {
566
-        $this->ensure_construct_finalized_called();
567
-        if ($display_previously_submitted_data) {
568
-            $this->populate_from_session();
569
-        }
570
-        return $this->_layout_strategy->layout_form();
571
-    }
572
-
573
-
574
-
575
-    /**
576
-     * enqueues JS and CSS for the form.
577
-     * It is preferred to call this before wp_enqueue_scripts so the
578
-     * scripts and styles can be put in the header, but if called later
579
-     * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
580
-     * only be in the header; but in HTML5 its ok in the body.
581
-     * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
582
-     * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
583
-     *
584
-     * @return string
585
-     * @throws \EE_Error
586
-     */
587
-    public function enqueue_js()
588
-    {
589
-        $this->_enqueue_and_localize_form_js();
590
-        foreach ($this->subsections() as $subsection) {
591
-            $subsection->enqueue_js();
592
-        }
593
-    }
594
-
595
-
596
-
597
-    /**
598
-     * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
599
-     * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
600
-     * the wp_enqueue_scripts hook.
601
-     * However, registering the form js and localizing it can happen when we
602
-     * actually output the form (which is preferred, seeing how teh form's fields
603
-     * could change until it's actually outputted)
604
-     *
605
-     * @param boolean $init_form_validation_automatically whether or not we want the form validation
606
-     *                                                    to be triggered automatically or not
607
-     * @return void
608
-     */
609
-    public static function wp_enqueue_scripts($init_form_validation_automatically = true)
610
-    {
611
-        add_filter('FHEE_load_jquery_validate', '__return_true');
612
-        wp_register_script(
613
-            'ee_form_section_validation',
614
-            EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
615
-            array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
616
-            EVENT_ESPRESSO_VERSION,
617
-            true
618
-        );
619
-        wp_localize_script(
620
-            'ee_form_section_validation',
621
-            'ee_form_section_validation_init',
622
-            array('init' => $init_form_validation_automatically ? true : false)
623
-        );
624
-    }
625
-
626
-
627
-
628
-    /**
629
-     * gets the variables used by form_section_validation.js.
630
-     * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
631
-     * but before the wordpress hook wp_loaded
632
-     *
633
-     * @throws \EE_Error
634
-     */
635
-    public function _enqueue_and_localize_form_js()
636
-    {
637
-        $this->ensure_construct_finalized_called();
638
-        //actually, we don't want to localize just yet. There may be other forms on the page.
639
-        //so we need to add our form section data to a static variable accessible by all form sections
640
-        //and localize it just before the footer
641
-        $this->localize_validation_rules();
642
-        add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
643
-        add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * add our form section data to a static variable accessible by all form sections
650
-     *
651
-     * @param bool $return_for_subsection
652
-     * @return void
653
-     * @throws \EE_Error
654
-     */
655
-    public function localize_validation_rules($return_for_subsection = false)
656
-    {
657
-        // we only want to localize vars ONCE for the entire form,
658
-        // so if the form section doesn't have a parent, then it must be the top dog
659
-        if ($return_for_subsection || ! $this->parent_section()) {
660
-            EE_Form_Section_Proper::$_js_localization['form_data'][$this->html_id()] = array(
661
-                'form_section_id'  => $this->html_id(true),
662
-                'validation_rules' => $this->get_jquery_validation_rules(),
663
-                'other_data'       => $this->get_other_js_data(),
664
-                'errors'           => $this->subsection_validation_errors_by_html_name(),
665
-            );
666
-            EE_Form_Section_Proper::$_scripts_localized = true;
667
-        }
668
-    }
669
-
670
-
671
-
672
-    /**
673
-     * Gets an array of extra data that will be useful for client-side javascript.
674
-     * This is primarily data added by inputs and forms in addition to any
675
-     * scripts they might enqueue
676
-     *
677
-     * @param array $form_other_js_data
678
-     * @return array
679
-     */
680
-    public function get_other_js_data($form_other_js_data = array())
681
-    {
682
-        foreach ($this->subsections() as $subsection) {
683
-            $form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
684
-        }
685
-        return $form_other_js_data;
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     * Gets a flat array of inputs for this form section and its subsections.
692
-     * Keys are their form names, and values are the inputs themselves
693
-     *
694
-     * @return EE_Form_Input_Base
695
-     */
696
-    public function inputs_in_subsections()
697
-    {
698
-        $inputs = array();
699
-        foreach ($this->subsections() as $subsection) {
700
-            if ($subsection instanceof EE_Form_Input_Base) {
701
-                $inputs[$subsection->html_name()] = $subsection;
702
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
703
-                $inputs += $subsection->inputs_in_subsections();
704
-            }
705
-        }
706
-        return $inputs;
707
-    }
708
-
709
-
710
-
711
-    /**
712
-     * Gets a flat array of all the validation errors.
713
-     * Keys are html names (because those should be unique)
714
-     * and values are a string of all their validation errors
715
-     *
716
-     * @return string[]
717
-     */
718
-    public function subsection_validation_errors_by_html_name()
719
-    {
720
-        $inputs = $this->inputs();
721
-        $errors = array();
722
-        foreach ($inputs as $form_input) {
723
-            if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
724
-                $errors[$form_input->html_name()] = $form_input->get_validation_error_string();
725
-            }
726
-        }
727
-        return $errors;
728
-    }
729
-
730
-
731
-
732
-    /**
733
-     * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
734
-     * Should be setup by each form during the _enqueues_and_localize_form_js
735
-     */
736
-    public static function localize_script_for_all_forms()
737
-    {
738
-        //allow inputs and stuff to hook in their JS and stuff here
739
-        do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
740
-        EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
741
-        $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
742
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
743
-            : 'wp_default';
744
-        EE_Form_Section_Proper::$_js_localization['email_validation_level'] = $email_validation_level;
745
-        wp_enqueue_script('ee_form_section_validation');
746
-        wp_localize_script(
747
-            'ee_form_section_validation',
748
-            'ee_form_section_vars',
749
-            EE_Form_Section_Proper::$_js_localization
750
-        );
751
-    }
752
-
753
-
754
-
755
-    /**
756
-     * ensure_scripts_localized
757
-     */
758
-    public function ensure_scripts_localized()
759
-    {
760
-        if ( ! EE_Form_Section_Proper::$_scripts_localized) {
761
-            $this->_enqueue_and_localize_form_js();
762
-        }
763
-    }
764
-
765
-
766
-
767
-    /**
768
-     * Gets the hard-coded validation error messages to be used in the JS. The convention
769
-     * is that the key here should be the same as the custom validation rule put in the JS file
770
-     *
771
-     * @return array keys are custom validation rules, and values are internationalized strings
772
-     */
773
-    private static function _get_localized_error_messages()
774
-    {
775
-        return array(
776
-            'validUrl' => __("This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg", "event_espresso"),
777
-            'regex'    => __('Please check your input', 'event_espresso'),
778
-        );
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * @return array
785
-     */
786
-    public static function js_localization()
787
-    {
788
-        return self::$_js_localization;
789
-    }
790
-
791
-
792
-
793
-    /**
794
-     * @return array
795
-     */
796
-    public static function reset_js_localization()
797
-    {
798
-        self::$_js_localization = array();
799
-    }
800
-
801
-
802
-
803
-    /**
804
-     * Gets the JS to put inside the jquery validation rules for subsection of this form section.
805
-     * See parent function for more...
806
-     *
807
-     * @return array
808
-     */
809
-    public function get_jquery_validation_rules()
810
-    {
811
-        $jquery_validation_rules = array();
812
-        foreach ($this->get_validatable_subsections() as $subsection) {
813
-            $jquery_validation_rules = array_merge(
814
-                $jquery_validation_rules,
815
-                $subsection->get_jquery_validation_rules()
816
-            );
817
-        }
818
-        return $jquery_validation_rules;
819
-    }
820
-
821
-
822
-
823
-    /**
824
-     * Sanitizes all the data and sets the sanitized value of each field
825
-     *
826
-     * @param array $req_data like $_POST
827
-     * @return void
828
-     */
829
-    protected function _normalize($req_data)
830
-    {
831
-        $this->_received_submission = true;
832
-        $this->_validation_errors = array();
833
-        foreach ($this->get_validatable_subsections() as $subsection) {
834
-            try {
835
-                $subsection->_normalize($req_data);
836
-            } catch (EE_Validation_Error $e) {
837
-                $subsection->add_validation_error($e);
838
-            }
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     * Performs validation on this form section and its subsections.
846
-     * For each subsection,
847
-     * calls _validate_{subsection_name} on THIS form (if the function exists)
848
-     * and passes it the subsection, then calls _validate on that subsection.
849
-     * If you need to perform validation on the form as a whole (considering multiple)
850
-     * you would be best to override this _validate method,
851
-     * calling parent::_validate() first.
852
-     */
853
-    protected function _validate()
854
-    {
855
-        foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
856
-            if (method_exists($this, '_validate_' . $subsection_name)) {
857
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
858
-            }
859
-            $subsection->_validate();
860
-        }
861
-    }
862
-
863
-
864
-
865
-    /**
866
-     * Gets all the validated inputs for the form section
867
-     *
868
-     * @return array
869
-     */
870
-    public function valid_data()
871
-    {
872
-        $inputs = array();
873
-        foreach ($this->subsections() as $subsection_name => $subsection) {
874
-            if ($subsection instanceof EE_Form_Section_Proper) {
875
-                $inputs[$subsection_name] = $subsection->valid_data();
876
-            } else if ($subsection instanceof EE_Form_Input_Base) {
877
-                $inputs[$subsection_name] = $subsection->normalized_value();
878
-            }
879
-        }
880
-        return $inputs;
881
-    }
882
-
883
-
884
-
885
-    /**
886
-     * Gets all the inputs on this form section
887
-     *
888
-     * @return EE_Form_Input_Base[]
889
-     */
890
-    public function inputs()
891
-    {
892
-        $inputs = array();
893
-        foreach ($this->subsections() as $subsection_name => $subsection) {
894
-            if ($subsection instanceof EE_Form_Input_Base) {
895
-                $inputs[$subsection_name] = $subsection;
896
-            }
897
-        }
898
-        return $inputs;
899
-    }
900
-
901
-
902
-
903
-    /**
904
-     * Gets all the subsections which are a proper form
905
-     *
906
-     * @return EE_Form_Section_Proper[]
907
-     */
908
-    public function subforms()
909
-    {
910
-        $form_sections = array();
911
-        foreach ($this->subsections() as $name => $obj) {
912
-            if ($obj instanceof EE_Form_Section_Proper) {
913
-                $form_sections[$name] = $obj;
914
-            }
915
-        }
916
-        return $form_sections;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * Gets all the subsections (inputs, proper subsections, or html-only sections).
923
-     * Consider using inputs() or subforms()
924
-     * if you only want form inputs or proper form sections.
925
-     *
926
-     * @return EE_Form_Section_Proper[]
927
-     */
928
-    public function subsections()
929
-    {
930
-        $this->ensure_construct_finalized_called();
931
-        return $this->_subsections;
932
-    }
933
-
934
-
935
-
936
-    /**
937
-     * Returns a simple array where keys are input names, and values are their normalized
938
-     * values. (Similar to calling get_input_value on inputs)
939
-     *
940
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
941
-     *                                        or just this forms' direct children inputs
942
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
943
-     *                                        or allow multidimensional array
944
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
945
-     *                                        with array keys being input names
946
-     *                                        (regardless of whether they are from a subsection or not),
947
-     *                                        and if $flatten is FALSE it can be a multidimensional array
948
-     *                                        where keys are always subsection names and values are either
949
-     *                                        the input's normalized value, or an array like the top-level array
950
-     */
951
-    public function input_values($include_subform_inputs = false, $flatten = false)
952
-    {
953
-        return $this->_input_values(false, $include_subform_inputs, $flatten);
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
960
-     * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
961
-     * is not necessarily the value we want to display to users. This creates an array
962
-     * where keys are the input names, and values are their display values
963
-     *
964
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
965
-     *                                        or just this forms' direct children inputs
966
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
967
-     *                                        or allow multidimensional array
968
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
969
-     *                                        with array keys being input names
970
-     *                                        (regardless of whether they are from a subsection or not),
971
-     *                                        and if $flatten is FALSE it can be a multidimensional array
972
-     *                                        where keys are always subsection names and values are either
973
-     *                                        the input's normalized value, or an array like the top-level array
974
-     */
975
-    public function input_pretty_values($include_subform_inputs = false, $flatten = false)
976
-    {
977
-        return $this->_input_values(true, $include_subform_inputs, $flatten);
978
-    }
979
-
980
-
981
-
982
-    /**
983
-     * Gets the input values from the form
984
-     *
985
-     * @param boolean $pretty                 Whether to retrieve the pretty value,
986
-     *                                        or just the normalized value
987
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
988
-     *                                        or just this forms' direct children inputs
989
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
990
-     *                                        or allow multidimensional array
991
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
992
-     *                                        input names (regardless of whether they are from a subsection or not),
993
-     *                                        and if $flatten is FALSE it can be a multidimensional array
994
-     *                                        where keys are always subsection names and values are either
995
-     *                                        the input's normalized value, or an array like the top-level array
996
-     */
997
-    public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
998
-    {
999
-        $input_values = array();
1000
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1001
-            if ($subsection instanceof EE_Form_Input_Base) {
1002
-                $input_values[$subsection_name] = $pretty
1003
-                    ? $subsection->pretty_value()
1004
-                    : $subsection->normalized_value();
1005
-            } else if ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1006
-                $subform_input_values = $subsection->_input_values($pretty, $include_subform_inputs, $flatten);
1007
-                if ($flatten) {
1008
-                    $input_values = array_merge($input_values, $subform_input_values);
1009
-                } else {
1010
-                    $input_values[$subsection_name] = $subform_input_values;
1011
-                }
1012
-            }
1013
-        }
1014
-        return $input_values;
1015
-    }
1016
-
1017
-
1018
-
1019
-    /**
1020
-     * Gets the originally submitted input values from the form
1021
-     *
1022
-     * @param boolean $include_subforms  Whether to include inputs from subforms,
1023
-     *                                   or just this forms' direct children inputs
1024
-     * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1025
-     *                                   with array keys being input names
1026
-     *                                   (regardless of whether they are from a subsection or not),
1027
-     *                                   and if $flatten is FALSE it can be a multidimensional array
1028
-     *                                   where keys are always subsection names and values are either
1029
-     *                                   the input's normalized value, or an array like the top-level array
1030
-     */
1031
-    public function submitted_values($include_subforms = false)
1032
-    {
1033
-        $submitted_values = array();
1034
-        foreach ($this->subsections() as $subsection) {
1035
-            if ($subsection instanceof EE_Form_Input_Base) {
1036
-                // is this input part of an array of inputs?
1037
-                if (strpos($subsection->html_name(), '[') !== false) {
1038
-                    $full_input_name = \EEH_Array::convert_array_values_to_keys(
1039
-                        explode('[', str_replace(']', '', $subsection->html_name())),
1040
-                        $subsection->raw_value()
1041
-                    );
1042
-                    $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1043
-                } else {
1044
-                    $submitted_values[$subsection->html_name()] = $subsection->raw_value();
1045
-                }
1046
-            } else if ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1047
-                $subform_input_values = $subsection->submitted_values($include_subforms);
1048
-                $submitted_values = array_replace_recursive($submitted_values, $subform_input_values);
1049
-            }
1050
-        }
1051
-        return $submitted_values;
1052
-    }
1053
-
1054
-
1055
-
1056
-    /**
1057
-     * Indicates whether or not this form has received a submission yet
1058
-     * (ie, had receive_form_submission called on it yet)
1059
-     *
1060
-     * @return boolean
1061
-     * @throws \EE_Error
1062
-     */
1063
-    public function has_received_submission()
1064
-    {
1065
-        $this->ensure_construct_finalized_called();
1066
-        return $this->_received_submission;
1067
-    }
1068
-
1069
-
1070
-
1071
-    /**
1072
-     * Equivalent to passing 'exclude' in the constructor's options array.
1073
-     * Removes the listed inputs from the form
1074
-     *
1075
-     * @param array $inputs_to_exclude values are the input names
1076
-     * @return void
1077
-     */
1078
-    public function exclude(array $inputs_to_exclude = array())
1079
-    {
1080
-        foreach ($inputs_to_exclude as $input_to_exclude_name) {
1081
-            unset($this->_subsections[$input_to_exclude_name]);
1082
-        }
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * @param array $inputs_to_hide
1089
-     * @throws \EE_Error
1090
-     */
1091
-    public function hide(array $inputs_to_hide = array())
1092
-    {
1093
-        foreach ($inputs_to_hide as $input_to_hide) {
1094
-            $input = $this->get_input($input_to_hide);
1095
-            $input->set_display_strategy(new EE_Hidden_Display_Strategy());
1096
-        }
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * add_subsections
1103
-     * Adds the listed subsections to the form section.
1104
-     * If $subsection_name_to_target is provided,
1105
-     * then new subsections are added before or after that subsection,
1106
-     * otherwise to the start or end of the entire subsections array.
1107
-     *
1108
-     * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1109
-     *                                                          where keys are their names
1110
-     * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1111
-     *                                                          should be added before or after
1112
-     *                                                          IF $subsection_name_to_target is null,
1113
-     *                                                          then $new_subsections will be added to
1114
-     *                                                          the beginning or end of the entire subsections array
1115
-     * @param boolean                $add_before                whether to add $new_subsections, before or after
1116
-     *                                                          $subsection_name_to_target,
1117
-     *                                                          or if $subsection_name_to_target is null,
1118
-     *                                                          before or after entire subsections array
1119
-     * @return void
1120
-     * @throws \EE_Error
1121
-     */
1122
-    public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1123
-    {
1124
-        foreach ($new_subsections as $subsection_name => $subsection) {
1125
-            if ( ! $subsection instanceof EE_Form_Section_Base) {
1126
-                EE_Error::add_error(
1127
-                    sprintf(
1128
-                        __(
1129
-                            "Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1130
-                            "event_espresso"
1131
-                        ),
1132
-                        get_class($subsection),
1133
-                        $subsection_name,
1134
-                        $this->name()
1135
-                    )
1136
-                );
1137
-                unset($new_subsections[$subsection_name]);
1138
-            }
1139
-        }
1140
-        $this->_subsections = EEH_Array::insert_into_array(
1141
-            $this->_subsections,
1142
-            $new_subsections,
1143
-            $subsection_name_to_target,
1144
-            $add_before
1145
-        );
1146
-        if ($this->_construction_finalized) {
1147
-            foreach ($this->_subsections as $name => $subsection) {
1148
-                $subsection->_construct_finalize($this, $name);
1149
-            }
1150
-        }
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * Just gets all validatable subsections to clean their sensitive data
1157
-     */
1158
-    public function clean_sensitive_data()
1159
-    {
1160
-        foreach ($this->get_validatable_subsections() as $subsection) {
1161
-            $subsection->clean_sensitive_data();
1162
-        }
1163
-    }
1164
-
1165
-
1166
-
1167
-    /**
1168
-     * @param string $form_submission_error_message
1169
-     */
1170
-    public function set_submission_error_message($form_submission_error_message = '')
1171
-    {
1172
-        $this->_form_submission_error_message .= ! empty($form_submission_error_message)
1173
-            ? $form_submission_error_message
1174
-            : __('Form submission failed due to errors', 'event_espresso');
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * @return string
1181
-     */
1182
-    public function submission_error_message()
1183
-    {
1184
-        return $this->_form_submission_error_message;
1185
-    }
1186
-
1187
-
1188
-
1189
-    /**
1190
-     * @param string $form_submission_success_message
1191
-     */
1192
-    public function set_submission_success_message($form_submission_success_message)
1193
-    {
1194
-        $this->_form_submission_success_message .= ! empty($form_submission_success_message)
1195
-            ? $form_submission_success_message
1196
-            : __('Form submitted successfully', 'event_espresso');
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * @return string
1203
-     */
1204
-    public function submission_success_message()
1205
-    {
1206
-        return $this->_form_submission_success_message;
1207
-    }
1208
-
1209
-
1210
-
1211
-    /**
1212
-     * Returns the prefix that should be used on child of this form section for
1213
-     * their html names. If this form section itself has a parent, prepends ITS
1214
-     * prefix onto this form section's prefix. Used primarily by
1215
-     * EE_Form_Input_Base::_set_default_html_name_if_empty
1216
-     *
1217
-     * @return string
1218
-     * @throws \EE_Error
1219
-     */
1220
-    public function html_name_prefix()
1221
-    {
1222
-        if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1223
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1224
-        } else {
1225
-            return $this->name();
1226
-        }
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets the name, but first checks _construct_finalize has been called. If not,
1233
-     * calls it (assumes there is no parent and that we want the name to be whatever
1234
-     * was set, which is probably nothing, or the classname)
1235
-     *
1236
-     * @return string
1237
-     * @throws \EE_Error
1238
-     */
1239
-    public function name()
1240
-    {
1241
-        $this->ensure_construct_finalized_called();
1242
-        return parent::name();
1243
-    }
1244
-
1245
-
1246
-
1247
-    /**
1248
-     * @return EE_Form_Section_Proper
1249
-     * @throws \EE_Error
1250
-     */
1251
-    public function parent_section()
1252
-    {
1253
-        $this->ensure_construct_finalized_called();
1254
-        return parent::parent_section();
1255
-    }
1256
-
1257
-
1258
-
1259
-    /**
1260
-     * make sure construction finalized was called, otherwise children might not be ready
1261
-     *
1262
-     * @return void
1263
-     * @throws \EE_Error
1264
-     */
1265
-    public function ensure_construct_finalized_called()
1266
-    {
1267
-        if ( ! $this->_construction_finalized) {
1268
-            $this->_construct_finalize($this->_parent_section, $this->_name);
1269
-        }
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Checks if any of this form section's inputs, or any of its children's inputs,
1276
-     * are in teh form data. If any are found, returns true. Else false
1277
-     *
1278
-     * @param array $req_data
1279
-     * @return boolean
1280
-     */
1281
-    public function form_data_present_in($req_data = null)
1282
-    {
1283
-        if ($req_data === null) {
1284
-            $req_data = $_POST;
1285
-        }
1286
-        foreach ($this->subsections() as $subsection) {
1287
-            if ($subsection instanceof EE_Form_Input_Base) {
1288
-                if ($subsection->form_data_present_in($req_data)) {
1289
-                    return true;
1290
-                }
1291
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
1292
-                if ($subsection->form_data_present_in($req_data)) {
1293
-                    return true;
1294
-                }
1295
-            }
1296
-        }
1297
-        return false;
1298
-    }
1299
-
1300
-
1301
-
1302
-    /**
1303
-     * Gets validation errors for this form section and subsections
1304
-     * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1305
-     * gets the validation errors for ALL subsection
1306
-     *
1307
-     * @return EE_Validation_Error[]
1308
-     */
1309
-    public function get_validation_errors_accumulated()
1310
-    {
1311
-        $validation_errors = $this->get_validation_errors();
1312
-        foreach ($this->get_validatable_subsections() as $subsection) {
1313
-            if ($subsection instanceof EE_Form_Section_Proper) {
1314
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1315
-            } else {
1316
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors();
1317
-            }
1318
-            if ($validation_errors_on_this_subsection) {
1319
-                $validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1320
-            }
1321
-        }
1322
-        return $validation_errors;
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * This isn't just the name of an input, it's a path pointing to an input. The
1329
-     * path is similar to a folder path: slash (/) means to descend into a subsection,
1330
-     * dot-dot-slash (../) means to ascend into the parent section.
1331
-     * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1332
-     * which will be returned.
1333
-     * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1334
-     * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1335
-     * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1336
-     * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1337
-     * Etc
1338
-     *
1339
-     * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1340
-     * @return EE_Form_Section_Base
1341
-     */
1342
-    public function find_section_from_path($form_section_path)
1343
-    {
1344
-        //check if we can find the input from purely going straight up the tree
1345
-        $input = parent::find_section_from_path($form_section_path);
1346
-        if ($input instanceof EE_Form_Section_Base) {
1347
-            return $input;
1348
-        }
1349
-        $next_slash_pos = strpos($form_section_path, '/');
1350
-        if ($next_slash_pos !== false) {
1351
-            $child_section_name = substr($form_section_path, 0, $next_slash_pos);
1352
-            $subpath = substr($form_section_path, $next_slash_pos + 1);
1353
-        } else {
1354
-            $child_section_name = $form_section_path;
1355
-            $subpath = '';
1356
-        }
1357
-        $child_section = $this->get_subsection($child_section_name);
1358
-        if ($child_section instanceof EE_Form_Section_Base) {
1359
-            return $child_section->find_section_from_path($subpath);
1360
-        } else {
1361
-            return null;
1362
-        }
1363
-    }
16
+	const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
17
+
18
+	/**
19
+	 * Subsections
20
+	 *
21
+	 * @var EE_Form_Section_Validatable[]
22
+	 */
23
+	protected $_subsections = array();
24
+
25
+	/**
26
+	 * Strategy for laying out the form
27
+	 *
28
+	 * @var EE_Form_Section_Layout_Base
29
+	 */
30
+	protected $_layout_strategy;
31
+
32
+	/**
33
+	 * Whether or not this form has received and validated a form submission yet
34
+	 *
35
+	 * @var boolean
36
+	 */
37
+	protected $_received_submission = false;
38
+
39
+	/**
40
+	 * message displayed to users upon successful form submission
41
+	 *
42
+	 * @var string
43
+	 */
44
+	protected $_form_submission_success_message = '';
45
+
46
+	/**
47
+	 * message displayed to users upon unsuccessful form submission
48
+	 *
49
+	 * @var string
50
+	 */
51
+	protected $_form_submission_error_message = '';
52
+
53
+	/**
54
+	 * Stores all the data that will localized for form validation
55
+	 *
56
+	 * @var array
57
+	 */
58
+	static protected $_js_localization = array();
59
+
60
+	/**
61
+	 * whether or not the form's localized validation JS vars have been set
62
+	 *
63
+	 * @type boolean
64
+	 */
65
+	static protected $_scripts_localized = false;
66
+
67
+
68
+
69
+	/**
70
+	 * when constructing a proper form section, calls _construct_finalize on children
71
+	 * so that they know who their parent is, and what name they've been given.
72
+	 *
73
+	 * @param array $options_array   {
74
+	 * @type        $subsections     EE_Form_Section_Validatable[] where keys are the section's name
75
+	 * @type        $include         string[] numerically-indexed where values are section names to be included,
76
+	 *                               and in that order. This is handy if you want
77
+	 *                               the subsections to be ordered differently than the default, and if you override
78
+	 *                               which fields are shown
79
+	 * @type        $exclude         string[] values are subsections to be excluded. This is handy if you want
80
+	 *                               to remove certain default subsections (note: if you specify BOTH 'include' AND
81
+	 *                               'exclude', the inclusions will be applied first, and the exclusions will exclude
82
+	 *                               items from that list of inclusions)
83
+	 * @type        $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
84
+	 *                               } @see EE_Form_Section_Validatable::__construct()
85
+	 * @throws \EE_Error
86
+	 */
87
+	public function __construct($options_array = array())
88
+	{
89
+		$options_array = (array)apply_filters('FHEE__EE_Form_Section_Proper___construct__options_array', $options_array,
90
+			$this);
91
+		//call parent first, as it may be setting the name
92
+		parent::__construct($options_array);
93
+		//if they've included subsections in the constructor, add them now
94
+		if (isset($options_array['include'])) {
95
+			//we are going to make sure we ONLY have those subsections to include
96
+			//AND we are going to make sure they're in that specified order
97
+			$reordered_subsections = array();
98
+			foreach ($options_array['include'] as $input_name) {
99
+				if (isset($this->_subsections[$input_name])) {
100
+					$reordered_subsections[$input_name] = $this->_subsections[$input_name];
101
+				}
102
+			}
103
+			$this->_subsections = $reordered_subsections;
104
+		}
105
+		if (isset($options_array['exclude'])) {
106
+			$exclude = $options_array['exclude'];
107
+			$this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
108
+		}
109
+		if (isset($options_array['layout_strategy'])) {
110
+			$this->_layout_strategy = $options_array['layout_strategy'];
111
+		}
112
+		if ( ! $this->_layout_strategy) {
113
+			$this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
114
+		}
115
+		$this->_layout_strategy->_construct_finalize($this);
116
+		//ok so we are definitely going to want the forms JS,
117
+		//so enqueue it or remember to enqueue it during wp_enqueue_scripts
118
+		if (did_action('wp_enqueue_scripts')
119
+			|| did_action('admin_enqueue_scripts')
120
+		) {
121
+			//ok so they've constructed this object after when they should have.
122
+			//just enqueue the generic form scripts and initialize the form immediately in the JS
123
+			\EE_Form_Section_Proper::wp_enqueue_scripts(true);
124
+		} else {
125
+			add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
126
+			add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
127
+		}
128
+		add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
129
+		if (isset($options_array['name'])) {
130
+			$this->_construct_finalize(null, $options_array['name']);
131
+		}
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * Finishes construction given the parent form section and this form section's name
138
+	 *
139
+	 * @param EE_Form_Section_Proper $parent_form_section
140
+	 * @param string                 $name
141
+	 * @throws \EE_Error
142
+	 */
143
+	public function _construct_finalize($parent_form_section, $name)
144
+	{
145
+		parent::_construct_finalize($parent_form_section, $name);
146
+		$this->_set_default_name_if_empty();
147
+		$this->_set_default_html_id_if_empty();
148
+		foreach ($this->_subsections as $subsection_name => $subsection) {
149
+			if ($subsection instanceof EE_Form_Section_Base) {
150
+				$subsection->_construct_finalize($this, $subsection_name);
151
+			} else {
152
+				throw new EE_Error(
153
+					sprintf(
154
+						__('Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
155
+							'event_espresso'),
156
+						$subsection_name,
157
+						get_class($this),
158
+						$subsection ? get_class($subsection) : __('NULL', 'event_espresso')
159
+					)
160
+				);
161
+			}
162
+		}
163
+		do_action('AHEE__EE_Form_Section_Proper___construct_finalize__end', $this, $parent_form_section, $name);
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * Gets the layout strategy for this form section
170
+	 *
171
+	 * @return EE_Form_Section_Layout_Base
172
+	 */
173
+	public function get_layout_strategy()
174
+	{
175
+		return $this->_layout_strategy;
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 * Gets the HTML for a single input for this form section according
182
+	 * to the layout strategy
183
+	 *
184
+	 * @param EE_Form_Input_Base $input
185
+	 * @return string
186
+	 */
187
+	public function get_html_for_input($input)
188
+	{
189
+		return $this->_layout_strategy->layout_input($input);
190
+	}
191
+
192
+
193
+
194
+	/**
195
+	 * was_submitted - checks if form inputs are present in request data
196
+	 * Basically an alias for form_data_present_in() (which is used by both
197
+	 * proper form sections and form inputs)
198
+	 *
199
+	 * @param null $form_data
200
+	 * @return boolean
201
+	 */
202
+	public function was_submitted($form_data = null)
203
+	{
204
+		return $this->form_data_present_in($form_data);
205
+	}
206
+
207
+
208
+
209
+	/**
210
+	 * After the form section is initially created, call this to sanitize the data in the submission
211
+	 * which relates to this form section, validate it, and set it as properties on the form.
212
+	 *
213
+	 * @param array|null $req_data should usually be $_POST (the default).
214
+	 *                             However, you CAN supply a different array.
215
+	 *                             Consider using set_defaults() instead however.
216
+	 *                             (If you rendered the form in the page using echo $form_x->get_html()
217
+	 *                             the inputs will have the correct name in the request data for this function
218
+	 *                             to find them and populate the form with them.
219
+	 *                             If you have a flat form (with only input subsections),
220
+	 *                             you can supply a flat array where keys
221
+	 *                             are the form input names and values are their values)
222
+	 * @param boolean    $validate whether or not to perform validation on this data. Default is,
223
+	 *                             of course, to validate that data, and set errors on the invalid values.
224
+	 *                             But if the data has already been validated
225
+	 *                             (eg you validated the data then stored it in the DB)
226
+	 *                             you may want to skip this step.
227
+	 */
228
+	public function receive_form_submission($req_data = null, $validate = true)
229
+	{
230
+		$req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__req_data', $req_data, $this,
231
+			$validate);
232
+		if ($req_data === null) {
233
+			$req_data = array_merge($_GET, $_POST);
234
+		}
235
+		$req_data = apply_filters('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data', $req_data,
236
+			$this);
237
+		$this->_normalize($req_data);
238
+		if ($validate) {
239
+			$this->_validate();
240
+			//if it's invalid, we're going to want to re-display so remember what they submitted
241
+			if ( ! $this->is_valid()) {
242
+				$this->store_submitted_form_data_in_session();
243
+			}
244
+		}
245
+		do_action('AHEE__EE_Form_Section_Proper__receive_form_submission__end', $req_data, $this, $validate);
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * caches the originally submitted input values in the session
252
+	 * so that they can be used to repopulate the form if it failed validation
253
+	 *
254
+	 * @return boolean whether or not the data was successfully stored in the session
255
+	 */
256
+	protected function store_submitted_form_data_in_session()
257
+	{
258
+		return EE_Registry::instance()->SSN->set_session_data(
259
+			array(
260
+				\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
261
+			)
262
+		);
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * retrieves the originally submitted input values in the session
269
+	 * so that they can be used to repopulate the form if it failed validation
270
+	 *
271
+	 * @return array
272
+	 */
273
+	protected function get_submitted_form_data_from_session()
274
+	{
275
+		$session = EE_Registry::instance()->SSN;
276
+		if ($session instanceof EE_Session) {
277
+			return $session->get_session_data(
278
+				\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
279
+			);
280
+		} else {
281
+			return array();
282
+		}
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * flushed the originally submitted input values from the session
289
+	 *
290
+	 * @return boolean whether or not the data was successfully removed from the session
291
+	 */
292
+	protected function flush_submitted_form_data_from_session()
293
+	{
294
+		return EE_Registry::instance()->SSN->reset_data(
295
+			array(\EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
296
+		);
297
+	}
298
+
299
+
300
+
301
+	/**
302
+	 * Populates this form and its subsections with data from the session.
303
+	 * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
304
+	 * validation errors when displaying too)
305
+	 * Returns true if the form was populated from the session, false otherwise
306
+	 *
307
+	 * @return boolean
308
+	 */
309
+	public function populate_from_session()
310
+	{
311
+		$form_data_in_session = $this->get_submitted_form_data_from_session();
312
+		if (empty($form_data_in_session)) {
313
+			return false;
314
+		}
315
+		$this->receive_form_submission($form_data_in_session);
316
+		$this->flush_submitted_form_data_from_session();
317
+		if ($this->form_data_present_in($form_data_in_session)) {
318
+			return true;
319
+		} else {
320
+			return false;
321
+		}
322
+	}
323
+
324
+
325
+
326
+	/**
327
+	 * Populates the default data for the form, given an array where keys are
328
+	 * the input names, and values are their values (preferably normalized to be their
329
+	 * proper PHP types, not all strings... although that should be ok too).
330
+	 * Proper subsections are sub-arrays, the key being the subsection's name, and
331
+	 * the value being an array formatted in teh same way
332
+	 *
333
+	 * @param array $default_data
334
+	 */
335
+	public function populate_defaults($default_data)
336
+	{
337
+		foreach ($this->subsections() as $subsection_name => $subsection) {
338
+			if (isset($default_data[$subsection_name])) {
339
+				if ($subsection instanceof EE_Form_Input_Base) {
340
+					$subsection->set_default($default_data[$subsection_name]);
341
+				} elseif ($subsection instanceof EE_Form_Section_Proper) {
342
+					$subsection->populate_defaults($default_data[$subsection_name]);
343
+				}
344
+			}
345
+		}
346
+	}
347
+
348
+
349
+
350
+	/**
351
+	 * returns true if subsection exists
352
+	 *
353
+	 * @param string $name
354
+	 * @return boolean
355
+	 */
356
+	public function subsection_exists($name)
357
+	{
358
+		return isset($this->_subsections[$name]) ? true : false;
359
+	}
360
+
361
+
362
+
363
+	/**
364
+	 * Gets the subsection specified by its name
365
+	 *
366
+	 * @param string  $name
367
+	 * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
368
+	 *                                                      so that the inputs will be properly configured.
369
+	 *                                                      However, some client code may be ok
370
+	 *                                                      with construction finalize being called later
371
+	 *                                                      (realizing that the subsections' html names
372
+	 *                                                      might not be set yet, etc.)
373
+	 * @return EE_Form_Section_Base
374
+	 * @throws \EE_Error
375
+	 */
376
+	public function get_subsection($name, $require_construction_to_be_finalized = true)
377
+	{
378
+		if ($require_construction_to_be_finalized) {
379
+			$this->ensure_construct_finalized_called();
380
+		}
381
+		return $this->subsection_exists($name) ? $this->_subsections[$name] : null;
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * Gets all the validatable subsections of this form section
388
+	 *
389
+	 * @return EE_Form_Section_Validatable[]
390
+	 */
391
+	public function get_validatable_subsections()
392
+	{
393
+		$validatable_subsections = array();
394
+		foreach ($this->subsections() as $name => $obj) {
395
+			if ($obj instanceof EE_Form_Section_Validatable) {
396
+				$validatable_subsections[$name] = $obj;
397
+			}
398
+		}
399
+		return $validatable_subsections;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
406
+	 * throw an EE_Error.
407
+	 *
408
+	 * @param string  $name
409
+	 * @param boolean $require_construction_to_be_finalized most client code should
410
+	 *                                                      leave this as TRUE so that the inputs will be properly
411
+	 *                                                      configured. However, some client code may be ok with
412
+	 *                                                      construction finalize being called later
413
+	 *                                                      (realizing that the subsections' html names might not be
414
+	 *                                                      set yet, etc.)
415
+	 * @return EE_Form_Input_Base
416
+	 * @throws EE_Error
417
+	 */
418
+	public function get_input($name, $require_construction_to_be_finalized = true)
419
+	{
420
+		$subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
421
+		if ( ! $subsection instanceof EE_Form_Input_Base) {
422
+			throw new EE_Error(
423
+				sprintf(
424
+					__(
425
+						"Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
426
+						'event_espresso'
427
+					),
428
+					$name,
429
+					get_class($this),
430
+					$subsection ? get_class($subsection) : __("NULL", 'event_espresso')
431
+				)
432
+			);
433
+		}
434
+		return $subsection;
435
+	}
436
+
437
+
438
+
439
+	/**
440
+	 * Like get_input(), gets the proper subsection of the form given the name,
441
+	 * otherwise throws an EE_Error
442
+	 *
443
+	 * @param string  $name
444
+	 * @param boolean $require_construction_to_be_finalized most client code should
445
+	 *                                                      leave this as TRUE so that the inputs will be properly
446
+	 *                                                      configured. However, some client code may be ok with
447
+	 *                                                      construction finalize being called later
448
+	 *                                                      (realizing that the subsections' html names might not be
449
+	 *                                                      set yet, etc.)
450
+	 * @return EE_Form_Section_Proper
451
+	 * @throws EE_Error
452
+	 */
453
+	public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
454
+	{
455
+		$subsection = $this->get_subsection($name, $require_construction_to_be_finalized);
456
+		if ( ! $subsection instanceof EE_Form_Section_Proper) {
457
+			throw new EE_Error(
458
+				sprintf(
459
+					__("Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'", 'event_espresso'),
460
+					$name,
461
+					get_class($this)
462
+				)
463
+			);
464
+		}
465
+		return $subsection;
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * Gets the value of the specified input. Should be called after receive_form_submission()
472
+	 * or populate_defaults() on the form, where the normalized value on the input is set.
473
+	 *
474
+	 * @param string $name
475
+	 * @return mixed depending on the input's type and its normalization strategy
476
+	 * @throws \EE_Error
477
+	 */
478
+	public function get_input_value($name)
479
+	{
480
+		$input = $this->get_input($name);
481
+		return $input->normalized_value();
482
+	}
483
+
484
+
485
+
486
+	/**
487
+	 * Checks if this form section itself is valid, and then checks its subsections
488
+	 *
489
+	 * @throws EE_Error
490
+	 * @return boolean
491
+	 */
492
+	public function is_valid()
493
+	{
494
+		if ( ! $this->has_received_submission()) {
495
+			throw new EE_Error(
496
+				sprintf(
497
+					__(
498
+						"You cannot check if a form is valid before receiving the form submission using receive_form_submission",
499
+						"event_espresso"
500
+					)
501
+				)
502
+			);
503
+		}
504
+		if ( ! parent::is_valid()) {
505
+			return false;
506
+		}
507
+		// ok so no general errors to this entire form section.
508
+		// so let's check the subsections, but only set errors if that hasn't been done yet
509
+		$set_submission_errors = $this->submission_error_message() === '' ? true : false;
510
+		foreach ($this->get_validatable_subsections() as $subsection) {
511
+			if ( ! $subsection->is_valid() || $subsection->get_validation_error_string() !== '') {
512
+				if ($set_submission_errors) {
513
+					$this->set_submission_error_message($subsection->get_validation_error_string());
514
+				}
515
+				return false;
516
+			}
517
+		}
518
+		return true;
519
+	}
520
+
521
+
522
+
523
+	/**
524
+	 * gets teh default name of this form section if none is specified
525
+	 *
526
+	 * @return string
527
+	 */
528
+	protected function _set_default_name_if_empty()
529
+	{
530
+		if ( ! $this->_name) {
531
+			$classname = get_class($this);
532
+			$default_name = str_replace("EE_", "", $classname);
533
+			$this->_name = $default_name;
534
+		}
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Returns the HTML for the form, except for the form opening and closing tags
541
+	 * (as the form section doesn't know where you necessarily want to send the information to),
542
+	 * and except for a submit button. Enqueus JS and CSS; if called early enough we will
543
+	 * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
544
+	 * Not doing_it_wrong because theoretically this CAN be used properly,
545
+	 * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
546
+	 * any CSS.
547
+	 *
548
+	 * @throws \EE_Error
549
+	 */
550
+	public function get_html_and_js()
551
+	{
552
+		$this->enqueue_js();
553
+		return $this->get_html();
554
+	}
555
+
556
+
557
+
558
+	/**
559
+	 * returns HTML for displaying this form section. recursively calls display_section() on all subsections
560
+	 *
561
+	 * @param bool $display_previously_submitted_data
562
+	 * @return string
563
+	 */
564
+	public function get_html($display_previously_submitted_data = true)
565
+	{
566
+		$this->ensure_construct_finalized_called();
567
+		if ($display_previously_submitted_data) {
568
+			$this->populate_from_session();
569
+		}
570
+		return $this->_layout_strategy->layout_form();
571
+	}
572
+
573
+
574
+
575
+	/**
576
+	 * enqueues JS and CSS for the form.
577
+	 * It is preferred to call this before wp_enqueue_scripts so the
578
+	 * scripts and styles can be put in the header, but if called later
579
+	 * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
580
+	 * only be in the header; but in HTML5 its ok in the body.
581
+	 * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
582
+	 * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
583
+	 *
584
+	 * @return string
585
+	 * @throws \EE_Error
586
+	 */
587
+	public function enqueue_js()
588
+	{
589
+		$this->_enqueue_and_localize_form_js();
590
+		foreach ($this->subsections() as $subsection) {
591
+			$subsection->enqueue_js();
592
+		}
593
+	}
594
+
595
+
596
+
597
+	/**
598
+	 * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
599
+	 * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
600
+	 * the wp_enqueue_scripts hook.
601
+	 * However, registering the form js and localizing it can happen when we
602
+	 * actually output the form (which is preferred, seeing how teh form's fields
603
+	 * could change until it's actually outputted)
604
+	 *
605
+	 * @param boolean $init_form_validation_automatically whether or not we want the form validation
606
+	 *                                                    to be triggered automatically or not
607
+	 * @return void
608
+	 */
609
+	public static function wp_enqueue_scripts($init_form_validation_automatically = true)
610
+	{
611
+		add_filter('FHEE_load_jquery_validate', '__return_true');
612
+		wp_register_script(
613
+			'ee_form_section_validation',
614
+			EE_GLOBAL_ASSETS_URL . 'scripts' . DS . 'form_section_validation.js',
615
+			array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
616
+			EVENT_ESPRESSO_VERSION,
617
+			true
618
+		);
619
+		wp_localize_script(
620
+			'ee_form_section_validation',
621
+			'ee_form_section_validation_init',
622
+			array('init' => $init_form_validation_automatically ? true : false)
623
+		);
624
+	}
625
+
626
+
627
+
628
+	/**
629
+	 * gets the variables used by form_section_validation.js.
630
+	 * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
631
+	 * but before the wordpress hook wp_loaded
632
+	 *
633
+	 * @throws \EE_Error
634
+	 */
635
+	public function _enqueue_and_localize_form_js()
636
+	{
637
+		$this->ensure_construct_finalized_called();
638
+		//actually, we don't want to localize just yet. There may be other forms on the page.
639
+		//so we need to add our form section data to a static variable accessible by all form sections
640
+		//and localize it just before the footer
641
+		$this->localize_validation_rules();
642
+		add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
643
+		add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * add our form section data to a static variable accessible by all form sections
650
+	 *
651
+	 * @param bool $return_for_subsection
652
+	 * @return void
653
+	 * @throws \EE_Error
654
+	 */
655
+	public function localize_validation_rules($return_for_subsection = false)
656
+	{
657
+		// we only want to localize vars ONCE for the entire form,
658
+		// so if the form section doesn't have a parent, then it must be the top dog
659
+		if ($return_for_subsection || ! $this->parent_section()) {
660
+			EE_Form_Section_Proper::$_js_localization['form_data'][$this->html_id()] = array(
661
+				'form_section_id'  => $this->html_id(true),
662
+				'validation_rules' => $this->get_jquery_validation_rules(),
663
+				'other_data'       => $this->get_other_js_data(),
664
+				'errors'           => $this->subsection_validation_errors_by_html_name(),
665
+			);
666
+			EE_Form_Section_Proper::$_scripts_localized = true;
667
+		}
668
+	}
669
+
670
+
671
+
672
+	/**
673
+	 * Gets an array of extra data that will be useful for client-side javascript.
674
+	 * This is primarily data added by inputs and forms in addition to any
675
+	 * scripts they might enqueue
676
+	 *
677
+	 * @param array $form_other_js_data
678
+	 * @return array
679
+	 */
680
+	public function get_other_js_data($form_other_js_data = array())
681
+	{
682
+		foreach ($this->subsections() as $subsection) {
683
+			$form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
684
+		}
685
+		return $form_other_js_data;
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 * Gets a flat array of inputs for this form section and its subsections.
692
+	 * Keys are their form names, and values are the inputs themselves
693
+	 *
694
+	 * @return EE_Form_Input_Base
695
+	 */
696
+	public function inputs_in_subsections()
697
+	{
698
+		$inputs = array();
699
+		foreach ($this->subsections() as $subsection) {
700
+			if ($subsection instanceof EE_Form_Input_Base) {
701
+				$inputs[$subsection->html_name()] = $subsection;
702
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
703
+				$inputs += $subsection->inputs_in_subsections();
704
+			}
705
+		}
706
+		return $inputs;
707
+	}
708
+
709
+
710
+
711
+	/**
712
+	 * Gets a flat array of all the validation errors.
713
+	 * Keys are html names (because those should be unique)
714
+	 * and values are a string of all their validation errors
715
+	 *
716
+	 * @return string[]
717
+	 */
718
+	public function subsection_validation_errors_by_html_name()
719
+	{
720
+		$inputs = $this->inputs();
721
+		$errors = array();
722
+		foreach ($inputs as $form_input) {
723
+			if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
724
+				$errors[$form_input->html_name()] = $form_input->get_validation_error_string();
725
+			}
726
+		}
727
+		return $errors;
728
+	}
729
+
730
+
731
+
732
+	/**
733
+	 * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
734
+	 * Should be setup by each form during the _enqueues_and_localize_form_js
735
+	 */
736
+	public static function localize_script_for_all_forms()
737
+	{
738
+		//allow inputs and stuff to hook in their JS and stuff here
739
+		do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
740
+		EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
741
+		$email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
742
+			? EE_Registry::instance()->CFG->registration->email_validation_level
743
+			: 'wp_default';
744
+		EE_Form_Section_Proper::$_js_localization['email_validation_level'] = $email_validation_level;
745
+		wp_enqueue_script('ee_form_section_validation');
746
+		wp_localize_script(
747
+			'ee_form_section_validation',
748
+			'ee_form_section_vars',
749
+			EE_Form_Section_Proper::$_js_localization
750
+		);
751
+	}
752
+
753
+
754
+
755
+	/**
756
+	 * ensure_scripts_localized
757
+	 */
758
+	public function ensure_scripts_localized()
759
+	{
760
+		if ( ! EE_Form_Section_Proper::$_scripts_localized) {
761
+			$this->_enqueue_and_localize_form_js();
762
+		}
763
+	}
764
+
765
+
766
+
767
+	/**
768
+	 * Gets the hard-coded validation error messages to be used in the JS. The convention
769
+	 * is that the key here should be the same as the custom validation rule put in the JS file
770
+	 *
771
+	 * @return array keys are custom validation rules, and values are internationalized strings
772
+	 */
773
+	private static function _get_localized_error_messages()
774
+	{
775
+		return array(
776
+			'validUrl' => __("This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg", "event_espresso"),
777
+			'regex'    => __('Please check your input', 'event_espresso'),
778
+		);
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * @return array
785
+	 */
786
+	public static function js_localization()
787
+	{
788
+		return self::$_js_localization;
789
+	}
790
+
791
+
792
+
793
+	/**
794
+	 * @return array
795
+	 */
796
+	public static function reset_js_localization()
797
+	{
798
+		self::$_js_localization = array();
799
+	}
800
+
801
+
802
+
803
+	/**
804
+	 * Gets the JS to put inside the jquery validation rules for subsection of this form section.
805
+	 * See parent function for more...
806
+	 *
807
+	 * @return array
808
+	 */
809
+	public function get_jquery_validation_rules()
810
+	{
811
+		$jquery_validation_rules = array();
812
+		foreach ($this->get_validatable_subsections() as $subsection) {
813
+			$jquery_validation_rules = array_merge(
814
+				$jquery_validation_rules,
815
+				$subsection->get_jquery_validation_rules()
816
+			);
817
+		}
818
+		return $jquery_validation_rules;
819
+	}
820
+
821
+
822
+
823
+	/**
824
+	 * Sanitizes all the data and sets the sanitized value of each field
825
+	 *
826
+	 * @param array $req_data like $_POST
827
+	 * @return void
828
+	 */
829
+	protected function _normalize($req_data)
830
+	{
831
+		$this->_received_submission = true;
832
+		$this->_validation_errors = array();
833
+		foreach ($this->get_validatable_subsections() as $subsection) {
834
+			try {
835
+				$subsection->_normalize($req_data);
836
+			} catch (EE_Validation_Error $e) {
837
+				$subsection->add_validation_error($e);
838
+			}
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 * Performs validation on this form section and its subsections.
846
+	 * For each subsection,
847
+	 * calls _validate_{subsection_name} on THIS form (if the function exists)
848
+	 * and passes it the subsection, then calls _validate on that subsection.
849
+	 * If you need to perform validation on the form as a whole (considering multiple)
850
+	 * you would be best to override this _validate method,
851
+	 * calling parent::_validate() first.
852
+	 */
853
+	protected function _validate()
854
+	{
855
+		foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
856
+			if (method_exists($this, '_validate_' . $subsection_name)) {
857
+				call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
858
+			}
859
+			$subsection->_validate();
860
+		}
861
+	}
862
+
863
+
864
+
865
+	/**
866
+	 * Gets all the validated inputs for the form section
867
+	 *
868
+	 * @return array
869
+	 */
870
+	public function valid_data()
871
+	{
872
+		$inputs = array();
873
+		foreach ($this->subsections() as $subsection_name => $subsection) {
874
+			if ($subsection instanceof EE_Form_Section_Proper) {
875
+				$inputs[$subsection_name] = $subsection->valid_data();
876
+			} else if ($subsection instanceof EE_Form_Input_Base) {
877
+				$inputs[$subsection_name] = $subsection->normalized_value();
878
+			}
879
+		}
880
+		return $inputs;
881
+	}
882
+
883
+
884
+
885
+	/**
886
+	 * Gets all the inputs on this form section
887
+	 *
888
+	 * @return EE_Form_Input_Base[]
889
+	 */
890
+	public function inputs()
891
+	{
892
+		$inputs = array();
893
+		foreach ($this->subsections() as $subsection_name => $subsection) {
894
+			if ($subsection instanceof EE_Form_Input_Base) {
895
+				$inputs[$subsection_name] = $subsection;
896
+			}
897
+		}
898
+		return $inputs;
899
+	}
900
+
901
+
902
+
903
+	/**
904
+	 * Gets all the subsections which are a proper form
905
+	 *
906
+	 * @return EE_Form_Section_Proper[]
907
+	 */
908
+	public function subforms()
909
+	{
910
+		$form_sections = array();
911
+		foreach ($this->subsections() as $name => $obj) {
912
+			if ($obj instanceof EE_Form_Section_Proper) {
913
+				$form_sections[$name] = $obj;
914
+			}
915
+		}
916
+		return $form_sections;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * Gets all the subsections (inputs, proper subsections, or html-only sections).
923
+	 * Consider using inputs() or subforms()
924
+	 * if you only want form inputs or proper form sections.
925
+	 *
926
+	 * @return EE_Form_Section_Proper[]
927
+	 */
928
+	public function subsections()
929
+	{
930
+		$this->ensure_construct_finalized_called();
931
+		return $this->_subsections;
932
+	}
933
+
934
+
935
+
936
+	/**
937
+	 * Returns a simple array where keys are input names, and values are their normalized
938
+	 * values. (Similar to calling get_input_value on inputs)
939
+	 *
940
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
941
+	 *                                        or just this forms' direct children inputs
942
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
943
+	 *                                        or allow multidimensional array
944
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
945
+	 *                                        with array keys being input names
946
+	 *                                        (regardless of whether they are from a subsection or not),
947
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
948
+	 *                                        where keys are always subsection names and values are either
949
+	 *                                        the input's normalized value, or an array like the top-level array
950
+	 */
951
+	public function input_values($include_subform_inputs = false, $flatten = false)
952
+	{
953
+		return $this->_input_values(false, $include_subform_inputs, $flatten);
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
960
+	 * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
961
+	 * is not necessarily the value we want to display to users. This creates an array
962
+	 * where keys are the input names, and values are their display values
963
+	 *
964
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
965
+	 *                                        or just this forms' direct children inputs
966
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
967
+	 *                                        or allow multidimensional array
968
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
969
+	 *                                        with array keys being input names
970
+	 *                                        (regardless of whether they are from a subsection or not),
971
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
972
+	 *                                        where keys are always subsection names and values are either
973
+	 *                                        the input's normalized value, or an array like the top-level array
974
+	 */
975
+	public function input_pretty_values($include_subform_inputs = false, $flatten = false)
976
+	{
977
+		return $this->_input_values(true, $include_subform_inputs, $flatten);
978
+	}
979
+
980
+
981
+
982
+	/**
983
+	 * Gets the input values from the form
984
+	 *
985
+	 * @param boolean $pretty                 Whether to retrieve the pretty value,
986
+	 *                                        or just the normalized value
987
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
988
+	 *                                        or just this forms' direct children inputs
989
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
990
+	 *                                        or allow multidimensional array
991
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
992
+	 *                                        input names (regardless of whether they are from a subsection or not),
993
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
994
+	 *                                        where keys are always subsection names and values are either
995
+	 *                                        the input's normalized value, or an array like the top-level array
996
+	 */
997
+	public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
998
+	{
999
+		$input_values = array();
1000
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1001
+			if ($subsection instanceof EE_Form_Input_Base) {
1002
+				$input_values[$subsection_name] = $pretty
1003
+					? $subsection->pretty_value()
1004
+					: $subsection->normalized_value();
1005
+			} else if ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1006
+				$subform_input_values = $subsection->_input_values($pretty, $include_subform_inputs, $flatten);
1007
+				if ($flatten) {
1008
+					$input_values = array_merge($input_values, $subform_input_values);
1009
+				} else {
1010
+					$input_values[$subsection_name] = $subform_input_values;
1011
+				}
1012
+			}
1013
+		}
1014
+		return $input_values;
1015
+	}
1016
+
1017
+
1018
+
1019
+	/**
1020
+	 * Gets the originally submitted input values from the form
1021
+	 *
1022
+	 * @param boolean $include_subforms  Whether to include inputs from subforms,
1023
+	 *                                   or just this forms' direct children inputs
1024
+	 * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1025
+	 *                                   with array keys being input names
1026
+	 *                                   (regardless of whether they are from a subsection or not),
1027
+	 *                                   and if $flatten is FALSE it can be a multidimensional array
1028
+	 *                                   where keys are always subsection names and values are either
1029
+	 *                                   the input's normalized value, or an array like the top-level array
1030
+	 */
1031
+	public function submitted_values($include_subforms = false)
1032
+	{
1033
+		$submitted_values = array();
1034
+		foreach ($this->subsections() as $subsection) {
1035
+			if ($subsection instanceof EE_Form_Input_Base) {
1036
+				// is this input part of an array of inputs?
1037
+				if (strpos($subsection->html_name(), '[') !== false) {
1038
+					$full_input_name = \EEH_Array::convert_array_values_to_keys(
1039
+						explode('[', str_replace(']', '', $subsection->html_name())),
1040
+						$subsection->raw_value()
1041
+					);
1042
+					$submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1043
+				} else {
1044
+					$submitted_values[$subsection->html_name()] = $subsection->raw_value();
1045
+				}
1046
+			} else if ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1047
+				$subform_input_values = $subsection->submitted_values($include_subforms);
1048
+				$submitted_values = array_replace_recursive($submitted_values, $subform_input_values);
1049
+			}
1050
+		}
1051
+		return $submitted_values;
1052
+	}
1053
+
1054
+
1055
+
1056
+	/**
1057
+	 * Indicates whether or not this form has received a submission yet
1058
+	 * (ie, had receive_form_submission called on it yet)
1059
+	 *
1060
+	 * @return boolean
1061
+	 * @throws \EE_Error
1062
+	 */
1063
+	public function has_received_submission()
1064
+	{
1065
+		$this->ensure_construct_finalized_called();
1066
+		return $this->_received_submission;
1067
+	}
1068
+
1069
+
1070
+
1071
+	/**
1072
+	 * Equivalent to passing 'exclude' in the constructor's options array.
1073
+	 * Removes the listed inputs from the form
1074
+	 *
1075
+	 * @param array $inputs_to_exclude values are the input names
1076
+	 * @return void
1077
+	 */
1078
+	public function exclude(array $inputs_to_exclude = array())
1079
+	{
1080
+		foreach ($inputs_to_exclude as $input_to_exclude_name) {
1081
+			unset($this->_subsections[$input_to_exclude_name]);
1082
+		}
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * @param array $inputs_to_hide
1089
+	 * @throws \EE_Error
1090
+	 */
1091
+	public function hide(array $inputs_to_hide = array())
1092
+	{
1093
+		foreach ($inputs_to_hide as $input_to_hide) {
1094
+			$input = $this->get_input($input_to_hide);
1095
+			$input->set_display_strategy(new EE_Hidden_Display_Strategy());
1096
+		}
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * add_subsections
1103
+	 * Adds the listed subsections to the form section.
1104
+	 * If $subsection_name_to_target is provided,
1105
+	 * then new subsections are added before or after that subsection,
1106
+	 * otherwise to the start or end of the entire subsections array.
1107
+	 *
1108
+	 * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1109
+	 *                                                          where keys are their names
1110
+	 * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1111
+	 *                                                          should be added before or after
1112
+	 *                                                          IF $subsection_name_to_target is null,
1113
+	 *                                                          then $new_subsections will be added to
1114
+	 *                                                          the beginning or end of the entire subsections array
1115
+	 * @param boolean                $add_before                whether to add $new_subsections, before or after
1116
+	 *                                                          $subsection_name_to_target,
1117
+	 *                                                          or if $subsection_name_to_target is null,
1118
+	 *                                                          before or after entire subsections array
1119
+	 * @return void
1120
+	 * @throws \EE_Error
1121
+	 */
1122
+	public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1123
+	{
1124
+		foreach ($new_subsections as $subsection_name => $subsection) {
1125
+			if ( ! $subsection instanceof EE_Form_Section_Base) {
1126
+				EE_Error::add_error(
1127
+					sprintf(
1128
+						__(
1129
+							"Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1130
+							"event_espresso"
1131
+						),
1132
+						get_class($subsection),
1133
+						$subsection_name,
1134
+						$this->name()
1135
+					)
1136
+				);
1137
+				unset($new_subsections[$subsection_name]);
1138
+			}
1139
+		}
1140
+		$this->_subsections = EEH_Array::insert_into_array(
1141
+			$this->_subsections,
1142
+			$new_subsections,
1143
+			$subsection_name_to_target,
1144
+			$add_before
1145
+		);
1146
+		if ($this->_construction_finalized) {
1147
+			foreach ($this->_subsections as $name => $subsection) {
1148
+				$subsection->_construct_finalize($this, $name);
1149
+			}
1150
+		}
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * Just gets all validatable subsections to clean their sensitive data
1157
+	 */
1158
+	public function clean_sensitive_data()
1159
+	{
1160
+		foreach ($this->get_validatable_subsections() as $subsection) {
1161
+			$subsection->clean_sensitive_data();
1162
+		}
1163
+	}
1164
+
1165
+
1166
+
1167
+	/**
1168
+	 * @param string $form_submission_error_message
1169
+	 */
1170
+	public function set_submission_error_message($form_submission_error_message = '')
1171
+	{
1172
+		$this->_form_submission_error_message .= ! empty($form_submission_error_message)
1173
+			? $form_submission_error_message
1174
+			: __('Form submission failed due to errors', 'event_espresso');
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * @return string
1181
+	 */
1182
+	public function submission_error_message()
1183
+	{
1184
+		return $this->_form_submission_error_message;
1185
+	}
1186
+
1187
+
1188
+
1189
+	/**
1190
+	 * @param string $form_submission_success_message
1191
+	 */
1192
+	public function set_submission_success_message($form_submission_success_message)
1193
+	{
1194
+		$this->_form_submission_success_message .= ! empty($form_submission_success_message)
1195
+			? $form_submission_success_message
1196
+			: __('Form submitted successfully', 'event_espresso');
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * @return string
1203
+	 */
1204
+	public function submission_success_message()
1205
+	{
1206
+		return $this->_form_submission_success_message;
1207
+	}
1208
+
1209
+
1210
+
1211
+	/**
1212
+	 * Returns the prefix that should be used on child of this form section for
1213
+	 * their html names. If this form section itself has a parent, prepends ITS
1214
+	 * prefix onto this form section's prefix. Used primarily by
1215
+	 * EE_Form_Input_Base::_set_default_html_name_if_empty
1216
+	 *
1217
+	 * @return string
1218
+	 * @throws \EE_Error
1219
+	 */
1220
+	public function html_name_prefix()
1221
+	{
1222
+		if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1223
+			return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1224
+		} else {
1225
+			return $this->name();
1226
+		}
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets the name, but first checks _construct_finalize has been called. If not,
1233
+	 * calls it (assumes there is no parent and that we want the name to be whatever
1234
+	 * was set, which is probably nothing, or the classname)
1235
+	 *
1236
+	 * @return string
1237
+	 * @throws \EE_Error
1238
+	 */
1239
+	public function name()
1240
+	{
1241
+		$this->ensure_construct_finalized_called();
1242
+		return parent::name();
1243
+	}
1244
+
1245
+
1246
+
1247
+	/**
1248
+	 * @return EE_Form_Section_Proper
1249
+	 * @throws \EE_Error
1250
+	 */
1251
+	public function parent_section()
1252
+	{
1253
+		$this->ensure_construct_finalized_called();
1254
+		return parent::parent_section();
1255
+	}
1256
+
1257
+
1258
+
1259
+	/**
1260
+	 * make sure construction finalized was called, otherwise children might not be ready
1261
+	 *
1262
+	 * @return void
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	public function ensure_construct_finalized_called()
1266
+	{
1267
+		if ( ! $this->_construction_finalized) {
1268
+			$this->_construct_finalize($this->_parent_section, $this->_name);
1269
+		}
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Checks if any of this form section's inputs, or any of its children's inputs,
1276
+	 * are in teh form data. If any are found, returns true. Else false
1277
+	 *
1278
+	 * @param array $req_data
1279
+	 * @return boolean
1280
+	 */
1281
+	public function form_data_present_in($req_data = null)
1282
+	{
1283
+		if ($req_data === null) {
1284
+			$req_data = $_POST;
1285
+		}
1286
+		foreach ($this->subsections() as $subsection) {
1287
+			if ($subsection instanceof EE_Form_Input_Base) {
1288
+				if ($subsection->form_data_present_in($req_data)) {
1289
+					return true;
1290
+				}
1291
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
1292
+				if ($subsection->form_data_present_in($req_data)) {
1293
+					return true;
1294
+				}
1295
+			}
1296
+		}
1297
+		return false;
1298
+	}
1299
+
1300
+
1301
+
1302
+	/**
1303
+	 * Gets validation errors for this form section and subsections
1304
+	 * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1305
+	 * gets the validation errors for ALL subsection
1306
+	 *
1307
+	 * @return EE_Validation_Error[]
1308
+	 */
1309
+	public function get_validation_errors_accumulated()
1310
+	{
1311
+		$validation_errors = $this->get_validation_errors();
1312
+		foreach ($this->get_validatable_subsections() as $subsection) {
1313
+			if ($subsection instanceof EE_Form_Section_Proper) {
1314
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1315
+			} else {
1316
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors();
1317
+			}
1318
+			if ($validation_errors_on_this_subsection) {
1319
+				$validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1320
+			}
1321
+		}
1322
+		return $validation_errors;
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * This isn't just the name of an input, it's a path pointing to an input. The
1329
+	 * path is similar to a folder path: slash (/) means to descend into a subsection,
1330
+	 * dot-dot-slash (../) means to ascend into the parent section.
1331
+	 * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1332
+	 * which will be returned.
1333
+	 * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1334
+	 * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1335
+	 * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1336
+	 * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1337
+	 * Etc
1338
+	 *
1339
+	 * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1340
+	 * @return EE_Form_Section_Base
1341
+	 */
1342
+	public function find_section_from_path($form_section_path)
1343
+	{
1344
+		//check if we can find the input from purely going straight up the tree
1345
+		$input = parent::find_section_from_path($form_section_path);
1346
+		if ($input instanceof EE_Form_Section_Base) {
1347
+			return $input;
1348
+		}
1349
+		$next_slash_pos = strpos($form_section_path, '/');
1350
+		if ($next_slash_pos !== false) {
1351
+			$child_section_name = substr($form_section_path, 0, $next_slash_pos);
1352
+			$subpath = substr($form_section_path, $next_slash_pos + 1);
1353
+		} else {
1354
+			$child_section_name = $form_section_path;
1355
+			$subpath = '';
1356
+		}
1357
+		$child_section = $this->get_subsection($child_section_name);
1358
+		if ($child_section instanceof EE_Form_Section_Base) {
1359
+			return $child_section->find_section_from_path($subpath);
1360
+		} else {
1361
+			return null;
1362
+		}
1363
+	}
1364 1364
 
1365 1365
 }
1366 1366
 
Please login to merge, or discard this patch.
public/Espresso_Arabica_2014/content-espresso_events-thumbnail.php 1 patch
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -1,15 +1,15 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 //echo '<br/><h6 style="color:#2EA2CC;">'. __FILE__ . ' &nbsp; <span style="font-weight:normal;color:#E76700"> Line #: ' . __LINE__ . '</span></h6>';
3 3
 global $post;
4
-do_action( 'AHEE_event_details_before_featured_img', $post );
4
+do_action('AHEE_event_details_before_featured_img', $post);
5 5
 
6
-if ( has_post_thumbnail( $post->ID )) :
7
-	if ( $img_ID = get_post_thumbnail_id( $post->ID )) :
8
-		if ( $featured_img = wp_get_attachment_image_src( $img_ID, 'large' )) :
9
-			$caption = esc_attr( get_post( get_post( $img_ID ))->post_excerpt );
6
+if (has_post_thumbnail($post->ID)) :
7
+	if ($img_ID = get_post_thumbnail_id($post->ID)) :
8
+		if ($featured_img = wp_get_attachment_image_src($img_ID, 'large')) :
9
+			$caption = esc_attr(get_post(get_post($img_ID))->post_excerpt);
10 10
 			?>
11 11
 <div id="ee-event-img-dv-<?php echo $post->ID; ?>" class="ee-event-img-dv">
12
-	<a class="ee-event-img-lnk" href="<?php the_permalink(); ?>"<?php echo \EED_Events_Archive::link_target();?>>
12
+	<a class="ee-event-img-lnk" href="<?php the_permalink(); ?>"<?php echo \EED_Events_Archive::link_target(); ?>>
13 13
 		<img class="ee-event-img" src="<?php echo $featured_img[0]; ?>" width="<?php echo $featured_img[1]; ?>" height="<?php echo $featured_img[2]; ?>" alt="<?php echo $caption; ?>"/>
14 14
 	</a>
15 15
 </div>
@@ -18,4 +18,4 @@  discard block
 block discarded – undo
18 18
 	endif;
19 19
 endif;
20 20
 ?>
21
-<?php do_action( 'AHEE_event_details_after_featured_img', $post );?>
21
+<?php do_action('AHEE_event_details_after_featured_img', $post); ?>
Please login to merge, or discard this patch.
public/Espresso_Arabica_2014/content-espresso_events-header.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -5,9 +5,9 @@
 block discarded – undo
5 5
 ?>
6 6
 <header class="event-header">
7 7
 	<?php echo "<{$tag}  id=\"event-details-{$tag}-{$post->ID}\" class=\"entry-title\">"; ?>
8
-		<a class="ee-event-header-lnk" href="<?php the_permalink(); ?>"<?php echo \EED_Events_Archive::link_target();?>>
8
+		<a class="ee-event-header-lnk" href="<?php the_permalink(); ?>"<?php echo \EED_Events_Archive::link_target(); ?>>
9 9
             <?php the_title(); ?>
10 10
         </a>
11 11
 	<?php echo "</{$tag}"; ?>
12
-	<?php if ( ! is_archive() && has_excerpt( $post->ID )): the_excerpt(); endif;?>
12
+	<?php if ( ! is_archive() && has_excerpt($post->ID)): the_excerpt(); endif; ?>
13 13
 </header>
Please login to merge, or discard this patch.
modules/events_archive/EED_Events_Archive.module.php 3 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -37,19 +37,19 @@  discard block
 block discarded – undo
37 37
 	 */
38 38
 	protected static $using_get_the_excerpt = false;
39 39
 
40
-    /**
41
-     * Used to flag when the event list is being called from an external iframe.
42
-     *
43
-     * @var bool $iframe
44
-     */
45
-    protected static $iframe = false;
46
-
47
-    /**
40
+	/**
41
+	 * Used to flag when the event list is being called from an external iframe.
42
+	 *
43
+	 * @var bool $iframe
44
+	 */
45
+	protected static $iframe = false;
46
+
47
+	/**
48 48
 	 * @var \EventEspresso\core\libraries\iframe_display\EventListIframeEmbedButton $_iframe_embed_button
49 49
 	 */
50 50
 	private static $_iframe_embed_button;
51 51
 
52
-    /**
52
+	/**
53 53
 	 * @type EE_Template_Part_Manager $template_parts
54 54
 	 */
55 55
 	protected $template_parts;
@@ -233,26 +233,26 @@  discard block
 block discarded – undo
233 233
 
234 234
 
235 235
 
236
-    /**
237
-     * @access    public
238
-     * @return    void
239
-     * @throws \EE_Error
240
-     * @throws \DomainException
241
-     */
236
+	/**
237
+	 * @access    public
238
+	 * @return    void
239
+	 * @throws \EE_Error
240
+	 * @throws \DomainException
241
+	 */
242 242
 	public function event_list_iframe() {
243
-        \EED_Events_Archive::$iframe = true;
243
+		\EED_Events_Archive::$iframe = true;
244 244
 		$event_list_iframe = new EventsArchiveIframe( $this );
245 245
 		$event_list_iframe->display();
246 246
 	}
247 247
 
248 248
 
249 249
 
250
-    /**
251
-     * @access public
252
-     * @return string
253
-     */
250
+	/**
251
+	 * @access public
252
+	 * @return string
253
+	 */
254 254
 	public static function link_target() {
255
-        return \EED_Events_Archive::$iframe ? ' target="_blank"' : '';
255
+		return \EED_Events_Archive::$iframe ? ' target="_blank"' : '';
256 256
 	}
257 257
 
258 258
 
Please login to merge, or discard this patch.
Spacing   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\libraries\iframe_display\EventListIframeEmbedButton;
4 4
 use EventEspresso\modules\events_archive\EventsArchiveIframe;
5 5
 
6
-if ( ! defined( 'EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7 7
 /**
8 8
  * Event Espresso
9 9
  *
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	 * @return EED_Events_Archive
61 61
 	 */
62 62
 	public static function instance() {
63
-		return parent::get_instance( __CLASS__ );
63
+		return parent::get_instance(__CLASS__);
64 64
 	}
65 65
 
66 66
 
@@ -72,10 +72,10 @@  discard block
 block discarded – undo
72 72
 	 *  @return 	void
73 73
 	 */
74 74
 	public static function set_hooks() {
75
-		EE_Config::register_route( EE_Registry::instance()->CFG->core->event_cpt_slug, 'Events_Archive', 'run' );
76
-		EE_Config::register_route( 'event_list', 'Events_Archive', 'event_list' );
77
-		EE_Config::register_route( 'iframe', 'Events_Archive', 'event_list_iframe', 'event_list' );
78
-		add_action( 'wp_loaded', array( 'EED_Events_Archive', 'set_definitions' ), 2 );
75
+		EE_Config::register_route(EE_Registry::instance()->CFG->core->event_cpt_slug, 'Events_Archive', 'run');
76
+		EE_Config::register_route('event_list', 'Events_Archive', 'event_list');
77
+		EE_Config::register_route('iframe', 'Events_Archive', 'event_list_iframe', 'event_list');
78
+		add_action('wp_loaded', array('EED_Events_Archive', 'set_definitions'), 2);
79 79
 	}
80 80
 
81 81
 	/**
@@ -85,12 +85,12 @@  discard block
 block discarded – undo
85 85
 	 *  @return 	void
86 86
 	 */
87 87
 	public static function set_hooks_admin() {
88
-		add_action( 'wp_loaded', array( 'EED_Events_Archive', 'set_definitions' ), 2 );
88
+		add_action('wp_loaded', array('EED_Events_Archive', 'set_definitions'), 2);
89 89
 		// hook into the end of the \EE_Admin_Page::_load_page_dependencies()
90 90
 		// to load assets for "espresso_events" page on the "default" route (action)
91 91
 		add_action(
92 92
 			'FHEE__EE_Admin_Page___load_page_dependencies__after_load__espresso_events__default',
93
-			array( 'EED_Events_Archive', 'event_list_iframe_embed_button' ),
93
+			array('EED_Events_Archive', 'event_list_iframe_embed_button'),
94 94
 			10
95 95
 		);
96 96
 	}
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 	 *  @return 	void
106 106
 	 */
107 107
 	public static function set_definitions() {
108
-		define( 'EVENTS_ARCHIVE_ASSETS_URL', plugin_dir_url( __FILE__ ) . 'assets' . DS );
109
-		define( 'EVENTS_ARCHIVE_TEMPLATES_PATH', str_replace( '\\', DS, plugin_dir_path( __FILE__ )) . 'templates' . DS );
108
+		define('EVENTS_ARCHIVE_ASSETS_URL', plugin_dir_url(__FILE__).'assets'.DS);
109
+		define('EVENTS_ARCHIVE_TEMPLATES_PATH', str_replace('\\', DS, plugin_dir_path(__FILE__)).'templates'.DS);
110 110
 	}
111 111
 
112 112
 
@@ -114,10 +114,10 @@  discard block
 block discarded – undo
114 114
 	/**
115 115
 	 * set up EE_Events_Archive_Config
116 116
 	 */
117
-	protected function set_config(){
118
-		$this->set_config_section( 'template_settings' );
119
-		$this->set_config_class( 'EE_Events_Archive_Config' );
120
-		$this->set_config_name( 'EED_Events_Archive' );
117
+	protected function set_config() {
118
+		$this->set_config_section('template_settings');
119
+		$this->set_config_class('EE_Events_Archive_Config');
120
+		$this->set_config_name('EED_Events_Archive');
121 121
 	}
122 122
 
123 123
 
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @return EventListIframeEmbedButton
127 127
 	 */
128 128
 	public static function get_iframe_embed_button() {
129
-		if ( ! self::$_iframe_embed_button instanceof EventListIframeEmbedButton ) {
129
+		if ( ! self::$_iframe_embed_button instanceof EventListIframeEmbedButton) {
130 130
 			self::$_iframe_embed_button = new EventListIframeEmbedButton();
131 131
 		}
132 132
 		return self::$_iframe_embed_button;
@@ -152,35 +152,35 @@  discard block
 block discarded – undo
152 152
 	 * @param \EE_Events_Archive_Config $config
153 153
 	 * @return \EE_Template_Part_Manager
154 154
 	 */
155
-	public function initialize_template_parts( EE_Events_Archive_Config $config = null ) {
155
+	public function initialize_template_parts(EE_Events_Archive_Config $config = null) {
156 156
 		$config = $config instanceof EE_Events_Archive_Config ? $config : $this->config();
157 157
 		EEH_Autoloader::instance()->register_template_part_autoloaders();
158 158
 		$template_parts = new EE_Template_Part_Manager();
159 159
 		$template_parts->add_template_part(
160 160
 			'tickets',
161
-			__( 'Ticket Selector', 'event_espresso' ),
161
+			__('Ticket Selector', 'event_espresso'),
162 162
 			'content-espresso_events-tickets.php',
163 163
 			$config->display_order_tickets
164 164
 		);
165 165
 		$template_parts->add_template_part(
166 166
 			'datetimes',
167
-			__( 'Dates and Times', 'event_espresso' ),
167
+			__('Dates and Times', 'event_espresso'),
168 168
 			'content-espresso_events-datetimes.php',
169 169
 			$config->display_order_datetimes
170 170
 		);
171 171
 		$template_parts->add_template_part(
172 172
 			'event',
173
-			__( 'Event Description', 'event_espresso' ),
173
+			__('Event Description', 'event_espresso'),
174 174
 			'content-espresso_events-details.php',
175 175
 			$config->display_order_event
176 176
 		);
177 177
 		$template_parts->add_template_part(
178 178
 			'venue',
179
-			__( 'Venue Information', 'event_espresso' ),
179
+			__('Venue Information', 'event_espresso'),
180 180
 			'content-espresso_events-venues.php',
181 181
 			$config->display_order_venue
182 182
 		);
183
-		do_action( 'AHEE__EED_Event_Archive__initialize_template_parts', $template_parts );
183
+		do_action('AHEE__EED_Event_Archive__initialize_template_parts', $template_parts);
184 184
 		return $template_parts;
185 185
 	}
186 186
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 	 * @param WP $WP
194 194
 	 * @return    void
195 195
 	 */
196
-	public function run( $WP ) {
197
-		do_action( 'AHEE__EED_Events_Archive__before_run' );
196
+	public function run($WP) {
197
+		do_action('AHEE__EED_Events_Archive__before_run');
198 198
 		// ensure valid EE_Events_Archive_Config() object exists
199 199
 		$this->set_config();
200 200
 		/** @type EE_Events_Archive_Config $config */
@@ -206,14 +206,14 @@  discard block
 block discarded – undo
206 206
 		EEH_Event_Query::add_query_filters();
207 207
 		// set params that will get used by the filters
208 208
 		EEH_Event_Query::set_query_params(
209
-			'', 	// month
210
-			'', 	// category
211
-			$config->display_expired_events, 	// show_expired
212
-			'start_date', 	// orderby
209
+			'', // month
210
+			'', // category
211
+			$config->display_expired_events, // show_expired
212
+			'start_date', // orderby
213 213
 			'ASC' 	// sort
214 214
 		);
215 215
 		// check what template is loaded
216
-		add_filter( 'template_include',  array( $this, 'template_include' ), 999, 1 );
216
+		add_filter('template_include', array($this, 'template_include'), 999, 1);
217 217
 	}
218 218
 
219 219
 
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
      */
242 242
 	public function event_list_iframe() {
243 243
         \EED_Events_Archive::$iframe = true;
244
-		$event_list_iframe = new EventsArchiveIframe( $this );
244
+		$event_list_iframe = new EventsArchiveIframe($this);
245 245
 		$event_list_iframe->display();
246 246
 	}
247 247
 
@@ -269,32 +269,32 @@  discard block
 block discarded – undo
269 269
 	 * @param string $template
270 270
 	 * @return    string
271 271
 	 */
272
-	public function template_include( $template = '' ) {
272
+	public function template_include($template = '') {
273 273
 		// don't add content filter for dedicated EE child themes or private posts
274
-		if ( ! EEH_Template::is_espresso_theme() ) {
274
+		if ( ! EEH_Template::is_espresso_theme()) {
275 275
 			/** @type EE_Events_Archive_Config $config */
276 276
 			$config = $this->config();
277 277
 			// add status banner ?
278
-			if ( $config->display_status_banner ) {
279
-				add_filter( 'the_title', array( 'EED_Events_Archive', 'the_title' ), 100, 2 );
278
+			if ($config->display_status_banner) {
279
+				add_filter('the_title', array('EED_Events_Archive', 'the_title'), 100, 2);
280 280
 			}
281 281
 			// if NOT a custom template
282 282
 			if (
283
-				EE_Registry::instance()->load_core( 'Front_Controller', array(), false, true )->get_selected_template() != 'archive-espresso_events.php'
284
-				|| apply_filters( 'FHEE__EED_Event_Archive__template_include__allow_custom_selected_template', FALSE )
283
+				EE_Registry::instance()->load_core('Front_Controller', array(), false, true)->get_selected_template() != 'archive-espresso_events.php'
284
+				|| apply_filters('FHEE__EED_Event_Archive__template_include__allow_custom_selected_template', FALSE)
285 285
 			) {
286 286
 				// don't display entry meta because the existing theme will take care of that
287
-				add_filter( 'FHEE__EED_Events_Archive__template_include__events_list_active', '__return_true' );
287
+				add_filter('FHEE__EED_Events_Archive__template_include__events_list_active', '__return_true');
288 288
 			// load functions.php file for the theme (loaded by WP if using child theme)
289 289
 				EEH_Template::load_espresso_theme_functions();
290 290
 				// because we don't know if the theme is using the_excerpt()
291
-				add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
291
+				add_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100, 1);
292 292
 				// or the_content
293
-				add_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
293
+				add_filter('the_content', array('EED_Events_Archive', 'event_details'), 100, 1);
294 294
 				// and just in case they are running get_the_excerpt() which DESTROYS things
295
-				add_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1, 1 );
295
+				add_filter('get_the_excerpt', array('EED_Events_Archive', 'get_the_excerpt'), 1, 1);
296 296
 				// don't display entry meta because the existing theme will take care of that
297
-				add_filter( 'FHEE__content_espresso_events_details_template__display_entry_meta', '__return_false' );
297
+				add_filter('FHEE__content_espresso_events_details_template__display_entry_meta', '__return_false');
298 298
 			}
299 299
 		}
300 300
 		return $template;
@@ -309,17 +309,17 @@  discard block
 block discarded – undo
309 309
 	 * 	@param		string 	$excerpt
310 310
 	 * 	@return 		string
311 311
 	 */
312
-	public static function get_the_excerpt( $excerpt = '' ) {
313
-		if ( post_password_required() ) {
312
+	public static function get_the_excerpt($excerpt = '') {
313
+		if (post_password_required()) {
314 314
 			return $excerpt;
315 315
 		}
316
-		if ( apply_filters( 'FHEE__EED_Events_Archive__get_the_excerpt__theme_uses_get_the_excerpt', false ) ) {
317
-			remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100 );
318
-			remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100 );
319
-			$excerpt = EED_Events_Archive::event_details( $excerpt );
316
+		if (apply_filters('FHEE__EED_Events_Archive__get_the_excerpt__theme_uses_get_the_excerpt', false)) {
317
+			remove_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100);
318
+			remove_filter('the_content', array('EED_Events_Archive', 'event_details'), 100);
319
+			$excerpt = EED_Events_Archive::event_details($excerpt);
320 320
 		} else {
321 321
 			EED_Events_Archive::$using_get_the_excerpt = true;
322
-			add_filter( 'wp_trim_excerpt', array( 'EED_Events_Archive', 'end_get_the_excerpt' ), 999, 1 );
322
+			add_filter('wp_trim_excerpt', array('EED_Events_Archive', 'end_get_the_excerpt'), 999, 1);
323 323
 		}
324 324
 		return $excerpt;
325 325
 	}
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 	 * @param  string $text
334 334
 	 * @return string
335 335
 	 */
336
-	public static function end_get_the_excerpt( $text = '' ) {
336
+	public static function end_get_the_excerpt($text = '') {
337 337
 		EED_Events_Archive::$using_get_the_excerpt = false;
338 338
 		return $text;
339 339
 	}
@@ -348,10 +348,10 @@  discard block
 block discarded – undo
348 348
 	 * @param 		string 		$id
349 349
 	 * @return 		string
350 350
 	 */
351
-	public static function the_title( $title = '', $id = '' ) {
351
+	public static function the_title($title = '', $id = '') {
352 352
 	global $post;
353
-	if ( $post instanceof WP_Post ) {
354
-		return in_the_loop() && $post->ID == $id ? espresso_event_status_banner( $post->ID  ) . $title :  $title;
353
+	if ($post instanceof WP_Post) {
354
+		return in_the_loop() && $post->ID == $id ? espresso_event_status_banner($post->ID).$title : $title;
355 355
 	}
356 356
 	return $title;
357 357
 }
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 * 	@param		string 	$content
366 366
 	 * 	@return 		string
367 367
 	 */
368
-	public static function event_details( $content ) {
368
+	public static function event_details($content) {
369 369
 		global $post;
370 370
 		static $current_post_ID = 0;
371 371
 		if (
@@ -374,8 +374,8 @@  discard block
 block discarded – undo
374 374
 			&& ! EED_Events_Archive::$using_get_the_excerpt
375 375
 			&& ! post_password_required()
376 376
 			&& (
377
-				apply_filters( 'FHEE__EES_Espresso_Events__process_shortcode__true', false )
378
-				|| ! apply_filters( 'FHEE__content_espresso_events__template_loaded', false )
377
+				apply_filters('FHEE__EES_Espresso_Events__process_shortcode__true', false)
378
+				|| ! apply_filters('FHEE__content_espresso_events__template_loaded', false)
379 379
 			)
380 380
 		) {
381 381
 			// Set current post ID to prevent showing content twice, but only if headers have definitely been sent.
@@ -384,8 +384,8 @@  discard block
 block discarded – undo
384 384
 			// We want to allow those plugins to still do their thing and have access to our content, but depending on
385 385
 			// how your event content is being displayed (shortcode, CPT route, etc), this filter can get applied twice,
386 386
 			// so the following allows this filter to be applied multiple times, but only once for real
387
-			$current_post_ID = did_action( 'loop_start' ) ? $post->ID : 0;
388
-			if ( EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->use_sortable_display_order ) {
387
+			$current_post_ID = did_action('loop_start') ? $post->ID : 0;
388
+			if (EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->use_sortable_display_order) {
389 389
 				$content = \EED_Events_Archive::use_sortable_display_order();
390 390
 			} else {
391 391
 				$content = \EED_Events_Archive::use_filterable_display_order();
@@ -404,20 +404,20 @@  discard block
 block discarded – undo
404 404
 	 */
405 405
 	protected static function use_sortable_display_order() {
406 406
 		// no further password checks required atm
407
-		add_filter( 'FHEE__EED_Events_Archive__event_details__no_post_password_required', '__return_true' );
407
+		add_filter('FHEE__EED_Events_Archive__event_details__no_post_password_required', '__return_true');
408 408
 		// we need to first remove this callback from being applied to the_content() or the_excerpt() (otherwise it will recurse and blow up the interweb)
409
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100 );
410
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100 );
411
-		remove_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1 );
409
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100);
410
+		remove_filter('the_content', array('EED_Events_Archive', 'event_details'), 100);
411
+		remove_filter('get_the_excerpt', array('EED_Events_Archive', 'get_the_excerpt'), 1);
412 412
 		// now add additional content depending on whether event is using the_excerpt() or the_content()
413 413
 		EED_Events_Archive::instance()->template_parts = EED_Events_Archive::instance()->initialize_template_parts();
414
-		$content = EEH_Template::locate_template( 'content-espresso_events-details.php' );
415
-		$content = EED_Events_Archive::instance()->template_parts->apply_template_part_filters( $content );
414
+		$content = EEH_Template::locate_template('content-espresso_events-details.php');
415
+		$content = EED_Events_Archive::instance()->template_parts->apply_template_part_filters($content);
416 416
 		// re-add our main filters (or else the next event won't have them)
417
-		add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
418
-		add_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
419
-		add_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1, 1 );
420
-		remove_filter( 'FHEE__EED_Events_Archive__event_details__no_post_password_required', '__return_true' );
417
+		add_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100, 1);
418
+		add_filter('the_content', array('EED_Events_Archive', 'event_details'), 100, 1);
419
+		add_filter('get_the_excerpt', array('EED_Events_Archive', 'get_the_excerpt'), 1, 1);
420
+		remove_filter('FHEE__EED_Events_Archive__event_details__no_post_password_required', '__return_true');
421 421
 		return $content;
422 422
 	}
423 423
 
@@ -432,22 +432,22 @@  discard block
 block discarded – undo
432 432
 	protected static function use_filterable_display_order() {
433 433
 		// we need to first remove this callback from being applied to the_content()
434 434
 		// (otherwise it will recurse and blow up the interweb)
435
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100 );
436
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100 );
437
-		remove_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1 );
435
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100);
436
+		remove_filter('the_content', array('EED_Events_Archive', 'event_details'), 100);
437
+		remove_filter('get_the_excerpt', array('EED_Events_Archive', 'get_the_excerpt'), 1);
438 438
 		//now add additional content depending on whether event is using the_excerpt() or the_content()
439 439
 		EED_Events_Archive::_add_additional_excerpt_filters();
440 440
 		EED_Events_Archive::_add_additional_content_filters();
441
-		do_action( 'AHEE__EED_Events_Archive__use_filterable_display_order__after_add_filters' );
441
+		do_action('AHEE__EED_Events_Archive__use_filterable_display_order__after_add_filters');
442 442
 		// now load our template
443
-		$content = EEH_Template::locate_template( 'content-espresso_events-details.php' );
443
+		$content = EEH_Template::locate_template('content-espresso_events-details.php');
444 444
 		// re-add our main filters (or else the next event won't have them)
445
-		add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
446
-		add_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100, 1 );
447
-		add_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1, 1 );
445
+		add_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100, 1);
446
+		add_filter('the_content', array('EED_Events_Archive', 'event_details'), 100, 1);
447
+		add_filter('get_the_excerpt', array('EED_Events_Archive', 'get_the_excerpt'), 1, 1);
448 448
 		// but remove the other filters so that they don't get applied to the next post
449 449
 		EED_Events_Archive::_remove_additional_events_archive_filters();
450
-		do_action( 'AHEE__EED_Events_Archive__use_filterable_display_order__after_remove_filters' );
450
+		do_action('AHEE__EED_Events_Archive__use_filterable_display_order__after_remove_filters');
451 451
 		// we're not returning the $content directly because the template we are loading uses the_content (or the_excerpt)
452 452
 		//return ! empty( $template ) ? $template : $content;
453 453
 		return $content;
@@ -462,11 +462,11 @@  discard block
 block discarded – undo
462 462
 	 * 	@param		string 	$content
463 463
 	 *  	@return 		string
464 464
 	 */
465
-	public static function event_datetimes( $content ) {
466
-		if ( post_password_required() ) {
465
+	public static function event_datetimes($content) {
466
+		if (post_password_required()) {
467 467
 			return $content;
468 468
 		}
469
-		return EEH_Template::locate_template( 'content-espresso_events-datetimes.php' ) . $content;
469
+		return EEH_Template::locate_template('content-espresso_events-datetimes.php').$content;
470 470
 	}
471 471
 
472 472
 	/**
@@ -476,11 +476,11 @@  discard block
 block discarded – undo
476 476
 	 * 	@param		string 	$content
477 477
 	 *  	@return 		string
478 478
 	 */
479
-	public static function event_tickets( $content ) {
480
-		if ( post_password_required() ) {
479
+	public static function event_tickets($content) {
480
+		if (post_password_required()) {
481 481
 			return $content;
482 482
 		}
483
-		return EEH_Template::locate_template( 'content-espresso_events-tickets.php' ) . $content;
483
+		return EEH_Template::locate_template('content-espresso_events-tickets.php').$content;
484 484
 	}
485 485
 
486 486
 
@@ -492,8 +492,8 @@  discard block
 block discarded – undo
492 492
 	 * @param    string $content
493 493
 	 * @return    string
494 494
 	 */
495
-	public static function event_venue( $content ) {
496
-		return EED_Events_Archive::event_venues( $content );
495
+	public static function event_venue($content) {
496
+		return EED_Events_Archive::event_venues($content);
497 497
 	}
498 498
 
499 499
 	/**
@@ -503,11 +503,11 @@  discard block
 block discarded – undo
503 503
 	 * 	@param		string 	$content
504 504
 	 *  	@return 		string
505 505
 	 */
506
-	public static function event_venues( $content ) {
507
-		if ( post_password_required() ) {
506
+	public static function event_venues($content) {
507
+		if (post_password_required()) {
508 508
 			return $content;
509 509
 		}
510
-		return $content . EEH_Template::locate_template( 'content-espresso_events-venues.php' );
510
+		return $content.EEH_Template::locate_template('content-espresso_events-venues.php');
511 511
 	}
512 512
 
513 513
 
@@ -519,9 +519,9 @@  discard block
 block discarded – undo
519 519
 	 * @return        void
520 520
 	 */
521 521
 	private static function _add_additional_excerpt_filters() {
522
-		add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_datetimes' ), 110, 1 );
523
-		add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_tickets' ), 120, 1 );
524
-		add_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_venues' ), 130, 1 );
522
+		add_filter('the_excerpt', array('EED_Events_Archive', 'event_datetimes'), 110, 1);
523
+		add_filter('the_excerpt', array('EED_Events_Archive', 'event_tickets'), 120, 1);
524
+		add_filter('the_excerpt', array('EED_Events_Archive', 'event_venues'), 130, 1);
525 525
 	}
526 526
 
527 527
 
@@ -533,9 +533,9 @@  discard block
 block discarded – undo
533 533
 	 * @return        void
534 534
 	 */
535 535
 	private static function _add_additional_content_filters() {
536
-		add_filter( 'the_content', array( 'EED_Events_Archive', 'event_datetimes' ), 110, 1 );
537
-		add_filter( 'the_content', array( 'EED_Events_Archive', 'event_tickets' ), 120, 1 );
538
-		add_filter( 'the_content', array( 'EED_Events_Archive', 'event_venues' ), 130, 1 );
536
+		add_filter('the_content', array('EED_Events_Archive', 'event_datetimes'), 110, 1);
537
+		add_filter('the_content', array('EED_Events_Archive', 'event_tickets'), 120, 1);
538
+		add_filter('the_content', array('EED_Events_Archive', 'event_venues'), 130, 1);
539 539
 	}
540 540
 
541 541
 
@@ -547,12 +547,12 @@  discard block
 block discarded – undo
547 547
 	 * @return        void
548 548
 	 */
549 549
 	private static function _remove_additional_events_archive_filters() {
550
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_datetimes' ), 110 );
551
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_tickets' ), 120 );
552
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_venues' ), 130 );
553
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_datetimes' ), 110 );
554
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_tickets' ), 120 );
555
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_venues' ), 130 );
550
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_datetimes'), 110);
551
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_tickets'), 120);
552
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_venues'), 130);
553
+		remove_filter('the_content', array('EED_Events_Archive', 'event_datetimes'), 110);
554
+		remove_filter('the_content', array('EED_Events_Archive', 'event_tickets'), 120);
555
+		remove_filter('the_content', array('EED_Events_Archive', 'event_venues'), 130);
556 556
 	}
557 557
 
558 558
 
@@ -565,17 +565,17 @@  discard block
 block discarded – undo
565 565
 	 */
566 566
 	public static function remove_all_events_archive_filters() {
567 567
 		//remove_filter( 'get_the_excerpt', array( 'EED_Events_Archive', 'get_the_excerpt' ), 1 );
568
-		remove_filter( 'the_title', array( 'EED_Events_Archive', 'the_title' ), 100 );
569
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_details' ), 100 );
570
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_datetimes' ), 110 );
571
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_tickets' ), 120 );
572
-		remove_filter( 'the_excerpt', array( 'EED_Events_Archive', 'event_venues' ), 130 );
573
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_details' ), 100 );
574
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_datetimes' ), 110 );
575
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_tickets' ), 120 );
576
-		remove_filter( 'the_content', array( 'EED_Events_Archive', 'event_venues' ), 130 );
568
+		remove_filter('the_title', array('EED_Events_Archive', 'the_title'), 100);
569
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_details'), 100);
570
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_datetimes'), 110);
571
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_tickets'), 120);
572
+		remove_filter('the_excerpt', array('EED_Events_Archive', 'event_venues'), 130);
573
+		remove_filter('the_content', array('EED_Events_Archive', 'event_details'), 100);
574
+		remove_filter('the_content', array('EED_Events_Archive', 'event_datetimes'), 110);
575
+		remove_filter('the_content', array('EED_Events_Archive', 'event_tickets'), 120);
576
+		remove_filter('the_content', array('EED_Events_Archive', 'event_venues'), 130);
577 577
 		// don't display entry meta because the existing theme will take care of that
578
-		remove_filter( 'FHEE__content_espresso_events_details_template__display_entry_meta', '__return_false' );
578
+		remove_filter('FHEE__content_espresso_events_details_template__display_entry_meta', '__return_false');
579 579
 	}
580 580
 
581 581
 
@@ -590,12 +590,12 @@  discard block
 block discarded – undo
590 590
 	 *  @return 	void
591 591
 	 */
592 592
 	public function load_event_list_assets() {
593
-		do_action( 'AHEE__EED_Events_Archive__before_load_assets' );
594
-		add_filter( 'FHEE_load_EE_Session', '__return_true' );
595
-		add_filter( 'FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true' );
596
-		add_action('wp_enqueue_scripts', array( $this, 'wp_enqueue_scripts' ), 10 );
597
-		if ( EE_Registry::instance()->CFG->map_settings->use_google_maps ) {
598
-			add_action('wp_enqueue_scripts', array( 'EEH_Maps', 'espresso_google_map_js' ), 11 );
593
+		do_action('AHEE__EED_Events_Archive__before_load_assets');
594
+		add_filter('FHEE_load_EE_Session', '__return_true');
595
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
596
+		add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 10);
597
+		if (EE_Registry::instance()->CFG->map_settings->use_google_maps) {
598
+			add_action('wp_enqueue_scripts', array('EEH_Maps', 'espresso_google_map_js'), 11);
599 599
 		}
600 600
 	}
601 601
 
@@ -612,13 +612,13 @@  discard block
 block discarded – undo
612 612
 	 */
613 613
 	public function wp_enqueue_scripts() {
614 614
 		// get some style
615
-		if ( apply_filters( 'FHEE_enable_default_espresso_css', FALSE ) ) {
615
+		if (apply_filters('FHEE_enable_default_espresso_css', FALSE)) {
616 616
 			// first check uploads folder
617
-			if ( EEH_File::is_readable( get_stylesheet_directory() . $this->theme . DS . 'style.css' )) {
618
-				wp_register_style( $this->theme, get_stylesheet_directory_uri() . $this->theme . DS . 'style.css', array( 'dashicons', 'espresso_default' ));
617
+			if (EEH_File::is_readable(get_stylesheet_directory().$this->theme.DS.'style.css')) {
618
+				wp_register_style($this->theme, get_stylesheet_directory_uri().$this->theme.DS.'style.css', array('dashicons', 'espresso_default'));
619 619
 			} else {
620 620
 		}
621
-		wp_enqueue_style( $this->theme );
621
+		wp_enqueue_style($this->theme);
622 622
 
623 623
 	}
624 624
 }
@@ -636,8 +636,8 @@  discard block
 block discarded – undo
636 636
 	 */
637 637
 	public static function template_settings_form() {
638 638
 	$template_settings = EE_Registry::instance()->CFG->template_settings;
639
-	$template_settings->EED_Events_Archive = isset( $template_settings->EED_Events_Archive ) ? $template_settings->EED_Events_Archive : new EE_Events_Archive_Config();
640
-	$template_settings->EED_Events_Archive = apply_filters( 'FHEE__EED_Events_Archive__template_settings_form__event_list_config', $template_settings->EED_Events_Archive );
639
+	$template_settings->EED_Events_Archive = isset($template_settings->EED_Events_Archive) ? $template_settings->EED_Events_Archive : new EE_Events_Archive_Config();
640
+	$template_settings->EED_Events_Archive = apply_filters('FHEE__EED_Events_Archive__template_settings_form__event_list_config', $template_settings->EED_Events_Archive);
641 641
 	$events_archive_settings = array(
642 642
 		'display_status_banner' => 0,
643 643
 		'display_description' => 1,
@@ -646,8 +646,8 @@  discard block
 block discarded – undo
646 646
 		'display_venue' => 0,
647 647
 		'display_expired_events' => 0
648 648
 	);
649
-	$events_archive_settings = array_merge( $events_archive_settings, (array)$template_settings->EED_Events_Archive );
650
-	EEH_Template::display_template( EVENTS_ARCHIVE_TEMPLATES_PATH . 'admin-event-list-settings.template.php', $events_archive_settings );
649
+	$events_archive_settings = array_merge($events_archive_settings, (array) $template_settings->EED_Events_Archive);
650
+	EEH_Template::display_template(EVENTS_ARCHIVE_TEMPLATES_PATH.'admin-event-list-settings.template.php', $events_archive_settings);
651 651
 }
652 652
 
653 653
 
@@ -663,16 +663,16 @@  discard block
 block discarded – undo
663 663
 	 *  @param 	EE_Request_Handler $REQ
664 664
 	 *  @return 	EE_Template_Config
665 665
 	 */
666
-	public static function update_template_settings( $CFG, $REQ ) {
666
+	public static function update_template_settings($CFG, $REQ) {
667 667
 		$CFG->EED_Events_Archive = new EE_Events_Archive_Config();
668 668
 		// unless we are resetting the config...
669
-		if ( ! isset( $REQ['EED_Events_Archive_reset_event_list_settings'] ) || absint( $REQ['EED_Events_Archive_reset_event_list_settings'] ) !== 1 ) {
670
-			$CFG->EED_Events_Archive->display_status_banner = isset( $REQ['EED_Events_Archive_display_status_banner'] ) ? absint( $REQ['EED_Events_Archive_display_status_banner'] ) : 0;
671
-			$CFG->EED_Events_Archive->display_description = isset( $REQ['EED_Events_Archive_display_description'] ) ? absint( $REQ['EED_Events_Archive_display_description'] ) : 1;
672
-			$CFG->EED_Events_Archive->display_ticket_selector = isset( $REQ['EED_Events_Archive_display_ticket_selector'] ) ? absint( $REQ['EED_Events_Archive_display_ticket_selector'] ) : 0;
673
-			$CFG->EED_Events_Archive->display_datetimes = isset( $REQ['EED_Events_Archive_display_datetimes'] ) ? absint( $REQ['EED_Events_Archive_display_datetimes'] ) : 1;
674
-			$CFG->EED_Events_Archive->display_venue = isset( $REQ['EED_Events_Archive_display_venue'] ) ? absint( $REQ['EED_Events_Archive_display_venue'] ) : 0;
675
-			$CFG->EED_Events_Archive->display_expired_events = isset( $REQ['EED_Events_Archive_display_expired_events'] ) ? absint( $REQ['EED_Events_Archive_display_expired_events'] ) : 0;			}
669
+		if ( ! isset($REQ['EED_Events_Archive_reset_event_list_settings']) || absint($REQ['EED_Events_Archive_reset_event_list_settings']) !== 1) {
670
+			$CFG->EED_Events_Archive->display_status_banner = isset($REQ['EED_Events_Archive_display_status_banner']) ? absint($REQ['EED_Events_Archive_display_status_banner']) : 0;
671
+			$CFG->EED_Events_Archive->display_description = isset($REQ['EED_Events_Archive_display_description']) ? absint($REQ['EED_Events_Archive_display_description']) : 1;
672
+			$CFG->EED_Events_Archive->display_ticket_selector = isset($REQ['EED_Events_Archive_display_ticket_selector']) ? absint($REQ['EED_Events_Archive_display_ticket_selector']) : 0;
673
+			$CFG->EED_Events_Archive->display_datetimes = isset($REQ['EED_Events_Archive_display_datetimes']) ? absint($REQ['EED_Events_Archive_display_datetimes']) : 1;
674
+			$CFG->EED_Events_Archive->display_venue = isset($REQ['EED_Events_Archive_display_venue']) ? absint($REQ['EED_Events_Archive_display_venue']) : 0;
675
+			$CFG->EED_Events_Archive->display_expired_events = isset($REQ['EED_Events_Archive_display_expired_events']) ? absint($REQ['EED_Events_Archive_display_expired_events']) : 0; }
676 676
 		return $CFG;
677 677
 	}
678 678
 
@@ -685,10 +685,10 @@  discard block
 block discarded – undo
685 685
 	 * @param string $extra_class
686 686
 	 * @return    string
687 687
 	 */
688
-	public static function event_list_css( $extra_class = '' ) {
689
-		$event_list_css = ! empty( $extra_class ) ? array( $extra_class ) : array();
688
+	public static function event_list_css($extra_class = '') {
689
+		$event_list_css = ! empty($extra_class) ? array($extra_class) : array();
690 690
 		$event_list_css[] = 'espresso-event-list-event';
691
-		return implode( ' ', $event_list_css );
691
+		return implode(' ', $event_list_css);
692 692
 	}
693 693
 
694 694
 
@@ -715,9 +715,9 @@  discard block
 block discarded – undo
715 715
 	 * @param $value
716 716
 	 * @return    bool
717 717
 	 */
718
-	public static function display_description( $value ) {
718
+	public static function display_description($value) {
719 719
 		$config = EE_Registry::instance()->CFG->template_settings->EED_Events_Archive;
720
-		$display_description= isset( $config->display_description ) ? $config->display_description : 1;
720
+		$display_description = isset($config->display_description) ? $config->display_description : 1;
721 721
 		return $display_description === $value ? TRUE : FALSE;
722 722
 	}
723 723
 
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
 	 */
731 731
 	public static function display_ticket_selector() {
732 732
 		$config = EE_Registry::instance()->CFG->template_settings->EED_Events_Archive;
733
-		return isset( $config->display_ticket_selector ) && $config->display_ticket_selector ? TRUE : FALSE;
733
+		return isset($config->display_ticket_selector) && $config->display_ticket_selector ? TRUE : FALSE;
734 734
 	}
735 735
 
736 736
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
 	 */
744 744
 	public static function display_venue() {
745 745
 		$config = EE_Registry::instance()->CFG->template_settings->EED_Events_Archive;
746
-		return isset( $config->display_venue ) && $config->display_venue && EEH_Venue_View::venue_name() ? TRUE : FALSE;
746
+		return isset($config->display_venue) && $config->display_venue && EEH_Venue_View::venue_name() ? TRUE : FALSE;
747 747
 	}
748 748
 
749 749
 
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 	 */
756 756
 	public static function display_datetimes() {
757 757
 		$config = EE_Registry::instance()->CFG->template_settings->EED_Events_Archive;
758
-		return isset( $config->display_datetimes ) && $config->display_datetimes ? TRUE : FALSE;
758
+		return isset($config->display_datetimes) && $config->display_datetimes ? TRUE : FALSE;
759 759
 }
760 760
 
761 761
 
@@ -770,7 +770,7 @@  discard block
 block discarded – undo
770 770
 	 *  @return 	string
771 771
 	 */
772 772
 	public static function event_list_title() {
773
-		return apply_filters( 'FHEE__archive_espresso_events_template__upcoming_events_h1', __( 'Upcoming Events', 'event_espresso' ));
773
+		return apply_filters('FHEE__archive_espresso_events_template__upcoming_events_h1', __('Upcoming Events', 'event_espresso'));
774 774
 	}
775 775
 
776 776
 
@@ -779,11 +779,11 @@  discard block
 block discarded – undo
779 779
 	/**
780 780
 	 * 	@since 4.4.0
781 781
 	 */
782
-	public static function _doing_it_wrong_notice( $function = '' ) {
782
+	public static function _doing_it_wrong_notice($function = '') {
783 783
 		EE_Error::doing_it_wrong(
784 784
 			__FUNCTION__,
785 785
 			sprintf(
786
-				__( 'EED_Events_Archive::%1$s was moved to EEH_Event_Query::%1$s:%2$sPlease update your existing code because the method it calls will be removed in version %3$s', 'event_espresso' ),
786
+				__('EED_Events_Archive::%1$s was moved to EEH_Event_Query::%1$s:%2$sPlease update your existing code because the method it calls will be removed in version %3$s', 'event_espresso'),
787 787
 				$function,
788 788
 				'<br />',
789 789
 				'4.6.0'
@@ -805,89 +805,89 @@  discard block
 block discarded – undo
805 805
 	 * 	@deprecated
806 806
 	 * 	@since 4.4.0
807 807
 	 */
808
-	public function posts_fields( $SQL, WP_Query $wp_query ) {
809
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
810
-		return EEH_Event_Query::posts_fields( $SQL, $wp_query );
808
+	public function posts_fields($SQL, WP_Query $wp_query) {
809
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
810
+		return EEH_Event_Query::posts_fields($SQL, $wp_query);
811 811
 	}
812 812
 	/**
813 813
 	 * 	@deprecated
814 814
 	 * 	@since 4.4.0
815 815
 	 */
816
-	public static function posts_fields_sql_for_orderby( $orderby_params = array() ) {
817
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
818
-		return EEH_Event_Query::posts_fields_sql_for_orderby( $orderby_params );
816
+	public static function posts_fields_sql_for_orderby($orderby_params = array()) {
817
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
818
+		return EEH_Event_Query::posts_fields_sql_for_orderby($orderby_params);
819 819
 	}
820 820
 	/**
821 821
 	 * 	@deprecated
822 822
 	 * 	@since 4.4.0
823 823
 	 */
824
-	public function posts_join( $SQL, WP_Query $wp_query ) {
825
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
826
-		return EEH_Event_Query::posts_join( $SQL, $wp_query );
824
+	public function posts_join($SQL, WP_Query $wp_query) {
825
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
826
+		return EEH_Event_Query::posts_join($SQL, $wp_query);
827 827
 	}
828 828
 	/**
829 829
 	 * 	@deprecated
830 830
 	 * 	@since 4.4.0
831 831
 	 */
832
-	public static function posts_join_sql_for_terms( $join_terms = NULL ) {
833
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
834
-		return EEH_Event_Query::posts_join_sql_for_terms( $join_terms );
832
+	public static function posts_join_sql_for_terms($join_terms = NULL) {
833
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
834
+		return EEH_Event_Query::posts_join_sql_for_terms($join_terms);
835 835
 	}
836 836
 	/**
837 837
 	 * 	@deprecated
838 838
 	 * 	@since 4.4.0
839 839
 	 */
840
-	public static function posts_join_for_orderby( $orderby_params = array() ) {
841
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
842
-		return EEH_Event_Query::posts_join_for_orderby( $orderby_params );
840
+	public static function posts_join_for_orderby($orderby_params = array()) {
841
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
842
+		return EEH_Event_Query::posts_join_for_orderby($orderby_params);
843 843
 	}
844 844
 	/**
845 845
 	 * 	@deprecated
846 846
 	 * 	@since 4.4.0
847 847
 	 */
848
-	public function posts_where( $SQL, WP_Query $wp_query ) {
849
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
850
-		return EEH_Event_Query::posts_where( $SQL, $wp_query );
848
+	public function posts_where($SQL, WP_Query $wp_query) {
849
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
850
+		return EEH_Event_Query::posts_where($SQL, $wp_query);
851 851
 	}
852 852
 	/**
853 853
 	 * 	@deprecated
854 854
 	 * 	@since 4.4.0
855 855
 	 */
856
-	public static function posts_where_sql_for_show_expired( $show_expired = FALSE ) {
857
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
858
-		return EEH_Event_Query::posts_where_sql_for_show_expired( $show_expired );
856
+	public static function posts_where_sql_for_show_expired($show_expired = FALSE) {
857
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
858
+		return EEH_Event_Query::posts_where_sql_for_show_expired($show_expired);
859 859
 	}
860 860
 	/**
861 861
 	 * 	@deprecated
862 862
 	 * 	@since 4.4.0
863 863
 	 */
864
-	public static function posts_where_sql_for_event_category_slug( $event_category_slug = NULL ) {
865
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
866
-		return EEH_Event_Query::posts_where_sql_for_event_category_slug( $event_category_slug );
864
+	public static function posts_where_sql_for_event_category_slug($event_category_slug = NULL) {
865
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
866
+		return EEH_Event_Query::posts_where_sql_for_event_category_slug($event_category_slug);
867 867
 	}
868 868
 	/**
869 869
 	 * 	@deprecated
870 870
 	 * 	@since 4.4.0
871 871
 	 */
872
-	public static function posts_where_sql_for_event_list_month( $month = NULL ) {
873
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
874
-		return EEH_Event_Query::posts_where_sql_for_event_list_month( $month );
872
+	public static function posts_where_sql_for_event_list_month($month = NULL) {
873
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
874
+		return EEH_Event_Query::posts_where_sql_for_event_list_month($month);
875 875
 	}
876 876
 	/**
877 877
 	 * 	@deprecated
878 878
 	 * 	@since 4.4.0
879 879
 	 */
880
-	public function posts_orderby( $SQL, WP_Query $wp_query ) {
881
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
882
-		return EEH_Event_Query::posts_orderby( $SQL, $wp_query );
880
+	public function posts_orderby($SQL, WP_Query $wp_query) {
881
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
882
+		return EEH_Event_Query::posts_orderby($SQL, $wp_query);
883 883
 	}
884 884
 	/**
885 885
 	 * 	@deprecated
886 886
 	 * 	@since 4.4.0
887 887
 	 */
888
-	public static function posts_orderby_sql( $orderby_params = array(), $sort = 'ASC' ) {
889
-		EED_Events_Archive::_doing_it_wrong_notice( __FUNCTION__ );
890
-		return EEH_Event_Query::posts_orderby_sql( $orderby_params, $sort );
888
+	public static function posts_orderby_sql($orderby_params = array(), $sort = 'ASC') {
889
+		EED_Events_Archive::_doing_it_wrong_notice(__FUNCTION__);
890
+		return EEH_Event_Query::posts_orderby_sql($orderby_params, $sort);
891 891
 	}
892 892
 
893 893
 
@@ -918,8 +918,8 @@  discard block
 block discarded – undo
918 918
  * @param string $extra_class
919 919
  * @return string
920 920
  */
921
-function espresso_event_list_css( $extra_class = '' ) {
922
-	return EED_Events_Archive::event_list_css( $extra_class );
921
+function espresso_event_list_css($extra_class = '') {
922
+	return EED_Events_Archive::event_list_css($extra_class);
923 923
 }
924 924
 
925 925
 /**
@@ -933,14 +933,14 @@  discard block
 block discarded – undo
933 933
  * @return bool
934 934
  */
935 935
 function espresso_display_full_description_in_event_list() {
936
-	return EED_Events_Archive::display_description( 2 );
936
+	return EED_Events_Archive::display_description(2);
937 937
 }
938 938
 
939 939
 /**
940 940
  * @return bool
941 941
  */
942 942
 function espresso_display_excerpt_in_event_list() {
943
-	return EED_Events_Archive::display_description( 1 );
943
+	return EED_Events_Archive::display_description(1);
944 944
 }
945 945
 
946 946
 /**
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -3,7 +3,9 @@
 block discarded – undo
3 3
 use EventEspresso\core\libraries\iframe_display\EventListIframeEmbedButton;
4 4
 use EventEspresso\modules\events_archive\EventsArchiveIframe;
5 5
 
6
-if ( ! defined( 'EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
6
+if ( ! defined( 'EVENT_ESPRESSO_VERSION')) {
7
+	exit('No direct script access allowed');
8
+}
7 9
 /**
8 10
  * Event Espresso
9 11
  *
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -128,7 +128,8 @@
 block discarded – undo
128 128
      *
129 129
      * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the relevant status const
130 130
      * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save further processing
131
-     * @return mixed status int if the display string isn't requested
131
+     * @param boolean $remaining
132
+     * @return string status int if the display string isn't requested
132 133
      * @throws \EE_Error
133 134
      */
134 135
 	public function ticket_status( $display = FALSE, $remaining = null ) {
Please login to merge, or discard this patch.
Indentation   +566 added lines, -566 removed lines patch added patch discarded remove patch
@@ -61,15 +61,15 @@  discard block
 block discarded – undo
61 61
 
62 62
 
63 63
 
64
-    /**
65
-     * @param array  $props_n_values          incoming values
66
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
67
-     *                                        used.)
68
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
69
-     *                                        date_format and the second value is the time format
70
-     * @return EE_Ticket
71
-     * @throws \EE_Error
72
-     */
64
+	/**
65
+	 * @param array  $props_n_values          incoming values
66
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
67
+	 *                                        used.)
68
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
69
+	 *                                        date_format and the second value is the time format
70
+	 * @return EE_Ticket
71
+	 * @throws \EE_Error
72
+	 */
73 73
 	public static function new_instance( $props_n_values = array(), $timezone = null, $date_formats = array() ) {
74 74
 		$has_object = parent::_check_for_object( $props_n_values, __CLASS__, $timezone, $date_formats );
75 75
 		return $has_object ? $has_object : new self( $props_n_values, false, $timezone, $date_formats );
@@ -77,36 +77,36 @@  discard block
 block discarded – undo
77 77
 
78 78
 
79 79
 
80
-    /**
81
-     * @param array  $props_n_values  incoming values from the database
82
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
83
-     *                                the website will be used.
84
-     * @return EE_Ticket
85
-     * @throws \EE_Error
86
-     */
80
+	/**
81
+	 * @param array  $props_n_values  incoming values from the database
82
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
83
+	 *                                the website will be used.
84
+	 * @return EE_Ticket
85
+	 * @throws \EE_Error
86
+	 */
87 87
 	public static function new_instance_from_db( $props_n_values = array(), $timezone = null ) {
88 88
 		return new self( $props_n_values, TRUE, $timezone );
89 89
 	}
90 90
 
91 91
 
92 92
 
93
-    /**
94
-     * @return bool
95
-     * @throws \EE_Error
96
-     */
93
+	/**
94
+	 * @return bool
95
+	 * @throws \EE_Error
96
+	 */
97 97
 	public function parent() {
98 98
 		return $this->get( 'TKT_parent' );
99 99
 	}
100 100
 
101 101
 
102 102
 
103
-    /**
104
-     * return if a ticket has quantities available for purchase
105
-     *
106
-     * @param  int $DTT_ID the primary key for a particular datetime
107
-     * @return boolean
108
-     * @throws \EE_Error
109
-     */
103
+	/**
104
+	 * return if a ticket has quantities available for purchase
105
+	 *
106
+	 * @param  int $DTT_ID the primary key for a particular datetime
107
+	 * @return boolean
108
+	 * @throws \EE_Error
109
+	 */
110 110
 	public function available( $DTT_ID = 0 ) {
111 111
 		// are we checking availability for a particular datetime ?
112 112
 		if ( $DTT_ID ) {
@@ -123,14 +123,14 @@  discard block
 block discarded – undo
123 123
 
124 124
 
125 125
 
126
-    /**
127
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
128
-     *
129
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the relevant status const
130
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save further processing
131
-     * @return mixed status int if the display string isn't requested
132
-     * @throws \EE_Error
133
-     */
126
+	/**
127
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
128
+	 *
129
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the relevant status const
130
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save further processing
131
+	 * @return mixed status int if the display string isn't requested
132
+	 * @throws \EE_Error
133
+	 */
134 134
 	public function ticket_status( $display = FALSE, $remaining = null ) {
135 135
 		$remaining = is_bool( $remaining ) ? $remaining : $this->is_remaining();
136 136
 		if ( ! $remaining ) {
@@ -153,14 +153,14 @@  discard block
 block discarded – undo
153 153
 
154 154
 
155 155
 
156
-    /**
157
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale considering ALL the factors used for figuring that out.
158
-     *
159
-     * @access public
160
-     * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
161
-     * @return boolean         true = tickets remaining, false not.
162
-     * @throws \EE_Error
163
-     */
156
+	/**
157
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale considering ALL the factors used for figuring that out.
158
+	 *
159
+	 * @access public
160
+	 * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
161
+	 * @return boolean         true = tickets remaining, false not.
162
+	 * @throws \EE_Error
163
+	 */
164 164
 	public function is_remaining( $DTT_ID = 0 ) {
165 165
 		$num_remaining = $this->remaining( $DTT_ID );
166 166
 		if ( $num_remaining === 0 ) {
@@ -174,76 +174,76 @@  discard block
 block discarded – undo
174 174
 
175 175
 
176 176
 
177
-    /**
178
-     * return the total number of tickets available for purchase
179
-     *
180
-     * @param  int $DTT_ID the primary key for a particular datetime.
181
-     *                     set to 0 for all related datetimes
182
-     * @return int
183
-     * @throws \EE_Error
184
-     */
177
+	/**
178
+	 * return the total number of tickets available for purchase
179
+	 *
180
+	 * @param  int $DTT_ID the primary key for a particular datetime.
181
+	 *                     set to 0 for all related datetimes
182
+	 * @return int
183
+	 * @throws \EE_Error
184
+	 */
185 185
 	public function remaining( $DTT_ID = 0 ) {
186 186
 		return $this->real_quantity_on_ticket('saleable', $DTT_ID );
187 187
 	}
188 188
 
189 189
 
190 190
 
191
-    /**
192
-     * Gets min
193
-     *
194
-     * @return int
195
-     * @throws \EE_Error
196
-     */
191
+	/**
192
+	 * Gets min
193
+	 *
194
+	 * @return int
195
+	 * @throws \EE_Error
196
+	 */
197 197
 	public function min() {
198 198
 		return $this->get( 'TKT_min' );
199 199
 	}
200 200
 
201 201
 
202 202
 
203
-    /**
204
-     * return if a ticket is no longer available cause its available dates have expired.
205
-     *
206
-     * @return boolean
207
-     * @throws \EE_Error
208
-     */
203
+	/**
204
+	 * return if a ticket is no longer available cause its available dates have expired.
205
+	 *
206
+	 * @return boolean
207
+	 * @throws \EE_Error
208
+	 */
209 209
 	public function is_expired() {
210 210
 		return ( $this->get_raw( 'TKT_end_date' ) < time() );
211 211
 	}
212 212
 
213 213
 
214 214
 
215
-    /**
216
-     * Return if a ticket is yet to go on sale or not
217
-     *
218
-     * @return boolean
219
-     * @throws \EE_Error
220
-     */
215
+	/**
216
+	 * Return if a ticket is yet to go on sale or not
217
+	 *
218
+	 * @return boolean
219
+	 * @throws \EE_Error
220
+	 */
221 221
 	public function is_pending() {
222 222
 		return ( $this->get_raw( 'TKT_start_date' ) > time() );
223 223
 	}
224 224
 
225 225
 
226 226
 
227
-    /**
228
-     * Return if a ticket is on sale or not
229
-     *
230
-     * @return boolean
231
-     * @throws \EE_Error
232
-     */
227
+	/**
228
+	 * Return if a ticket is on sale or not
229
+	 *
230
+	 * @return boolean
231
+	 * @throws \EE_Error
232
+	 */
233 233
 	public function is_on_sale() {
234 234
 		return ( $this->get_raw( 'TKT_start_date' ) < time() && $this->get_raw( 'TKT_end_date' ) > time() );
235 235
 	}
236 236
 
237 237
 
238 238
 
239
-    /**
240
-     * This returns the chronologically last datetime that this ticket is associated with
241
-     *
242
-     * @param string $dt_frmt
243
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with the end date ie: Jan 01 "to" Dec 31
244
-     * @return string
245
-     * @throws \EE_Error
246
-     */
239
+	/**
240
+	 * This returns the chronologically last datetime that this ticket is associated with
241
+	 *
242
+	 * @param string $dt_frmt
243
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with the end date ie: Jan 01 "to" Dec 31
244
+	 * @return string
245
+	 * @throws \EE_Error
246
+	 */
247 247
 	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
248 248
 		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date( $dt_frmt ) : '';
249 249
 		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date( $dt_frmt ) : '';
@@ -253,12 +253,12 @@  discard block
 block discarded – undo
253 253
 
254 254
 
255 255
 
256
-    /**
257
-     * This returns the chronologically first datetime that this ticket is associated with
258
-     *
259
-     * @return EE_Datetime
260
-     * @throws \EE_Error
261
-     */
256
+	/**
257
+	 * This returns the chronologically first datetime that this ticket is associated with
258
+	 *
259
+	 * @return EE_Datetime
260
+	 * @throws \EE_Error
261
+	 */
262 262
 	public function first_datetime() {
263 263
 		$datetimes = $this->datetimes( array( 'limit' => 1 ) );
264 264
 		return reset( $datetimes );
@@ -266,14 +266,14 @@  discard block
 block discarded – undo
266 266
 
267 267
 
268 268
 
269
-    /**
270
-     * Gets all the datetimes this ticket can be used for attending.
271
-     * Unless otherwise specified, orders datetimes by start date.
272
-     *
273
-     * @param array $query_params see EEM_Base::get_all()
274
-     * @return EE_Datetime[]|EE_Base_Class[]
275
-     * @throws \EE_Error
276
-     */
269
+	/**
270
+	 * Gets all the datetimes this ticket can be used for attending.
271
+	 * Unless otherwise specified, orders datetimes by start date.
272
+	 *
273
+	 * @param array $query_params see EEM_Base::get_all()
274
+	 * @return EE_Datetime[]|EE_Base_Class[]
275
+	 * @throws \EE_Error
276
+	 */
277 277
 	public function datetimes( $query_params = array() ) {
278 278
 		if ( ! isset( $query_params[ 'order_by' ] ) ) {
279 279
 			$query_params[ 'order_by' ][ 'DTT_order' ] = 'ASC';
@@ -283,12 +283,12 @@  discard block
 block discarded – undo
283 283
 
284 284
 
285 285
 
286
-    /**
287
-     * This returns the chronologically last datetime that this ticket is associated with
288
-     *
289
-     * @return EE_Datetime
290
-     * @throws \EE_Error
291
-     */
286
+	/**
287
+	 * This returns the chronologically last datetime that this ticket is associated with
288
+	 *
289
+	 * @return EE_Datetime
290
+	 * @throws \EE_Error
291
+	 */
292 292
 	public function last_datetime() {
293 293
 		$datetimes = $this->datetimes( array( 'limit' => 1, 'order_by' => array( 'DTT_EVT_start' => 'DESC' ) ) );
294 294
 		return end( $datetimes );
@@ -296,19 +296,19 @@  discard block
 block discarded – undo
296 296
 
297 297
 
298 298
 
299
-    /**
300
-     * This returns the total tickets sold depending on the given parameters.
301
-     *
302
-     * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
303
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
304
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
305
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
306
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
307
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
308
-     * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
309
-     * @return mixed (array|int)          how many tickets have sold
310
-     * @throws \EE_Error
311
-     */
299
+	/**
300
+	 * This returns the total tickets sold depending on the given parameters.
301
+	 *
302
+	 * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
303
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
304
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
305
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
306
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
307
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
308
+	 * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
309
+	 * @return mixed (array|int)          how many tickets have sold
310
+	 * @throws \EE_Error
311
+	 */
312 312
 	public function tickets_sold( $what = 'ticket', $dtt_id = NULL ) {
313 313
 		$total = 0;
314 314
 		$tickets_sold = $this->_all_tickets_sold();
@@ -333,12 +333,12 @@  discard block
 block discarded – undo
333 333
 
334 334
 
335 335
 
336
-    /**
337
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
338
-     *
339
-     * @return EE_Ticket[]
340
-     * @throws \EE_Error
341
-     */
336
+	/**
337
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
338
+	 *
339
+	 * @return EE_Ticket[]
340
+	 * @throws \EE_Error
341
+	 */
342 342
 	protected function _all_tickets_sold() {
343 343
 		$datetimes = $this->get_many_related( 'Datetime' );
344 344
 		$tickets_sold = array();
@@ -354,29 +354,29 @@  discard block
 block discarded – undo
354 354
 
355 355
 
356 356
 
357
-    /**
358
-     * This returns the base price object for the ticket.
359
-     *
360
-     * @param  bool $return_array whether to return as an array indexed by price id or just the object.
361
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
362
-     * @throws \EE_Error
363
-     */
357
+	/**
358
+	 * This returns the base price object for the ticket.
359
+	 *
360
+	 * @param  bool $return_array whether to return as an array indexed by price id or just the object.
361
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
362
+	 * @throws \EE_Error
363
+	 */
364 364
 	public function base_price( $return_array = FALSE ) {
365 365
 		$_where = array( 'Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price );
366 366
 		return $return_array
367
-            ? $this->get_many_related( 'Price', array( $_where ) )
368
-            : $this->get_first_related( 'Price', array( $_where ) );
367
+			? $this->get_many_related( 'Price', array( $_where ) )
368
+			: $this->get_first_related( 'Price', array( $_where ) );
369 369
 	}
370 370
 
371 371
 
372 372
 
373
-    /**
374
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
375
-     *
376
-     * @access public
377
-     * @return EE_Price[]
378
-     * @throws \EE_Error
379
-     */
373
+	/**
374
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
375
+	 *
376
+	 * @access public
377
+	 * @return EE_Price[]
378
+	 * @throws \EE_Error
379
+	 */
380 380
 	public function price_modifiers() {
381 381
 		$query_params = array( 0 => array( 'Price_Type.PBT_ID' => array( 'NOT IN', array( EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax ) ) ) );
382 382
 		return $this->prices( $query_params );
@@ -384,132 +384,132 @@  discard block
 block discarded – undo
384 384
 
385 385
 
386 386
 
387
-    /**
388
-     * Gets all the prices that combine to form the final price of this ticket
389
-     *
390
-     * @param array $query_params like EEM_Base::get_all
391
-     * @return EE_Price[]|EE_Base_Class[]
392
-     * @throws \EE_Error
393
-     */
387
+	/**
388
+	 * Gets all the prices that combine to form the final price of this ticket
389
+	 *
390
+	 * @param array $query_params like EEM_Base::get_all
391
+	 * @return EE_Price[]|EE_Base_Class[]
392
+	 * @throws \EE_Error
393
+	 */
394 394
 	public function prices( $query_params = array() ) {
395 395
 		return $this->get_many_related( 'Price', $query_params );
396 396
 	}
397 397
 
398 398
 
399 399
 
400
-    /**
401
-     * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
402
-     *
403
-     * @param array $query_params see EEM_Base::get_all()
404
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
405
-     * @throws \EE_Error
406
-     */
400
+	/**
401
+	 * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
402
+	 *
403
+	 * @param array $query_params see EEM_Base::get_all()
404
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
405
+	 * @throws \EE_Error
406
+	 */
407 407
 	public function datetime_tickets( $query_params = array() ) {
408 408
 		return $this->get_many_related( 'Datetime_Ticket', $query_params );
409 409
 	}
410 410
 
411 411
 
412 412
 
413
-    /**
414
-     * Gets all the datetimes from the db ordered by DTT_order
415
-     *
416
-     * @param boolean $show_expired
417
-     * @param boolean $show_deleted
418
-     * @return EE_Datetime[]
419
-     * @throws \EE_Error
420
-     */
413
+	/**
414
+	 * Gets all the datetimes from the db ordered by DTT_order
415
+	 *
416
+	 * @param boolean $show_expired
417
+	 * @param boolean $show_deleted
418
+	 * @return EE_Datetime[]
419
+	 * @throws \EE_Error
420
+	 */
421 421
 	public function datetimes_ordered( $show_expired = TRUE, $show_deleted = FALSE ) {
422 422
 		return EEM_Datetime::instance( $this->_timezone )->get_datetimes_for_ticket_ordered_by_DTT_order( $this->ID(), $show_expired, $show_deleted );
423 423
 	}
424 424
 
425 425
 
426 426
 
427
-    /**
428
-     * Gets ID
429
-     *
430
-     * @return string
431
-     * @throws \EE_Error
432
-     */
427
+	/**
428
+	 * Gets ID
429
+	 *
430
+	 * @return string
431
+	 * @throws \EE_Error
432
+	 */
433 433
 	public function ID() {
434 434
 		return $this->get( 'TKT_ID' );
435 435
 	}
436 436
 
437 437
 
438 438
 
439
-    /**
440
-     * get the author of the ticket.
441
-     *
442
-     * @since 4.5.0
443
-     * @return int
444
-     * @throws \EE_Error
445
-     */
439
+	/**
440
+	 * get the author of the ticket.
441
+	 *
442
+	 * @since 4.5.0
443
+	 * @return int
444
+	 * @throws \EE_Error
445
+	 */
446 446
 	public function wp_user() {
447 447
 		return $this->get('TKT_wp_user');
448 448
 	}
449 449
 
450 450
 
451 451
 
452
-    /**
453
-     * Gets the template for the ticket
454
-     *
455
-     * @return EE_Ticket_Template|EE_Base_Class
456
-     * @throws \EE_Error
457
-     */
452
+	/**
453
+	 * Gets the template for the ticket
454
+	 *
455
+	 * @return EE_Ticket_Template|EE_Base_Class
456
+	 * @throws \EE_Error
457
+	 */
458 458
 	public function template() {
459 459
 		return $this->get_first_related( 'Ticket_Template' );
460 460
 	}
461 461
 
462 462
 
463 463
 
464
-    /**
465
-     * Simply returns an array of EE_Price objects that are taxes.
466
-     *
467
-     * @return EE_Price[]
468
-     * @throws \EE_Error
469
-     */
464
+	/**
465
+	 * Simply returns an array of EE_Price objects that are taxes.
466
+	 *
467
+	 * @return EE_Price[]
468
+	 * @throws \EE_Error
469
+	 */
470 470
 	public function get_ticket_taxes_for_admin() {
471 471
 		return EE_Taxes::get_taxes_for_admin();
472 472
 	}
473 473
 
474 474
 
475 475
 
476
-    /**
477
-     * @return float
478
-     * @throws \EE_Error
479
-     */
476
+	/**
477
+	 * @return float
478
+	 * @throws \EE_Error
479
+	 */
480 480
 	public function ticket_price() {
481 481
 		return $this->get( 'TKT_price' );
482 482
 	}
483 483
 
484 484
 
485 485
 
486
-    /**
487
-     * @return mixed
488
-     * @throws \EE_Error
489
-     */
486
+	/**
487
+	 * @return mixed
488
+	 * @throws \EE_Error
489
+	 */
490 490
 	public function pretty_price() {
491 491
 		return $this->get_pretty( 'TKT_price' );
492 492
 	}
493 493
 
494 494
 
495 495
 
496
-    /**
497
-     * @return bool
498
-     * @throws \EE_Error
499
-     */
496
+	/**
497
+	 * @return bool
498
+	 * @throws \EE_Error
499
+	 */
500 500
 	public function is_free() {
501 501
 		return $this->get_ticket_total_with_taxes() === 0;
502 502
 	}
503 503
 
504 504
 
505 505
 
506
-    /**
507
-     * get_ticket_total_with_taxes
508
-     *
509
-     * @param bool $no_cache
510
-     * @return float
511
-     * @throws \EE_Error
512
-     */
506
+	/**
507
+	 * get_ticket_total_with_taxes
508
+	 *
509
+	 * @param bool $no_cache
510
+	 * @return float
511
+	 * @throws \EE_Error
512
+	 */
513 513
 	public function get_ticket_total_with_taxes( $no_cache = FALSE ) {
514 514
 		if ($this->_ticket_total_with_taxes === null || $no_cache ) {
515 515
 			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
@@ -526,201 +526,201 @@  discard block
 block discarded – undo
526 526
 
527 527
 
528 528
 
529
-    /**
530
-     * @return float
531
-     * @throws \EE_Error
532
-     */
529
+	/**
530
+	 * @return float
531
+	 * @throws \EE_Error
532
+	 */
533 533
 	public function get_ticket_subtotal() {
534 534
 		return EE_Taxes::get_subtotal_for_admin( $this );
535 535
 	}
536 536
 
537 537
 
538 538
 
539
-    /**
540
-     * Returns the total taxes applied to this ticket
541
-     *
542
-     * @return float
543
-     * @throws \EE_Error
544
-     */
539
+	/**
540
+	 * Returns the total taxes applied to this ticket
541
+	 *
542
+	 * @return float
543
+	 * @throws \EE_Error
544
+	 */
545 545
 	public function get_ticket_taxes_total_for_admin() {
546 546
 		return EE_Taxes::get_total_taxes_for_admin( $this );
547 547
 	}
548 548
 
549 549
 
550 550
 
551
-    /**
552
-     * Sets name
553
-     *
554
-     * @param string $name
555
-     * @throws \EE_Error
556
-     */
551
+	/**
552
+	 * Sets name
553
+	 *
554
+	 * @param string $name
555
+	 * @throws \EE_Error
556
+	 */
557 557
 	public function set_name( $name ) {
558 558
 		$this->set( 'TKT_name', $name );
559 559
 	}
560 560
 
561 561
 
562 562
 
563
-    /**
564
-     * Gets description
565
-     *
566
-     * @return string
567
-     * @throws \EE_Error
568
-     */
563
+	/**
564
+	 * Gets description
565
+	 *
566
+	 * @return string
567
+	 * @throws \EE_Error
568
+	 */
569 569
 	public function description() {
570 570
 		return $this->get( 'TKT_description' );
571 571
 	}
572 572
 
573 573
 
574 574
 
575
-    /**
576
-     * Sets description
577
-     *
578
-     * @param string $description
579
-     * @throws \EE_Error
580
-     */
575
+	/**
576
+	 * Sets description
577
+	 *
578
+	 * @param string $description
579
+	 * @throws \EE_Error
580
+	 */
581 581
 	public function set_description( $description ) {
582 582
 		$this->set( 'TKT_description', $description );
583 583
 	}
584 584
 
585 585
 
586 586
 
587
-    /**
588
-     * Gets start_date
589
-     *
590
-     * @param string $dt_frmt
591
-     * @param string $tm_frmt
592
-     * @return string
593
-     * @throws \EE_Error
594
-     */
587
+	/**
588
+	 * Gets start_date
589
+	 *
590
+	 * @param string $dt_frmt
591
+	 * @param string $tm_frmt
592
+	 * @return string
593
+	 * @throws \EE_Error
594
+	 */
595 595
 	public function start_date( $dt_frmt = '', $tm_frmt = '' ) {
596 596
 		return $this->_get_datetime( 'TKT_start_date', $dt_frmt, $tm_frmt );
597 597
 	}
598 598
 
599 599
 
600 600
 
601
-    /**
602
-     * Sets start_date
603
-     *
604
-     * @param string $start_date
605
-     * @return void
606
-     * @throws \EE_Error
607
-     */
601
+	/**
602
+	 * Sets start_date
603
+	 *
604
+	 * @param string $start_date
605
+	 * @return void
606
+	 * @throws \EE_Error
607
+	 */
608 608
 	public function set_start_date( $start_date ) {
609 609
 		$this->_set_date_time( 'B', $start_date, 'TKT_start_date' );
610 610
 	}
611 611
 
612 612
 
613 613
 
614
-    /**
615
-     * Gets end_date
616
-     *
617
-     * @param string $dt_frmt
618
-     * @param string $tm_frmt
619
-     * @return string
620
-     * @throws \EE_Error
621
-     */
614
+	/**
615
+	 * Gets end_date
616
+	 *
617
+	 * @param string $dt_frmt
618
+	 * @param string $tm_frmt
619
+	 * @return string
620
+	 * @throws \EE_Error
621
+	 */
622 622
 	public function end_date( $dt_frmt = '', $tm_frmt = '' ) {
623 623
 		return $this->_get_datetime( 'TKT_end_date', $dt_frmt, $tm_frmt );
624 624
 	}
625 625
 
626 626
 
627 627
 
628
-    /**
629
-     * Sets end_date
630
-     *
631
-     * @param string $end_date
632
-     * @return void
633
-     * @throws \EE_Error
634
-     */
628
+	/**
629
+	 * Sets end_date
630
+	 *
631
+	 * @param string $end_date
632
+	 * @return void
633
+	 * @throws \EE_Error
634
+	 */
635 635
 	public function set_end_date( $end_date ) {
636 636
 		$this->_set_date_time( 'B', $end_date, 'TKT_end_date' );
637 637
 	}
638 638
 
639 639
 
640 640
 
641
-    /**
642
-     * Sets sell until time
643
-     *
644
-     * @since 4.5.0
645
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
646
-     * @throws \EE_Error
647
-     */
641
+	/**
642
+	 * Sets sell until time
643
+	 *
644
+	 * @since 4.5.0
645
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
646
+	 * @throws \EE_Error
647
+	 */
648 648
 	public function set_end_time( $time ) {
649 649
 		$this->_set_time_for( $time, 'TKT_end_date' );
650 650
 	}
651 651
 
652 652
 
653 653
 
654
-    /**
655
-     * Sets min
656
-     *
657
-     * @param int $min
658
-     * @return void
659
-     * @throws \EE_Error
660
-     */
654
+	/**
655
+	 * Sets min
656
+	 *
657
+	 * @param int $min
658
+	 * @return void
659
+	 * @throws \EE_Error
660
+	 */
661 661
 	public function set_min( $min ) {
662 662
 		$this->set( 'TKT_min', $min );
663 663
 	}
664 664
 
665 665
 
666 666
 
667
-    /**
668
-     * Gets max
669
-     *
670
-     * @return int
671
-     * @throws \EE_Error
672
-     */
667
+	/**
668
+	 * Gets max
669
+	 *
670
+	 * @return int
671
+	 * @throws \EE_Error
672
+	 */
673 673
 	public function max() {
674 674
 		return $this->get( 'TKT_max' );
675 675
 	}
676 676
 
677 677
 
678 678
 
679
-    /**
680
-     * Sets max
681
-     *
682
-     * @param int $max
683
-     * @return void
684
-     * @throws \EE_Error
685
-     */
679
+	/**
680
+	 * Sets max
681
+	 *
682
+	 * @param int $max
683
+	 * @return void
684
+	 * @throws \EE_Error
685
+	 */
686 686
 	public function set_max( $max ) {
687 687
 		$this->set( 'TKT_max', $max );
688 688
 	}
689 689
 
690 690
 
691 691
 
692
-    /**
693
-     * Sets price
694
-     *
695
-     * @param float $price
696
-     * @return void
697
-     * @throws \EE_Error
698
-     */
692
+	/**
693
+	 * Sets price
694
+	 *
695
+	 * @param float $price
696
+	 * @return void
697
+	 * @throws \EE_Error
698
+	 */
699 699
 	public function set_price( $price ) {
700 700
 		$this->set( 'TKT_price', $price );
701 701
 	}
702 702
 
703 703
 
704 704
 
705
-    /**
706
-     * Gets sold
707
-     *
708
-     * @return int
709
-     * @throws \EE_Error
710
-     */
705
+	/**
706
+	 * Gets sold
707
+	 *
708
+	 * @return int
709
+	 * @throws \EE_Error
710
+	 */
711 711
 	public function sold() {
712 712
 		return $this->get_raw( 'TKT_sold' );
713 713
 	}
714 714
 
715 715
 
716 716
 
717
-    /**
718
-     * Sets sold
719
-     *
720
-     * @param int $sold
721
-     * @return void
722
-     * @throws \EE_Error
723
-     */
717
+	/**
718
+	 * Sets sold
719
+	 *
720
+	 * @param int $sold
721
+	 * @return void
722
+	 * @throws \EE_Error
723
+	 */
724 724
 	public function set_sold( $sold ) {
725 725
 		// sold can not go below zero
726 726
 		$sold = max( 0, $sold );
@@ -729,13 +729,13 @@  discard block
 block discarded – undo
729 729
 
730 730
 
731 731
 
732
-    /**
733
-     * increments sold by amount passed by $qty
734
-     *
735
-     * @param int $qty
736
-     * @return void
737
-     * @throws \EE_Error
738
-     */
732
+	/**
733
+	 * increments sold by amount passed by $qty
734
+	 *
735
+	 * @param int $qty
736
+	 * @return void
737
+	 * @throws \EE_Error
738
+	 */
739 739
 	public function increase_sold( $qty = 1 ) {
740 740
 		$sold = $this->sold() + $qty;
741 741
 		// remove ticket reservation, but don't adjust datetime reservations,  because that will happen
@@ -747,13 +747,13 @@  discard block
 block discarded – undo
747 747
 
748 748
 
749 749
 
750
-    /**
751
-     * Increases sold on related datetimes
752
-     *
753
-     * @param int $qty
754
-     * @return void
755
-     * @throws \EE_Error
756
-     */
750
+	/**
751
+	 * Increases sold on related datetimes
752
+	 *
753
+	 * @param int $qty
754
+	 * @return void
755
+	 * @throws \EE_Error
756
+	 */
757 757
 	protected function _increase_sold_for_datetimes( $qty = 1 ) {
758 758
 		$datetimes = $this->datetimes();
759 759
 		if ( is_array( $datetimes ) ) {
@@ -768,13 +768,13 @@  discard block
 block discarded – undo
768 768
 
769 769
 
770 770
 
771
-    /**
772
-     * decrements (subtracts) sold by amount passed by $qty
773
-     *
774
-     * @param int $qty
775
-     * @return void
776
-     * @throws \EE_Error
777
-     */
771
+	/**
772
+	 * decrements (subtracts) sold by amount passed by $qty
773
+	 *
774
+	 * @param int $qty
775
+	 * @return void
776
+	 * @throws \EE_Error
777
+	 */
778 778
 	public function decrease_sold( $qty = 1 ) {
779 779
 		$sold = $this->sold() - $qty;
780 780
 		$this->_decrease_sold_for_datetimes( $qty );
@@ -783,13 +783,13 @@  discard block
 block discarded – undo
783 783
 
784 784
 
785 785
 
786
-    /**
787
-     * Decreases sold on related datetimes
788
-     *
789
-     * @param int $qty
790
-     * @return void
791
-     * @throws \EE_Error
792
-     */
786
+	/**
787
+	 * Decreases sold on related datetimes
788
+	 *
789
+	 * @param int $qty
790
+	 * @return void
791
+	 * @throws \EE_Error
792
+	 */
793 793
 	protected function _decrease_sold_for_datetimes( $qty = 1 ) {
794 794
 		$datetimes = $this->datetimes();
795 795
 		if ( is_array( $datetimes ) ) {
@@ -804,25 +804,25 @@  discard block
 block discarded – undo
804 804
 
805 805
 
806 806
 
807
-    /**
808
-     * Gets qty of reserved tickets
809
-     *
810
-     * @return int
811
-     * @throws \EE_Error
812
-     */
807
+	/**
808
+	 * Gets qty of reserved tickets
809
+	 *
810
+	 * @return int
811
+	 * @throws \EE_Error
812
+	 */
813 813
 	public function reserved() {
814 814
 		return $this->get_raw( 'TKT_reserved' );
815 815
 	}
816 816
 
817 817
 
818 818
 
819
-    /**
820
-     * Sets reserved
821
-     *
822
-     * @param int $reserved
823
-     * @return void
824
-     * @throws \EE_Error
825
-     */
819
+	/**
820
+	 * Sets reserved
821
+	 *
822
+	 * @param int $reserved
823
+	 * @return void
824
+	 * @throws \EE_Error
825
+	 */
826 826
 	public function set_reserved( $reserved ) {
827 827
 		// reserved can not go below zero
828 828
 		$reserved = max( 0, (int) $reserved );
@@ -831,13 +831,13 @@  discard block
 block discarded – undo
831 831
 
832 832
 
833 833
 
834
-    /**
835
-     * increments reserved by amount passed by $qty
836
-     *
837
-     * @param int $qty
838
-     * @return void
839
-     * @throws \EE_Error
840
-     */
834
+	/**
835
+	 * increments reserved by amount passed by $qty
836
+	 *
837
+	 * @param int $qty
838
+	 * @return void
839
+	 * @throws \EE_Error
840
+	 */
841 841
 	public function increase_reserved( $qty = 1 ) {
842 842
 		$qty = absint( $qty );
843 843
 		$reserved = $this->reserved() + $qty;
@@ -847,13 +847,13 @@  discard block
 block discarded – undo
847 847
 
848 848
 
849 849
 
850
-    /**
851
-     * Increases sold on related datetimes
852
-     *
853
-     * @param int $qty
854
-     * @return void
855
-     * @throws \EE_Error
856
-     */
850
+	/**
851
+	 * Increases sold on related datetimes
852
+	 *
853
+	 * @param int $qty
854
+	 * @return void
855
+	 * @throws \EE_Error
856
+	 */
857 857
 	protected function _increase_reserved_for_datetimes( $qty = 1 ) {
858 858
 		$datetimes = $this->datetimes();
859 859
 		if ( is_array( $datetimes ) ) {
@@ -868,14 +868,14 @@  discard block
 block discarded – undo
868 868
 
869 869
 
870 870
 
871
-    /**
872
-     * decrements (subtracts) reserved by amount passed by $qty
873
-     *
874
-     * @param int  $qty
875
-     * @param bool $adjust_datetimes
876
-     * @return void
877
-     * @throws \EE_Error
878
-     */
871
+	/**
872
+	 * decrements (subtracts) reserved by amount passed by $qty
873
+	 *
874
+	 * @param int  $qty
875
+	 * @param bool $adjust_datetimes
876
+	 * @return void
877
+	 * @throws \EE_Error
878
+	 */
879 879
 	public function decrease_reserved( $qty = 1, $adjust_datetimes = true ) {
880 880
 		$reserved = $this->reserved() - absint( $qty );
881 881
 		if ( $adjust_datetimes ) {
@@ -886,13 +886,13 @@  discard block
 block discarded – undo
886 886
 
887 887
 
888 888
 
889
-    /**
890
-     * Increases sold on related datetimes
891
-     *
892
-     * @param int $qty
893
-     * @return void
894
-     * @throws \EE_Error
895
-     */
889
+	/**
890
+	 * Increases sold on related datetimes
891
+	 *
892
+	 * @param int $qty
893
+	 * @return void
894
+	 * @throws \EE_Error
895
+	 */
896 896
 	protected function _decrease_reserved_for_datetimes( $qty = 1 ) {
897 897
 		$datetimes = $this->datetimes();
898 898
 		if ( is_array( $datetimes ) ) {
@@ -907,18 +907,18 @@  discard block
 block discarded – undo
907 907
 
908 908
 
909 909
 
910
-    /**
911
-     * Gets ticket quantity
912
-     *
913
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
914
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
915
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
916
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
917
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
918
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
919
-     * @return int
920
-     * @throws \EE_Error
921
-     */
910
+	/**
911
+	 * Gets ticket quantity
912
+	 *
913
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
914
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
915
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
916
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
917
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
918
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
919
+	 * @return int
920
+	 * @throws \EE_Error
921
+	 */
922 922
 	public function qty( $context = '' ) {
923 923
 		switch ( $context ) {
924 924
 			case 'reg_limit' :
@@ -932,19 +932,19 @@  discard block
 block discarded – undo
932 932
 
933 933
 
934 934
 
935
-    /**
936
-     * Gets ticket quantity
937
-     *
938
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
939
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
940
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
941
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
942
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
943
-     * @param  int   $DTT_ID      the primary key for a particular datetime.
944
-     *                            set to 0 for all related datetimes
945
-     * @return int
946
-     * @throws \EE_Error
947
-     */
935
+	/**
936
+	 * Gets ticket quantity
937
+	 *
938
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
939
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
940
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
941
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
942
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
943
+	 * @param  int   $DTT_ID      the primary key for a particular datetime.
944
+	 *                            set to 0 for all related datetimes
945
+	 * @return int
946
+	 * @throws \EE_Error
947
+	 */
948 948
 	public function real_quantity_on_ticket( $context = 'reg_limit', $DTT_ID = 0 ) {
949 949
 		$raw = $this->get_raw( 'TKT_qty' );
950 950
 		// return immediately if it's zero
@@ -1027,212 +1027,212 @@  discard block
 block discarded – undo
1027 1027
 
1028 1028
 
1029 1029
 
1030
-    /**
1031
-     * Gets uses
1032
-     *
1033
-     * @return int
1034
-     * @throws \EE_Error
1035
-     */
1030
+	/**
1031
+	 * Gets uses
1032
+	 *
1033
+	 * @return int
1034
+	 * @throws \EE_Error
1035
+	 */
1036 1036
 	public function uses() {
1037 1037
 		return $this->get( 'TKT_uses' );
1038 1038
 	}
1039 1039
 
1040 1040
 
1041 1041
 
1042
-    /**
1043
-     * Sets uses
1044
-     *
1045
-     * @param int $uses
1046
-     * @return void
1047
-     * @throws \EE_Error
1048
-     */
1042
+	/**
1043
+	 * Sets uses
1044
+	 *
1045
+	 * @param int $uses
1046
+	 * @return void
1047
+	 * @throws \EE_Error
1048
+	 */
1049 1049
 	public function set_uses( $uses ) {
1050 1050
 		$this->set( 'TKT_uses', $uses );
1051 1051
 	}
1052 1052
 
1053 1053
 
1054 1054
 
1055
-    /**
1056
-     * returns whether ticket is required or not.
1057
-     *
1058
-     * @return boolean
1059
-     * @throws \EE_Error
1060
-     */
1055
+	/**
1056
+	 * returns whether ticket is required or not.
1057
+	 *
1058
+	 * @return boolean
1059
+	 * @throws \EE_Error
1060
+	 */
1061 1061
 	public function required() {
1062 1062
 		return $this->get( 'TKT_required' );
1063 1063
 	}
1064 1064
 
1065 1065
 
1066 1066
 
1067
-    /**
1068
-     * sets the TKT_required property
1069
-     *
1070
-     * @param boolean $required
1071
-     * @return void
1072
-     * @throws \EE_Error
1073
-     */
1067
+	/**
1068
+	 * sets the TKT_required property
1069
+	 *
1070
+	 * @param boolean $required
1071
+	 * @return void
1072
+	 * @throws \EE_Error
1073
+	 */
1074 1074
 	public function set_required( $required ) {
1075 1075
 		$this->set( 'TKT_required', $required );
1076 1076
 	}
1077 1077
 
1078 1078
 
1079 1079
 
1080
-    /**
1081
-     * Gets taxable
1082
-     *
1083
-     * @return boolean
1084
-     * @throws \EE_Error
1085
-     */
1080
+	/**
1081
+	 * Gets taxable
1082
+	 *
1083
+	 * @return boolean
1084
+	 * @throws \EE_Error
1085
+	 */
1086 1086
 	public function taxable() {
1087 1087
 		return $this->get( 'TKT_taxable' );
1088 1088
 	}
1089 1089
 
1090 1090
 
1091 1091
 
1092
-    /**
1093
-     * Sets taxable
1094
-     *
1095
-     * @param boolean $taxable
1096
-     * @return void
1097
-     * @throws \EE_Error
1098
-     */
1092
+	/**
1093
+	 * Sets taxable
1094
+	 *
1095
+	 * @param boolean $taxable
1096
+	 * @return void
1097
+	 * @throws \EE_Error
1098
+	 */
1099 1099
 	public function set_taxable( $taxable ) {
1100 1100
 		$this->set( 'TKT_taxable', $taxable );
1101 1101
 	}
1102 1102
 
1103 1103
 
1104 1104
 
1105
-    /**
1106
-     * Gets is_default
1107
-     *
1108
-     * @return boolean
1109
-     * @throws \EE_Error
1110
-     */
1105
+	/**
1106
+	 * Gets is_default
1107
+	 *
1108
+	 * @return boolean
1109
+	 * @throws \EE_Error
1110
+	 */
1111 1111
 	public function is_default() {
1112 1112
 		return $this->get( 'TKT_is_default' );
1113 1113
 	}
1114 1114
 
1115 1115
 
1116 1116
 
1117
-    /**
1118
-     * Sets is_default
1119
-     *
1120
-     * @param boolean $is_default
1121
-     * @return void
1122
-     * @throws \EE_Error
1123
-     */
1117
+	/**
1118
+	 * Sets is_default
1119
+	 *
1120
+	 * @param boolean $is_default
1121
+	 * @return void
1122
+	 * @throws \EE_Error
1123
+	 */
1124 1124
 	public function set_is_default( $is_default ) {
1125 1125
 		$this->set( 'TKT_is_default', $is_default );
1126 1126
 	}
1127 1127
 
1128 1128
 
1129 1129
 
1130
-    /**
1131
-     * Gets order
1132
-     *
1133
-     * @return int
1134
-     * @throws \EE_Error
1135
-     */
1130
+	/**
1131
+	 * Gets order
1132
+	 *
1133
+	 * @return int
1134
+	 * @throws \EE_Error
1135
+	 */
1136 1136
 	public function order() {
1137 1137
 		return $this->get( 'TKT_order' );
1138 1138
 	}
1139 1139
 
1140 1140
 
1141 1141
 
1142
-    /**
1143
-     * Sets order
1144
-     *
1145
-     * @param int $order
1146
-     * @return void
1147
-     * @throws \EE_Error
1148
-     */
1142
+	/**
1143
+	 * Sets order
1144
+	 *
1145
+	 * @param int $order
1146
+	 * @return void
1147
+	 * @throws \EE_Error
1148
+	 */
1149 1149
 	public function set_order( $order ) {
1150 1150
 		$this->set( 'TKT_order', $order );
1151 1151
 	}
1152 1152
 
1153 1153
 
1154 1154
 
1155
-    /**
1156
-     * Gets row
1157
-     *
1158
-     * @return int
1159
-     * @throws \EE_Error
1160
-     */
1155
+	/**
1156
+	 * Gets row
1157
+	 *
1158
+	 * @return int
1159
+	 * @throws \EE_Error
1160
+	 */
1161 1161
 	public function row() {
1162 1162
 		return $this->get( 'TKT_row' );
1163 1163
 	}
1164 1164
 
1165 1165
 
1166 1166
 
1167
-    /**
1168
-     * Sets row
1169
-     *
1170
-     * @param int $row
1171
-     * @return void
1172
-     * @throws \EE_Error
1173
-     */
1167
+	/**
1168
+	 * Sets row
1169
+	 *
1170
+	 * @param int $row
1171
+	 * @return void
1172
+	 * @throws \EE_Error
1173
+	 */
1174 1174
 	public function set_row( $row ) {
1175 1175
 		$this->set( 'TKT_row', $row );
1176 1176
 	}
1177 1177
 
1178 1178
 
1179 1179
 
1180
-    /**
1181
-     * Gets deleted
1182
-     *
1183
-     * @return boolean
1184
-     * @throws \EE_Error
1185
-     */
1180
+	/**
1181
+	 * Gets deleted
1182
+	 *
1183
+	 * @return boolean
1184
+	 * @throws \EE_Error
1185
+	 */
1186 1186
 	public function deleted() {
1187 1187
 		return $this->get( 'TKT_deleted' );
1188 1188
 	}
1189 1189
 
1190 1190
 
1191 1191
 
1192
-    /**
1193
-     * Sets deleted
1194
-     *
1195
-     * @param boolean $deleted
1196
-     * @return void
1197
-     * @throws \EE_Error
1198
-     */
1192
+	/**
1193
+	 * Sets deleted
1194
+	 *
1195
+	 * @param boolean $deleted
1196
+	 * @return void
1197
+	 * @throws \EE_Error
1198
+	 */
1199 1199
 	public function set_deleted( $deleted ) {
1200 1200
 		$this->set( 'TKT_deleted', $deleted );
1201 1201
 	}
1202 1202
 
1203 1203
 
1204 1204
 
1205
-    /**
1206
-     * Gets parent
1207
-     *
1208
-     * @return int
1209
-     * @throws \EE_Error
1210
-     */
1205
+	/**
1206
+	 * Gets parent
1207
+	 *
1208
+	 * @return int
1209
+	 * @throws \EE_Error
1210
+	 */
1211 1211
 	public function parent_ID() {
1212 1212
 		return $this->get( 'TKT_parent' );
1213 1213
 	}
1214 1214
 
1215 1215
 
1216 1216
 
1217
-    /**
1218
-     * Sets parent
1219
-     *
1220
-     * @param int $parent
1221
-     * @return void
1222
-     * @throws \EE_Error
1223
-     */
1217
+	/**
1218
+	 * Sets parent
1219
+	 *
1220
+	 * @param int $parent
1221
+	 * @return void
1222
+	 * @throws \EE_Error
1223
+	 */
1224 1224
 	public function set_parent_ID( $parent ) {
1225 1225
 		$this->set( 'TKT_parent', $parent );
1226 1226
 	}
1227 1227
 
1228 1228
 
1229 1229
 
1230
-    /**
1231
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1232
-     *
1233
-     * @return string
1234
-     * @throws \EE_Error
1235
-     */
1230
+	/**
1231
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1232
+	 *
1233
+	 * @return string
1234
+	 * @throws \EE_Error
1235
+	 */
1236 1236
 	public function name_and_info() {
1237 1237
 		$times = array();
1238 1238
 		foreach ( $this->datetimes() as $datetime ) {
@@ -1243,50 +1243,50 @@  discard block
 block discarded – undo
1243 1243
 
1244 1244
 
1245 1245
 
1246
-    /**
1247
-     * Gets name
1248
-     *
1249
-     * @return string
1250
-     * @throws \EE_Error
1251
-     */
1246
+	/**
1247
+	 * Gets name
1248
+	 *
1249
+	 * @return string
1250
+	 * @throws \EE_Error
1251
+	 */
1252 1252
 	public function name() {
1253 1253
 		return $this->get( 'TKT_name' );
1254 1254
 	}
1255 1255
 
1256 1256
 
1257 1257
 
1258
-    /**
1259
-     * Gets price
1260
-     *
1261
-     * @return float
1262
-     * @throws \EE_Error
1263
-     */
1258
+	/**
1259
+	 * Gets price
1260
+	 *
1261
+	 * @return float
1262
+	 * @throws \EE_Error
1263
+	 */
1264 1264
 	public function price() {
1265 1265
 		return $this->get( 'TKT_price' );
1266 1266
 	}
1267 1267
 
1268 1268
 
1269 1269
 
1270
-    /**
1271
-     * Gets all the registrations for this ticket
1272
-     *
1273
-     * @param array $query_params like EEM_Base::get_all's
1274
-     * @return EE_Registration[]|EE_Base_Class[]
1275
-     * @throws \EE_Error
1276
-     */
1270
+	/**
1271
+	 * Gets all the registrations for this ticket
1272
+	 *
1273
+	 * @param array $query_params like EEM_Base::get_all's
1274
+	 * @return EE_Registration[]|EE_Base_Class[]
1275
+	 * @throws \EE_Error
1276
+	 */
1277 1277
 	public function registrations( $query_params = array() ) {
1278 1278
 		return $this->get_many_related( 'Registration', $query_params );
1279 1279
 	}
1280 1280
 
1281 1281
 
1282 1282
 
1283
-    /**
1284
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1285
-     * into account
1286
-     *
1287
-     * @return int
1288
-     * @throws \EE_Error
1289
-     */
1283
+	/**
1284
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1285
+	 * into account
1286
+	 *
1287
+	 * @return int
1288
+	 * @throws \EE_Error
1289
+	 */
1290 1290
 	public function update_tickets_sold() {
1291 1291
 		$count_regs_for_this_ticket = $this->count_registrations( array( array( 'STS_ID' => EEM_Registration::status_id_approved, 'REG_deleted' => 0 ) ) );
1292 1292
 		$this->set_sold( $count_regs_for_this_ticket );
@@ -1318,21 +1318,21 @@  discard block
 block discarded – undo
1318 1318
 
1319 1319
 
1320 1320
 
1321
-    /**
1322
-     * Implementation of the EEI_Event_Relation interface method
1323
-     *
1324
-     * @see EEI_Event_Relation for comments
1325
-     * @return EE_Event
1326
-     * @throws \EE_Error
1327
-     * @throws UnexpectedEntityException
1328
-     */
1321
+	/**
1322
+	 * Implementation of the EEI_Event_Relation interface method
1323
+	 *
1324
+	 * @see EEI_Event_Relation for comments
1325
+	 * @return EE_Event
1326
+	 * @throws \EE_Error
1327
+	 * @throws UnexpectedEntityException
1328
+	 */
1329 1329
 	public function get_related_event() {
1330 1330
 		//get one datetime to use for getting the event
1331 1331
 		$datetime = $this->first_datetime();
1332 1332
 		if ( ! $datetime instanceof \EE_Datetime ) {
1333 1333
 			throw new UnexpectedEntityException(
1334 1334
 				$datetime,
1335
-                'EE_Datetime',
1335
+				'EE_Datetime',
1336 1336
 				sprintf(
1337 1337
 					__( 'The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1338 1338
 					$this->name()
@@ -1343,7 +1343,7 @@  discard block
 block discarded – undo
1343 1343
 		if ( ! $event instanceof \EE_Event ) {
1344 1344
 			throw new UnexpectedEntityException(
1345 1345
 				$event,
1346
-                'EE_Event',
1346
+				'EE_Event',
1347 1347
 				sprintf(
1348 1348
 					__( 'The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1349 1349
 					$this->name()
@@ -1355,14 +1355,14 @@  discard block
 block discarded – undo
1355 1355
 
1356 1356
 
1357 1357
 
1358
-    /**
1359
-     * Implementation of the EEI_Event_Relation interface method
1360
-     *
1361
-     * @see EEI_Event_Relation for comments
1362
-     * @return string
1363
-     * @throws UnexpectedEntityException
1364
-     * @throws \EE_Error
1365
-     */
1358
+	/**
1359
+	 * Implementation of the EEI_Event_Relation interface method
1360
+	 *
1361
+	 * @see EEI_Event_Relation for comments
1362
+	 * @return string
1363
+	 * @throws UnexpectedEntityException
1364
+	 * @throws \EE_Error
1365
+	 */
1366 1366
 	public function get_event_name() {
1367 1367
 		$event = $this->get_related_event();
1368 1368
 		return $event instanceof EE_Event ? $event->name() : '';
@@ -1370,14 +1370,14 @@  discard block
 block discarded – undo
1370 1370
 
1371 1371
 
1372 1372
 
1373
-    /**
1374
-     * Implementation of the EEI_Event_Relation interface method
1375
-     *
1376
-     * @see EEI_Event_Relation for comments
1377
-     * @return int
1378
-     * @throws UnexpectedEntityException
1379
-     * @throws \EE_Error
1380
-     */
1373
+	/**
1374
+	 * Implementation of the EEI_Event_Relation interface method
1375
+	 *
1376
+	 * @see EEI_Event_Relation for comments
1377
+	 * @return int
1378
+	 * @throws UnexpectedEntityException
1379
+	 * @throws \EE_Error
1380
+	 */
1381 1381
 	public function get_event_ID() {
1382 1382
 		$event = $this->get_related_event();
1383 1383
 		return $event instanceof EE_Event ? $event->ID() : 0;
Please login to merge, or discard this patch.
Spacing   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\exceptions\UnexpectedEntityException;
2 2
 
3
-if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
4
-	exit( 'No direct script access allowed' );
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 /**
7 7
  * Event Espresso
@@ -70,9 +70,9 @@  discard block
 block discarded – undo
70 70
      * @return EE_Ticket
71 71
      * @throws \EE_Error
72 72
      */
73
-	public static function new_instance( $props_n_values = array(), $timezone = null, $date_formats = array() ) {
74
-		$has_object = parent::_check_for_object( $props_n_values, __CLASS__, $timezone, $date_formats );
75
-		return $has_object ? $has_object : new self( $props_n_values, false, $timezone, $date_formats );
73
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array()) {
74
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
75
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
76 76
 	}
77 77
 
78 78
 
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
      * @return EE_Ticket
85 85
      * @throws \EE_Error
86 86
      */
87
-	public static function new_instance_from_db( $props_n_values = array(), $timezone = null ) {
88
-		return new self( $props_n_values, TRUE, $timezone );
87
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null) {
88
+		return new self($props_n_values, TRUE, $timezone);
89 89
 	}
90 90
 
91 91
 
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
      * @throws \EE_Error
96 96
      */
97 97
 	public function parent() {
98
-		return $this->get( 'TKT_parent' );
98
+		return $this->get('TKT_parent');
99 99
 	}
100 100
 
101 101
 
@@ -107,13 +107,13 @@  discard block
 block discarded – undo
107 107
      * @return boolean
108 108
      * @throws \EE_Error
109 109
      */
110
-	public function available( $DTT_ID = 0 ) {
110
+	public function available($DTT_ID = 0) {
111 111
 		// are we checking availability for a particular datetime ?
112
-		if ( $DTT_ID ) {
112
+		if ($DTT_ID) {
113 113
 			// get that datetime object
114
-			$datetime = $this->get_first_related( 'Datetime', array( array( 'DTT_ID' => $DTT_ID ) ) );
114
+			$datetime = $this->get_first_related('Datetime', array(array('DTT_ID' => $DTT_ID)));
115 115
 			// if  ticket sales for this datetime have exceeded the reg limit...
116
-			if ( $datetime instanceof EE_Datetime && $datetime->sold_out() ) {
116
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
117 117
 				return FALSE;
118 118
 			}
119 119
 		}
@@ -131,22 +131,22 @@  discard block
 block discarded – undo
131 131
      * @return mixed status int if the display string isn't requested
132 132
      * @throws \EE_Error
133 133
      */
134
-	public function ticket_status( $display = FALSE, $remaining = null ) {
135
-		$remaining = is_bool( $remaining ) ? $remaining : $this->is_remaining();
136
-		if ( ! $remaining ) {
137
-			return $display ? EEH_Template::pretty_status( EE_Ticket::sold_out, FALSE, 'sentence' ) : EE_Ticket::sold_out;
134
+	public function ticket_status($display = FALSE, $remaining = null) {
135
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
136
+		if ( ! $remaining) {
137
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, FALSE, 'sentence') : EE_Ticket::sold_out;
138 138
 		}
139
-		if ( $this->get( 'TKT_deleted' ) ) {
140
-			return $display ? EEH_Template::pretty_status( EE_Ticket::archived, FALSE, 'sentence' ) : EE_Ticket::archived;
139
+		if ($this->get('TKT_deleted')) {
140
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, FALSE, 'sentence') : EE_Ticket::archived;
141 141
 		}
142
-		if ( $this->is_expired() ) {
143
-			return $display ? EEH_Template::pretty_status( EE_Ticket::expired, FALSE, 'sentence' ) : EE_Ticket::expired;
142
+		if ($this->is_expired()) {
143
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, FALSE, 'sentence') : EE_Ticket::expired;
144 144
 		}
145
-		if ( $this->is_pending() ) {
146
-			return $display ? EEH_Template::pretty_status( EE_Ticket::pending, FALSE, 'sentence' ) : EE_Ticket::pending;
145
+		if ($this->is_pending()) {
146
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, FALSE, 'sentence') : EE_Ticket::pending;
147 147
 		}
148
-		if ( $this->is_on_sale() ) {
149
-			return $display ? EEH_Template::pretty_status( EE_Ticket::onsale, FALSE, 'sentence' ) : EE_Ticket::onsale;
148
+		if ($this->is_on_sale()) {
149
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, FALSE, 'sentence') : EE_Ticket::onsale;
150 150
 		}
151 151
 		return '';
152 152
 	}
@@ -161,12 +161,12 @@  discard block
 block discarded – undo
161 161
      * @return boolean         true = tickets remaining, false not.
162 162
      * @throws \EE_Error
163 163
      */
164
-	public function is_remaining( $DTT_ID = 0 ) {
165
-		$num_remaining = $this->remaining( $DTT_ID );
166
-		if ( $num_remaining === 0 ) {
164
+	public function is_remaining($DTT_ID = 0) {
165
+		$num_remaining = $this->remaining($DTT_ID);
166
+		if ($num_remaining === 0) {
167 167
 			return FALSE;
168 168
 		}
169
-		if ( $num_remaining > 0 && $num_remaining < $this->min() ) {
169
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
170 170
 			return FALSE;
171 171
 		}
172 172
 		return TRUE;
@@ -182,8 +182,8 @@  discard block
 block discarded – undo
182 182
      * @return int
183 183
      * @throws \EE_Error
184 184
      */
185
-	public function remaining( $DTT_ID = 0 ) {
186
-		return $this->real_quantity_on_ticket('saleable', $DTT_ID );
185
+	public function remaining($DTT_ID = 0) {
186
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
187 187
 	}
188 188
 
189 189
 
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
      * @throws \EE_Error
196 196
      */
197 197
 	public function min() {
198
-		return $this->get( 'TKT_min' );
198
+		return $this->get('TKT_min');
199 199
 	}
200 200
 
201 201
 
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
      * @throws \EE_Error
208 208
      */
209 209
 	public function is_expired() {
210
-		return ( $this->get_raw( 'TKT_end_date' ) < time() );
210
+		return ($this->get_raw('TKT_end_date') < time());
211 211
 	}
212 212
 
213 213
 
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
      * @throws \EE_Error
220 220
      */
221 221
 	public function is_pending() {
222
-		return ( $this->get_raw( 'TKT_start_date' ) > time() );
222
+		return ($this->get_raw('TKT_start_date') > time());
223 223
 	}
224 224
 
225 225
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      * @throws \EE_Error
232 232
      */
233 233
 	public function is_on_sale() {
234
-		return ( $this->get_raw( 'TKT_start_date' ) < time() && $this->get_raw( 'TKT_end_date' ) > time() );
234
+		return ($this->get_raw('TKT_start_date') < time() && $this->get_raw('TKT_end_date') > time());
235 235
 	}
236 236
 
237 237
 
@@ -244,11 +244,11 @@  discard block
 block discarded – undo
244 244
      * @return string
245 245
      * @throws \EE_Error
246 246
      */
247
-	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
248
-		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date( $dt_frmt ) : '';
249
-		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date( $dt_frmt ) : '';
247
+	public function date_range($dt_frmt = '', $conjunction = ' - ') {
248
+		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date($dt_frmt) : '';
249
+		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date($dt_frmt) : '';
250 250
 
251
-		return $first_date && $last_date ? $first_date . $conjunction  . $last_date : '';
251
+		return $first_date && $last_date ? $first_date.$conjunction.$last_date : '';
252 252
 	}
253 253
 
254 254
 
@@ -260,8 +260,8 @@  discard block
 block discarded – undo
260 260
      * @throws \EE_Error
261 261
      */
262 262
 	public function first_datetime() {
263
-		$datetimes = $this->datetimes( array( 'limit' => 1 ) );
264
-		return reset( $datetimes );
263
+		$datetimes = $this->datetimes(array('limit' => 1));
264
+		return reset($datetimes);
265 265
 	}
266 266
 
267 267
 
@@ -274,11 +274,11 @@  discard block
 block discarded – undo
274 274
      * @return EE_Datetime[]|EE_Base_Class[]
275 275
      * @throws \EE_Error
276 276
      */
277
-	public function datetimes( $query_params = array() ) {
278
-		if ( ! isset( $query_params[ 'order_by' ] ) ) {
279
-			$query_params[ 'order_by' ][ 'DTT_order' ] = 'ASC';
277
+	public function datetimes($query_params = array()) {
278
+		if ( ! isset($query_params['order_by'])) {
279
+			$query_params['order_by']['DTT_order'] = 'ASC';
280 280
 		}
281
-		return $this->get_many_related( 'Datetime', $query_params );
281
+		return $this->get_many_related('Datetime', $query_params);
282 282
 	}
283 283
 
284 284
 
@@ -290,8 +290,8 @@  discard block
 block discarded – undo
290 290
      * @throws \EE_Error
291 291
      */
292 292
 	public function last_datetime() {
293
-		$datetimes = $this->datetimes( array( 'limit' => 1, 'order_by' => array( 'DTT_EVT_start' => 'DESC' ) ) );
294
-		return end( $datetimes );
293
+		$datetimes = $this->datetimes(array('limit' => 1, 'order_by' => array('DTT_EVT_start' => 'DESC')));
294
+		return end($datetimes);
295 295
 	}
296 296
 
297 297
 
@@ -309,22 +309,22 @@  discard block
 block discarded – undo
309 309
      * @return mixed (array|int)          how many tickets have sold
310 310
      * @throws \EE_Error
311 311
      */
312
-	public function tickets_sold( $what = 'ticket', $dtt_id = NULL ) {
312
+	public function tickets_sold($what = 'ticket', $dtt_id = NULL) {
313 313
 		$total = 0;
314 314
 		$tickets_sold = $this->_all_tickets_sold();
315
-		switch ( $what ) {
315
+		switch ($what) {
316 316
 			case 'ticket' :
317
-				return $tickets_sold[ 'ticket' ];
317
+				return $tickets_sold['ticket'];
318 318
 				break;
319 319
 			case 'datetime' :
320
-				if ( empty( $tickets_sold[ 'datetime' ] ) ) {
320
+				if (empty($tickets_sold['datetime'])) {
321 321
 					return $total;
322 322
 				}
323
-				if ( ! empty( $dtt_id ) && ! isset( $tickets_sold[ 'datetime' ][ $dtt_id ] ) ) {
324
-					EE_Error::add_error( __( 'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?', 'event_espresso' ), __FILE__, __FUNCTION__, __LINE__ );
323
+				if ( ! empty($dtt_id) && ! isset($tickets_sold['datetime'][$dtt_id])) {
324
+					EE_Error::add_error(__('You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
325 325
 					return $total;
326 326
 				}
327
-				return empty( $dtt_id ) ? $tickets_sold[ 'datetime' ] : $tickets_sold[ 'datetime' ][ $dtt_id ];
327
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][$dtt_id];
328 328
 				break;
329 329
 			default:
330 330
 				return $total;
@@ -340,15 +340,15 @@  discard block
 block discarded – undo
340 340
      * @throws \EE_Error
341 341
      */
342 342
 	protected function _all_tickets_sold() {
343
-		$datetimes = $this->get_many_related( 'Datetime' );
343
+		$datetimes = $this->get_many_related('Datetime');
344 344
 		$tickets_sold = array();
345
-		if ( ! empty( $datetimes ) ) {
346
-			foreach ( $datetimes as $datetime ) {
347
-				$tickets_sold[ 'datetime' ][ $datetime->ID() ] = $datetime->get( 'DTT_sold' );
345
+		if ( ! empty($datetimes)) {
346
+			foreach ($datetimes as $datetime) {
347
+				$tickets_sold['datetime'][$datetime->ID()] = $datetime->get('DTT_sold');
348 348
 			}
349 349
 		}
350 350
 		//Tickets sold
351
-		$tickets_sold[ 'ticket' ] = $this->sold();
351
+		$tickets_sold['ticket'] = $this->sold();
352 352
 		return $tickets_sold;
353 353
 	}
354 354
 
@@ -361,11 +361,11 @@  discard block
 block discarded – undo
361 361
      * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
362 362
      * @throws \EE_Error
363 363
      */
364
-	public function base_price( $return_array = FALSE ) {
365
-		$_where = array( 'Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price );
364
+	public function base_price($return_array = FALSE) {
365
+		$_where = array('Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price);
366 366
 		return $return_array
367
-            ? $this->get_many_related( 'Price', array( $_where ) )
368
-            : $this->get_first_related( 'Price', array( $_where ) );
367
+            ? $this->get_many_related('Price', array($_where))
368
+            : $this->get_first_related('Price', array($_where));
369 369
 	}
370 370
 
371 371
 
@@ -378,8 +378,8 @@  discard block
 block discarded – undo
378 378
      * @throws \EE_Error
379 379
      */
380 380
 	public function price_modifiers() {
381
-		$query_params = array( 0 => array( 'Price_Type.PBT_ID' => array( 'NOT IN', array( EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax ) ) ) );
382
-		return $this->prices( $query_params );
381
+		$query_params = array(0 => array('Price_Type.PBT_ID' => array('NOT IN', array(EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax))));
382
+		return $this->prices($query_params);
383 383
 	}
384 384
 
385 385
 
@@ -391,8 +391,8 @@  discard block
 block discarded – undo
391 391
      * @return EE_Price[]|EE_Base_Class[]
392 392
      * @throws \EE_Error
393 393
      */
394
-	public function prices( $query_params = array() ) {
395
-		return $this->get_many_related( 'Price', $query_params );
394
+	public function prices($query_params = array()) {
395
+		return $this->get_many_related('Price', $query_params);
396 396
 	}
397 397
 
398 398
 
@@ -404,8 +404,8 @@  discard block
 block discarded – undo
404 404
      * @return EE_Datetime_Ticket|EE_Base_Class[]
405 405
      * @throws \EE_Error
406 406
      */
407
-	public function datetime_tickets( $query_params = array() ) {
408
-		return $this->get_many_related( 'Datetime_Ticket', $query_params );
407
+	public function datetime_tickets($query_params = array()) {
408
+		return $this->get_many_related('Datetime_Ticket', $query_params);
409 409
 	}
410 410
 
411 411
 
@@ -418,8 +418,8 @@  discard block
 block discarded – undo
418 418
      * @return EE_Datetime[]
419 419
      * @throws \EE_Error
420 420
      */
421
-	public function datetimes_ordered( $show_expired = TRUE, $show_deleted = FALSE ) {
422
-		return EEM_Datetime::instance( $this->_timezone )->get_datetimes_for_ticket_ordered_by_DTT_order( $this->ID(), $show_expired, $show_deleted );
421
+	public function datetimes_ordered($show_expired = TRUE, $show_deleted = FALSE) {
422
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order($this->ID(), $show_expired, $show_deleted);
423 423
 	}
424 424
 
425 425
 
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
      * @throws \EE_Error
432 432
      */
433 433
 	public function ID() {
434
-		return $this->get( 'TKT_ID' );
434
+		return $this->get('TKT_ID');
435 435
 	}
436 436
 
437 437
 
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
      * @throws \EE_Error
457 457
      */
458 458
 	public function template() {
459
-		return $this->get_first_related( 'Ticket_Template' );
459
+		return $this->get_first_related('Ticket_Template');
460 460
 	}
461 461
 
462 462
 
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
      * @throws \EE_Error
479 479
      */
480 480
 	public function ticket_price() {
481
-		return $this->get( 'TKT_price' );
481
+		return $this->get('TKT_price');
482 482
 	}
483 483
 
484 484
 
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
      * @throws \EE_Error
489 489
      */
490 490
 	public function pretty_price() {
491
-		return $this->get_pretty( 'TKT_price' );
491
+		return $this->get_pretty('TKT_price');
492 492
 	}
493 493
 
494 494
 
@@ -510,8 +510,8 @@  discard block
 block discarded – undo
510 510
      * @return float
511 511
      * @throws \EE_Error
512 512
      */
513
-	public function get_ticket_total_with_taxes( $no_cache = FALSE ) {
514
-		if ($this->_ticket_total_with_taxes === null || $no_cache ) {
513
+	public function get_ticket_total_with_taxes($no_cache = FALSE) {
514
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
515 515
 			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
516 516
 		}
517 517
 		return (float) $this->_ticket_total_with_taxes;
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
 
521 521
 
522 522
 	public function ensure_TKT_Price_correct() {
523
-		$this->set( 'TKT_price', EE_Taxes::get_subtotal_for_admin( $this ) );
523
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
524 524
 		$this->save();
525 525
 	}
526 526
 
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
      * @throws \EE_Error
532 532
      */
533 533
 	public function get_ticket_subtotal() {
534
-		return EE_Taxes::get_subtotal_for_admin( $this );
534
+		return EE_Taxes::get_subtotal_for_admin($this);
535 535
 	}
536 536
 
537 537
 
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
      * @throws \EE_Error
544 544
      */
545 545
 	public function get_ticket_taxes_total_for_admin() {
546
-		return EE_Taxes::get_total_taxes_for_admin( $this );
546
+		return EE_Taxes::get_total_taxes_for_admin($this);
547 547
 	}
548 548
 
549 549
 
@@ -554,8 +554,8 @@  discard block
 block discarded – undo
554 554
      * @param string $name
555 555
      * @throws \EE_Error
556 556
      */
557
-	public function set_name( $name ) {
558
-		$this->set( 'TKT_name', $name );
557
+	public function set_name($name) {
558
+		$this->set('TKT_name', $name);
559 559
 	}
560 560
 
561 561
 
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
      * @throws \EE_Error
568 568
      */
569 569
 	public function description() {
570
-		return $this->get( 'TKT_description' );
570
+		return $this->get('TKT_description');
571 571
 	}
572 572
 
573 573
 
@@ -578,8 +578,8 @@  discard block
 block discarded – undo
578 578
      * @param string $description
579 579
      * @throws \EE_Error
580 580
      */
581
-	public function set_description( $description ) {
582
-		$this->set( 'TKT_description', $description );
581
+	public function set_description($description) {
582
+		$this->set('TKT_description', $description);
583 583
 	}
584 584
 
585 585
 
@@ -592,8 +592,8 @@  discard block
 block discarded – undo
592 592
      * @return string
593 593
      * @throws \EE_Error
594 594
      */
595
-	public function start_date( $dt_frmt = '', $tm_frmt = '' ) {
596
-		return $this->_get_datetime( 'TKT_start_date', $dt_frmt, $tm_frmt );
595
+	public function start_date($dt_frmt = '', $tm_frmt = '') {
596
+		return $this->_get_datetime('TKT_start_date', $dt_frmt, $tm_frmt);
597 597
 	}
598 598
 
599 599
 
@@ -605,8 +605,8 @@  discard block
 block discarded – undo
605 605
      * @return void
606 606
      * @throws \EE_Error
607 607
      */
608
-	public function set_start_date( $start_date ) {
609
-		$this->_set_date_time( 'B', $start_date, 'TKT_start_date' );
608
+	public function set_start_date($start_date) {
609
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
610 610
 	}
611 611
 
612 612
 
@@ -619,8 +619,8 @@  discard block
 block discarded – undo
619 619
      * @return string
620 620
      * @throws \EE_Error
621 621
      */
622
-	public function end_date( $dt_frmt = '', $tm_frmt = '' ) {
623
-		return $this->_get_datetime( 'TKT_end_date', $dt_frmt, $tm_frmt );
622
+	public function end_date($dt_frmt = '', $tm_frmt = '') {
623
+		return $this->_get_datetime('TKT_end_date', $dt_frmt, $tm_frmt);
624 624
 	}
625 625
 
626 626
 
@@ -632,8 +632,8 @@  discard block
 block discarded – undo
632 632
      * @return void
633 633
      * @throws \EE_Error
634 634
      */
635
-	public function set_end_date( $end_date ) {
636
-		$this->_set_date_time( 'B', $end_date, 'TKT_end_date' );
635
+	public function set_end_date($end_date) {
636
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
637 637
 	}
638 638
 
639 639
 
@@ -645,8 +645,8 @@  discard block
 block discarded – undo
645 645
      * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
646 646
      * @throws \EE_Error
647 647
      */
648
-	public function set_end_time( $time ) {
649
-		$this->_set_time_for( $time, 'TKT_end_date' );
648
+	public function set_end_time($time) {
649
+		$this->_set_time_for($time, 'TKT_end_date');
650 650
 	}
651 651
 
652 652
 
@@ -658,8 +658,8 @@  discard block
 block discarded – undo
658 658
      * @return void
659 659
      * @throws \EE_Error
660 660
      */
661
-	public function set_min( $min ) {
662
-		$this->set( 'TKT_min', $min );
661
+	public function set_min($min) {
662
+		$this->set('TKT_min', $min);
663 663
 	}
664 664
 
665 665
 
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
      * @throws \EE_Error
672 672
      */
673 673
 	public function max() {
674
-		return $this->get( 'TKT_max' );
674
+		return $this->get('TKT_max');
675 675
 	}
676 676
 
677 677
 
@@ -683,8 +683,8 @@  discard block
 block discarded – undo
683 683
      * @return void
684 684
      * @throws \EE_Error
685 685
      */
686
-	public function set_max( $max ) {
687
-		$this->set( 'TKT_max', $max );
686
+	public function set_max($max) {
687
+		$this->set('TKT_max', $max);
688 688
 	}
689 689
 
690 690
 
@@ -696,8 +696,8 @@  discard block
 block discarded – undo
696 696
      * @return void
697 697
      * @throws \EE_Error
698 698
      */
699
-	public function set_price( $price ) {
700
-		$this->set( 'TKT_price', $price );
699
+	public function set_price($price) {
700
+		$this->set('TKT_price', $price);
701 701
 	}
702 702
 
703 703
 
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
      * @throws \EE_Error
710 710
      */
711 711
 	public function sold() {
712
-		return $this->get_raw( 'TKT_sold' );
712
+		return $this->get_raw('TKT_sold');
713 713
 	}
714 714
 
715 715
 
@@ -721,10 +721,10 @@  discard block
 block discarded – undo
721 721
      * @return void
722 722
      * @throws \EE_Error
723 723
      */
724
-	public function set_sold( $sold ) {
724
+	public function set_sold($sold) {
725 725
 		// sold can not go below zero
726
-		$sold = max( 0, $sold );
727
-		$this->set( 'TKT_sold', $sold );
726
+		$sold = max(0, $sold);
727
+		$this->set('TKT_sold', $sold);
728 728
 	}
729 729
 
730 730
 
@@ -736,13 +736,13 @@  discard block
 block discarded – undo
736 736
      * @return void
737 737
      * @throws \EE_Error
738 738
      */
739
-	public function increase_sold( $qty = 1 ) {
739
+	public function increase_sold($qty = 1) {
740 740
 		$sold = $this->sold() + $qty;
741 741
 		// remove ticket reservation, but don't adjust datetime reservations,  because that will happen
742 742
 		// via \EE_Datetime::increase_sold() when \EE_Ticket::_increase_sold_for_datetimes() is called
743
-		$this->decrease_reserved( $qty, false );
744
-		$this->_increase_sold_for_datetimes( $qty );
745
-		$this->set_sold( $sold );
743
+		$this->decrease_reserved($qty, false);
744
+		$this->_increase_sold_for_datetimes($qty);
745
+		$this->set_sold($sold);
746 746
 	}
747 747
 
748 748
 
@@ -754,12 +754,12 @@  discard block
 block discarded – undo
754 754
      * @return void
755 755
      * @throws \EE_Error
756 756
      */
757
-	protected function _increase_sold_for_datetimes( $qty = 1 ) {
757
+	protected function _increase_sold_for_datetimes($qty = 1) {
758 758
 		$datetimes = $this->datetimes();
759
-		if ( is_array( $datetimes ) ) {
760
-			foreach ( $datetimes as $datetime ) {
761
-				if ( $datetime instanceof EE_Datetime ) {
762
-					$datetime->increase_sold( $qty );
759
+		if (is_array($datetimes)) {
760
+			foreach ($datetimes as $datetime) {
761
+				if ($datetime instanceof EE_Datetime) {
762
+					$datetime->increase_sold($qty);
763 763
 					$datetime->save();
764 764
 				}
765 765
 			}
@@ -775,10 +775,10 @@  discard block
 block discarded – undo
775 775
      * @return void
776 776
      * @throws \EE_Error
777 777
      */
778
-	public function decrease_sold( $qty = 1 ) {
778
+	public function decrease_sold($qty = 1) {
779 779
 		$sold = $this->sold() - $qty;
780
-		$this->_decrease_sold_for_datetimes( $qty );
781
-		$this->set_sold( $sold );
780
+		$this->_decrease_sold_for_datetimes($qty);
781
+		$this->set_sold($sold);
782 782
 	}
783 783
 
784 784
 
@@ -790,12 +790,12 @@  discard block
 block discarded – undo
790 790
      * @return void
791 791
      * @throws \EE_Error
792 792
      */
793
-	protected function _decrease_sold_for_datetimes( $qty = 1 ) {
793
+	protected function _decrease_sold_for_datetimes($qty = 1) {
794 794
 		$datetimes = $this->datetimes();
795
-		if ( is_array( $datetimes ) ) {
796
-			foreach ( $datetimes as $datetime ) {
797
-				if ( $datetime instanceof EE_Datetime ) {
798
-					$datetime->decrease_sold( $qty );
795
+		if (is_array($datetimes)) {
796
+			foreach ($datetimes as $datetime) {
797
+				if ($datetime instanceof EE_Datetime) {
798
+					$datetime->decrease_sold($qty);
799 799
 					$datetime->save();
800 800
 				}
801 801
 			}
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
      * @throws \EE_Error
812 812
      */
813 813
 	public function reserved() {
814
-		return $this->get_raw( 'TKT_reserved' );
814
+		return $this->get_raw('TKT_reserved');
815 815
 	}
816 816
 
817 817
 
@@ -823,10 +823,10 @@  discard block
 block discarded – undo
823 823
      * @return void
824 824
      * @throws \EE_Error
825 825
      */
826
-	public function set_reserved( $reserved ) {
826
+	public function set_reserved($reserved) {
827 827
 		// reserved can not go below zero
828
-		$reserved = max( 0, (int) $reserved );
829
-		$this->set( 'TKT_reserved', $reserved );
828
+		$reserved = max(0, (int) $reserved);
829
+		$this->set('TKT_reserved', $reserved);
830 830
 	}
831 831
 
832 832
 
@@ -838,11 +838,11 @@  discard block
 block discarded – undo
838 838
      * @return void
839 839
      * @throws \EE_Error
840 840
      */
841
-	public function increase_reserved( $qty = 1 ) {
842
-		$qty = absint( $qty );
841
+	public function increase_reserved($qty = 1) {
842
+		$qty = absint($qty);
843 843
 		$reserved = $this->reserved() + $qty;
844
-		$this->_increase_reserved_for_datetimes( $qty );
845
-		$this->set_reserved( $reserved );
844
+		$this->_increase_reserved_for_datetimes($qty);
845
+		$this->set_reserved($reserved);
846 846
 	}
847 847
 
848 848
 
@@ -854,12 +854,12 @@  discard block
 block discarded – undo
854 854
      * @return void
855 855
      * @throws \EE_Error
856 856
      */
857
-	protected function _increase_reserved_for_datetimes( $qty = 1 ) {
857
+	protected function _increase_reserved_for_datetimes($qty = 1) {
858 858
 		$datetimes = $this->datetimes();
859
-		if ( is_array( $datetimes ) ) {
860
-			foreach ( $datetimes as $datetime ) {
861
-				if ( $datetime instanceof EE_Datetime ) {
862
-					$datetime->increase_reserved( $qty );
859
+		if (is_array($datetimes)) {
860
+			foreach ($datetimes as $datetime) {
861
+				if ($datetime instanceof EE_Datetime) {
862
+					$datetime->increase_reserved($qty);
863 863
 					$datetime->save();
864 864
 				}
865 865
 			}
@@ -876,12 +876,12 @@  discard block
 block discarded – undo
876 876
      * @return void
877 877
      * @throws \EE_Error
878 878
      */
879
-	public function decrease_reserved( $qty = 1, $adjust_datetimes = true ) {
880
-		$reserved = $this->reserved() - absint( $qty );
881
-		if ( $adjust_datetimes ) {
882
-			$this->_decrease_reserved_for_datetimes( $qty );
879
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true) {
880
+		$reserved = $this->reserved() - absint($qty);
881
+		if ($adjust_datetimes) {
882
+			$this->_decrease_reserved_for_datetimes($qty);
883 883
 		}
884
-		$this->set_reserved( $reserved );
884
+		$this->set_reserved($reserved);
885 885
 	}
886 886
 
887 887
 
@@ -893,12 +893,12 @@  discard block
 block discarded – undo
893 893
      * @return void
894 894
      * @throws \EE_Error
895 895
      */
896
-	protected function _decrease_reserved_for_datetimes( $qty = 1 ) {
896
+	protected function _decrease_reserved_for_datetimes($qty = 1) {
897 897
 		$datetimes = $this->datetimes();
898
-		if ( is_array( $datetimes ) ) {
899
-			foreach ( $datetimes as $datetime ) {
900
-				if ( $datetime instanceof EE_Datetime ) {
901
-					$datetime->decrease_reserved( $qty );
898
+		if (is_array($datetimes)) {
899
+			foreach ($datetimes as $datetime) {
900
+				if ($datetime instanceof EE_Datetime) {
901
+					$datetime->decrease_reserved($qty);
902 902
 					$datetime->save();
903 903
 				}
904 904
 			}
@@ -919,14 +919,14 @@  discard block
 block discarded – undo
919 919
      * @return int
920 920
      * @throws \EE_Error
921 921
      */
922
-	public function qty( $context = '' ) {
923
-		switch ( $context ) {
922
+	public function qty($context = '') {
923
+		switch ($context) {
924 924
 			case 'reg_limit' :
925 925
 				return $this->real_quantity_on_ticket();
926 926
 			case 'saleable' :
927
-				return $this->real_quantity_on_ticket( 'saleable' );
927
+				return $this->real_quantity_on_ticket('saleable');
928 928
 			default:
929
-				return $this->get_raw( 'TKT_qty' );
929
+				return $this->get_raw('TKT_qty');
930 930
 		}
931 931
 	}
932 932
 
@@ -945,15 +945,15 @@  discard block
 block discarded – undo
945 945
      * @return int
946 946
      * @throws \EE_Error
947 947
      */
948
-	public function real_quantity_on_ticket( $context = 'reg_limit', $DTT_ID = 0 ) {
949
-		$raw = $this->get_raw( 'TKT_qty' );
948
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0) {
949
+		$raw = $this->get_raw('TKT_qty');
950 950
 		// return immediately if it's zero
951
-		if ( $raw === 0 ) {
951
+		if ($raw === 0) {
952 952
 			return $raw;
953 953
 		}
954 954
 		//echo "\n\n<br />Ticket: " . $this->name() . '<br />';
955 955
 		// ensure qty doesn't exceed raw value for THIS ticket
956
-		$qty = min( EE_INF, $raw );
956
+		$qty = min(EE_INF, $raw);
957 957
 		//echo "\n . qty: " . $qty . '<br />';
958 958
 		// calculate this ticket's total sales and reservations
959 959
 		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
@@ -962,23 +962,23 @@  discard block
 block discarded – undo
962 962
 		//echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
963 963
 		// first we need to calculate the maximum number of tickets available for the datetime
964 964
 		// do we want data for one datetime or all of them ?
965
-		$query_params = $DTT_ID ? array( array( 'DTT_ID' => $DTT_ID ) ) : array();
966
-		$datetimes = $this->datetimes( $query_params );
967
-		if ( is_array( $datetimes ) && ! empty( $datetimes ) ) {
968
-			foreach ( $datetimes as $datetime ) {
969
-				if ( $datetime instanceof EE_Datetime ) {
965
+		$query_params = $DTT_ID ? array(array('DTT_ID' => $DTT_ID)) : array();
966
+		$datetimes = $this->datetimes($query_params);
967
+		if (is_array($datetimes) && ! empty($datetimes)) {
968
+			foreach ($datetimes as $datetime) {
969
+				if ($datetime instanceof EE_Datetime) {
970 970
 					$datetime->refresh_from_db();
971 971
 					//echo "\n . . datetime name: " . $datetime->name() . '<br />';
972 972
 					//echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
973 973
 					// initialize with no restrictions for each datetime
974 974
 					// but adjust datetime qty based on datetime reg limit
975
-					$datetime_qty = min( EE_INF, $datetime->reg_limit() );
975
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
976 976
 					//echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
977 977
 					//echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
978 978
 					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
979 979
 					// and reservations for this datetime, that do NOT include sales and reservations
980 980
 					// for this ticket (so we add $this->sold() and $this->reserved() back in)
981
-					if ( $context === 'saleable' ) {
981
+					if ($context === 'saleable') {
982 982
 						$datetime_qty = max(
983 983
 							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
984 984
 							0
@@ -990,16 +990,16 @@  discard block
 block discarded – undo
990 990
 						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
991 991
 						//echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
992 992
 					}
993
-					$qty = min( $datetime_qty, $qty );
993
+					$qty = min($datetime_qty, $qty);
994 994
 					//echo "\n . . qty: " . $qty . '<br />';
995 995
 				}
996 996
 			}
997 997
 		}
998 998
 		// NOW that we know the  maximum number of tickets available for the datetime
999 999
 		// we can finally factor in the details for this specific ticket
1000
-		if ( $qty > 0 && $context === 'saleable' ) {
1000
+		if ($qty > 0 && $context === 'saleable') {
1001 1001
 			// and subtract the sales for THIS ticket
1002
-			$qty = max( $qty - $sold_and_reserved_for_this_ticket, 0 );
1002
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1003 1003
 			//echo "\n . qty: " . $qty . '<br />';
1004 1004
 		}
1005 1005
 		//echo "\nFINAL QTY: " . $qty . "<br /><br />";
@@ -1015,14 +1015,14 @@  discard block
 block discarded – undo
1015 1015
 	 * @return void
1016 1016
 	 * @throws \EE_Error
1017 1017
 	 */
1018
-	public function set_qty( $qty ) {
1018
+	public function set_qty($qty) {
1019 1019
 		$datetimes = $this->datetimes();
1020
-		foreach ( $datetimes as $datetime ) {
1021
-			if ( $datetime instanceof EE_Datetime ) {
1022
-				$qty = min( $qty, $datetime->reg_limit() );
1020
+		foreach ($datetimes as $datetime) {
1021
+			if ($datetime instanceof EE_Datetime) {
1022
+				$qty = min($qty, $datetime->reg_limit());
1023 1023
 			}
1024 1024
 		}
1025
-		$this->set( 'TKT_qty', $qty );
1025
+		$this->set('TKT_qty', $qty);
1026 1026
 	}
1027 1027
 
1028 1028
 
@@ -1034,7 +1034,7 @@  discard block
 block discarded – undo
1034 1034
      * @throws \EE_Error
1035 1035
      */
1036 1036
 	public function uses() {
1037
-		return $this->get( 'TKT_uses' );
1037
+		return $this->get('TKT_uses');
1038 1038
 	}
1039 1039
 
1040 1040
 
@@ -1046,8 +1046,8 @@  discard block
 block discarded – undo
1046 1046
      * @return void
1047 1047
      * @throws \EE_Error
1048 1048
      */
1049
-	public function set_uses( $uses ) {
1050
-		$this->set( 'TKT_uses', $uses );
1049
+	public function set_uses($uses) {
1050
+		$this->set('TKT_uses', $uses);
1051 1051
 	}
1052 1052
 
1053 1053
 
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
      * @throws \EE_Error
1060 1060
      */
1061 1061
 	public function required() {
1062
-		return $this->get( 'TKT_required' );
1062
+		return $this->get('TKT_required');
1063 1063
 	}
1064 1064
 
1065 1065
 
@@ -1071,8 +1071,8 @@  discard block
 block discarded – undo
1071 1071
      * @return void
1072 1072
      * @throws \EE_Error
1073 1073
      */
1074
-	public function set_required( $required ) {
1075
-		$this->set( 'TKT_required', $required );
1074
+	public function set_required($required) {
1075
+		$this->set('TKT_required', $required);
1076 1076
 	}
1077 1077
 
1078 1078
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      * @throws \EE_Error
1085 1085
      */
1086 1086
 	public function taxable() {
1087
-		return $this->get( 'TKT_taxable' );
1087
+		return $this->get('TKT_taxable');
1088 1088
 	}
1089 1089
 
1090 1090
 
@@ -1096,8 +1096,8 @@  discard block
 block discarded – undo
1096 1096
      * @return void
1097 1097
      * @throws \EE_Error
1098 1098
      */
1099
-	public function set_taxable( $taxable ) {
1100
-		$this->set( 'TKT_taxable', $taxable );
1099
+	public function set_taxable($taxable) {
1100
+		$this->set('TKT_taxable', $taxable);
1101 1101
 	}
1102 1102
 
1103 1103
 
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
      * @throws \EE_Error
1110 1110
      */
1111 1111
 	public function is_default() {
1112
-		return $this->get( 'TKT_is_default' );
1112
+		return $this->get('TKT_is_default');
1113 1113
 	}
1114 1114
 
1115 1115
 
@@ -1121,8 +1121,8 @@  discard block
 block discarded – undo
1121 1121
      * @return void
1122 1122
      * @throws \EE_Error
1123 1123
      */
1124
-	public function set_is_default( $is_default ) {
1125
-		$this->set( 'TKT_is_default', $is_default );
1124
+	public function set_is_default($is_default) {
1125
+		$this->set('TKT_is_default', $is_default);
1126 1126
 	}
1127 1127
 
1128 1128
 
@@ -1134,7 +1134,7 @@  discard block
 block discarded – undo
1134 1134
      * @throws \EE_Error
1135 1135
      */
1136 1136
 	public function order() {
1137
-		return $this->get( 'TKT_order' );
1137
+		return $this->get('TKT_order');
1138 1138
 	}
1139 1139
 
1140 1140
 
@@ -1146,8 +1146,8 @@  discard block
 block discarded – undo
1146 1146
      * @return void
1147 1147
      * @throws \EE_Error
1148 1148
      */
1149
-	public function set_order( $order ) {
1150
-		$this->set( 'TKT_order', $order );
1149
+	public function set_order($order) {
1150
+		$this->set('TKT_order', $order);
1151 1151
 	}
1152 1152
 
1153 1153
 
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
      * @throws \EE_Error
1160 1160
      */
1161 1161
 	public function row() {
1162
-		return $this->get( 'TKT_row' );
1162
+		return $this->get('TKT_row');
1163 1163
 	}
1164 1164
 
1165 1165
 
@@ -1171,8 +1171,8 @@  discard block
 block discarded – undo
1171 1171
      * @return void
1172 1172
      * @throws \EE_Error
1173 1173
      */
1174
-	public function set_row( $row ) {
1175
-		$this->set( 'TKT_row', $row );
1174
+	public function set_row($row) {
1175
+		$this->set('TKT_row', $row);
1176 1176
 	}
1177 1177
 
1178 1178
 
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
      * @throws \EE_Error
1185 1185
      */
1186 1186
 	public function deleted() {
1187
-		return $this->get( 'TKT_deleted' );
1187
+		return $this->get('TKT_deleted');
1188 1188
 	}
1189 1189
 
1190 1190
 
@@ -1196,8 +1196,8 @@  discard block
 block discarded – undo
1196 1196
      * @return void
1197 1197
      * @throws \EE_Error
1198 1198
      */
1199
-	public function set_deleted( $deleted ) {
1200
-		$this->set( 'TKT_deleted', $deleted );
1199
+	public function set_deleted($deleted) {
1200
+		$this->set('TKT_deleted', $deleted);
1201 1201
 	}
1202 1202
 
1203 1203
 
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
      * @throws \EE_Error
1210 1210
      */
1211 1211
 	public function parent_ID() {
1212
-		return $this->get( 'TKT_parent' );
1212
+		return $this->get('TKT_parent');
1213 1213
 	}
1214 1214
 
1215 1215
 
@@ -1221,8 +1221,8 @@  discard block
 block discarded – undo
1221 1221
      * @return void
1222 1222
      * @throws \EE_Error
1223 1223
      */
1224
-	public function set_parent_ID( $parent ) {
1225
-		$this->set( 'TKT_parent', $parent );
1224
+	public function set_parent_ID($parent) {
1225
+		$this->set('TKT_parent', $parent);
1226 1226
 	}
1227 1227
 
1228 1228
 
@@ -1235,10 +1235,10 @@  discard block
 block discarded – undo
1235 1235
      */
1236 1236
 	public function name_and_info() {
1237 1237
 		$times = array();
1238
-		foreach ( $this->datetimes() as $datetime ) {
1238
+		foreach ($this->datetimes() as $datetime) {
1239 1239
 			$times[] = $datetime->start_date_and_time();
1240 1240
 		}
1241
-		return $this->name() . ' @ ' . implode( ', ', $times ) . ' for ' . $this->pretty_price();
1241
+		return $this->name().' @ '.implode(', ', $times).' for '.$this->pretty_price();
1242 1242
 	}
1243 1243
 
1244 1244
 
@@ -1250,7 +1250,7 @@  discard block
 block discarded – undo
1250 1250
      * @throws \EE_Error
1251 1251
      */
1252 1252
 	public function name() {
1253
-		return $this->get( 'TKT_name' );
1253
+		return $this->get('TKT_name');
1254 1254
 	}
1255 1255
 
1256 1256
 
@@ -1262,7 +1262,7 @@  discard block
 block discarded – undo
1262 1262
      * @throws \EE_Error
1263 1263
      */
1264 1264
 	public function price() {
1265
-		return $this->get( 'TKT_price' );
1265
+		return $this->get('TKT_price');
1266 1266
 	}
1267 1267
 
1268 1268
 
@@ -1274,8 +1274,8 @@  discard block
 block discarded – undo
1274 1274
      * @return EE_Registration[]|EE_Base_Class[]
1275 1275
      * @throws \EE_Error
1276 1276
      */
1277
-	public function registrations( $query_params = array() ) {
1278
-		return $this->get_many_related( 'Registration', $query_params );
1277
+	public function registrations($query_params = array()) {
1278
+		return $this->get_many_related('Registration', $query_params);
1279 1279
 	}
1280 1280
 
1281 1281
 
@@ -1288,8 +1288,8 @@  discard block
 block discarded – undo
1288 1288
      * @throws \EE_Error
1289 1289
      */
1290 1290
 	public function update_tickets_sold() {
1291
-		$count_regs_for_this_ticket = $this->count_registrations( array( array( 'STS_ID' => EEM_Registration::status_id_approved, 'REG_deleted' => 0 ) ) );
1292
-		$this->set_sold( $count_regs_for_this_ticket );
1291
+		$count_regs_for_this_ticket = $this->count_registrations(array(array('STS_ID' => EEM_Registration::status_id_approved, 'REG_deleted' => 0)));
1292
+		$this->set_sold($count_regs_for_this_ticket);
1293 1293
 		$this->save();
1294 1294
 		return $count_regs_for_this_ticket;
1295 1295
 	}
@@ -1301,7 +1301,7 @@  discard block
 block discarded – undo
1301 1301
 	 * @param array $query_params like EEM_Base::get_all's
1302 1302
 	 * @return int
1303 1303
 	 */
1304
-	public function count_registrations( $query_params = array() ) {
1304
+	public function count_registrations($query_params = array()) {
1305 1305
 		return $this->count_related('Registration', $query_params);
1306 1306
 	}
1307 1307
 
@@ -1329,23 +1329,23 @@  discard block
 block discarded – undo
1329 1329
 	public function get_related_event() {
1330 1330
 		//get one datetime to use for getting the event
1331 1331
 		$datetime = $this->first_datetime();
1332
-		if ( ! $datetime instanceof \EE_Datetime ) {
1332
+		if ( ! $datetime instanceof \EE_Datetime) {
1333 1333
 			throw new UnexpectedEntityException(
1334 1334
 				$datetime,
1335 1335
                 'EE_Datetime',
1336 1336
 				sprintf(
1337
-					__( 'The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1337
+					__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1338 1338
 					$this->name()
1339 1339
 				)
1340 1340
 			);
1341 1341
 		}
1342 1342
 		$event = $datetime->event();
1343
-		if ( ! $event instanceof \EE_Event ) {
1343
+		if ( ! $event instanceof \EE_Event) {
1344 1344
 			throw new UnexpectedEntityException(
1345 1345
 				$event,
1346 1346
                 'EE_Event',
1347 1347
 				sprintf(
1348
-					__( 'The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1348
+					__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1349 1349
 					$this->name()
1350 1350
 				)
1351 1351
 			);
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 2 patches
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 
359 359
 
360 360
 
361
-    /**
362
-     * get event start date.  Provide either the date format, or NULL to re-use the
363
-     * last-used format, or '' to use the default date format
364
-     *
365
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
-     * @return        mixed        string on success, FALSE on fail
367
-     */
361
+	/**
362
+	 * get event start date.  Provide either the date format, or NULL to re-use the
363
+	 * last-used format, or '' to use the default date format
364
+	 *
365
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
+	 * @return        mixed        string on success, FALSE on fail
367
+	 */
368 368
 	public function start_date( $dt_frmt = '' ) {
369 369
 		return $this->_show_datetime( 'D', 'start', $dt_frmt );
370 370
 	}
@@ -381,13 +381,13 @@  discard block
 block discarded – undo
381 381
 
382 382
 
383 383
 
384
-    /**
385
-     * get end date. Provide either the date format, or NULL to re-use the
386
-     * last-used format, or '' to use the default date format
387
-     *
388
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
-     * @return        mixed        string on success, FALSE on fail
390
-     */
384
+	/**
385
+	 * get end date. Provide either the date format, or NULL to re-use the
386
+	 * last-used format, or '' to use the default date format
387
+	 *
388
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
+	 * @return        mixed        string on success, FALSE on fail
390
+	 */
391 391
 	public function end_date( $dt_frmt = '' ) {
392 392
 		return $this->_show_datetime( 'D', 'end', $dt_frmt );
393 393
 	}
@@ -509,23 +509,23 @@  discard block
 block discarded – undo
509 509
 	/**
510 510
 	 * This returns a range representation of the date and times.
511 511
 	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
512
-     * Also, the return value is localized.
513
-     *
514
-     * @param string $dt_format
512
+	 * Also, the return value is localized.
513
+	 *
514
+	 * @param string $dt_format
515 515
 	 * @param string $tm_format
516 516
 	 * @param string $conjunction used between two different dates or times.
517
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
-     * @param string $separator   used between the date and time formats.
519
-     *                            ex: Dec 1, 2016{$separator}2pm
517
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
+	 * @param string $separator   used between the date and time formats.
519
+	 *                            ex: Dec 1, 2016{$separator}2pm
520 520
 	 * @return string
521 521
 	 * @throws \EE_Error
522 522
 	 */
523 523
 	public function date_and_time_range(
524
-	    $dt_format = '',
525
-        $tm_format = '',
526
-        $conjunction = ' - ' ,
527
-        $separator = ' '
528
-    ) {
524
+		$dt_format = '',
525
+		$tm_format = '',
526
+		$conjunction = ' - ' ,
527
+		$separator = ' '
528
+	) {
529 529
 		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530 530
 		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531 531
 		$full_format = $dt_format . $separator . $tm_format;
@@ -539,14 +539,14 @@  discard block
 block discarded – undo
539 539
 			//start and end date are the same but times are different
540 540
 			case ( $this->start_date() === $this->end_date() ) :
541 541
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
542
-				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
542
+						  . $conjunction
543
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547 547
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
548
-				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
548
+						  . $conjunction
549
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -630,13 +630,13 @@  discard block
 block discarded – undo
630 630
 
631 631
 
632 632
 	/**
633
-     *        get end date and time
634
-     *
635
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
-     * @return    mixed                string on success, FALSE on fail
638
-     */
639
-    public function end_date_and_time($dt_frmt = '', $tm_format = '') {
633
+	 *        get end date and time
634
+	 *
635
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
+	 * @return    mixed                string on success, FALSE on fail
638
+	 */
639
+	public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640 640
 		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
641 641
 	}
642 642
 
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -74,9 +74,9 @@  discard block
 block discarded – undo
74 74
 	 *                             		    date_format and the second value is the time format
75 75
 	 * @return EE_Datetime
76 76
 	 */
77
-	public static function new_instance( $props_n_values = array(), $timezone = null, $date_formats = array() ) {
78
-		$has_object = parent::_check_for_object( $props_n_values, __CLASS__, $timezone, $date_formats );
79
-		return $has_object ? $has_object : new self( $props_n_values, false, $timezone, $date_formats );
77
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array()) {
78
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
79
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
80 80
 	}
81 81
 
82 82
 
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 	 *                          		the website will be used.
88 88
 	 * @return EE_Datetime
89 89
 	 */
90
-	public static function new_instance_from_db( $props_n_values = array(), $timezone = null ) {
91
-		return new self( $props_n_values, TRUE, $timezone );
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null) {
91
+		return new self($props_n_values, TRUE, $timezone);
92 92
 	}
93 93
 
94 94
 
@@ -96,8 +96,8 @@  discard block
 block discarded – undo
96 96
 	/**
97 97
 	 * @param $name
98 98
 	 */
99
-	public function set_name( $name ) {
100
-		$this->set( 'DTT_name', $name );
99
+	public function set_name($name) {
100
+		$this->set('DTT_name', $name);
101 101
 	}
102 102
 
103 103
 
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 	/**
106 106
 	 * @param $description
107 107
 	 */
108
-	public function set_description( $description ) {
109
-		$this->set( 'DTT_description', $description );
108
+	public function set_description($description) {
109
+		$this->set('DTT_description', $description);
110 110
 	}
111 111
 
112 112
 
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 	 *
119 119
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
120 120
 	 */
121
-	public function set_start_date( $date ) {
122
-		$this->_set_date_for( $date, 'DTT_EVT_start' );
121
+	public function set_start_date($date) {
122
+		$this->_set_date_for($date, 'DTT_EVT_start');
123 123
 	}
124 124
 
125 125
 
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
 	 *
132 132
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
133 133
 	 */
134
-	public function set_start_time( $time ) {
135
-		$this->_set_time_for( $time, 'DTT_EVT_start' );
134
+	public function set_start_time($time) {
135
+		$this->_set_time_for($time, 'DTT_EVT_start');
136 136
 	}
137 137
 
138 138
 
@@ -144,8 +144,8 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
146 146
 	 */
147
-	public function set_end_date( $date ) {
148
-		$this->_set_date_for( $date, 'DTT_EVT_end' );
147
+	public function set_end_date($date) {
148
+		$this->_set_date_for($date, 'DTT_EVT_end');
149 149
 	}
150 150
 
151 151
 
@@ -157,8 +157,8 @@  discard block
 block discarded – undo
157 157
 	 *
158 158
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
159 159
 	 */
160
-	public function set_end_time( $time ) {
161
-		$this->_set_time_for( $time, 'DTT_EVT_end' );
160
+	public function set_end_time($time) {
161
+		$this->_set_time_for($time, 'DTT_EVT_end');
162 162
 	}
163 163
 
164 164
 
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 	 *
171 171
 	 * @param        int $reg_limit
172 172
 	 */
173
-	public function set_reg_limit( $reg_limit ) {
174
-		$this->set( 'DTT_reg_limit', $reg_limit );
173
+	public function set_reg_limit($reg_limit) {
174
+		$this->set('DTT_reg_limit', $reg_limit);
175 175
 	}
176 176
 
177 177
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	 * @return        mixed        int on success, FALSE on fail
184 184
 	 */
185 185
 	public function sold() {
186
-		return $this->get_raw( 'DTT_sold' );
186
+		return $this->get_raw('DTT_sold');
187 187
 	}
188 188
 
189 189
 
@@ -193,10 +193,10 @@  discard block
 block discarded – undo
193 193
 	 *
194 194
 	 * @param        int $sold
195 195
 	 */
196
-	public function set_sold( $sold ) {
196
+	public function set_sold($sold) {
197 197
 		// sold can not go below zero
198
-		$sold = max( 0, $sold );
199
-		$this->set( 'DTT_sold', $sold );
198
+		$sold = max(0, $sold);
199
+		$this->set('DTT_sold', $sold);
200 200
 	}
201 201
 
202 202
 
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
 	 * increments sold by amount passed by $qty
206 206
 	 * @param int $qty
207 207
 	 */
208
-	public function increase_sold( $qty = 1 ) {
208
+	public function increase_sold($qty = 1) {
209 209
 		$sold = $this->sold() + $qty;
210 210
 		// remove ticket reservation
211
-		$this->decrease_reserved( $qty );
212
-		$this->set_sold( $sold );
211
+		$this->decrease_reserved($qty);
212
+		$this->set_sold($sold);
213 213
 	}
214 214
 
215 215
 
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 	 * decrements (subtracts) sold amount passed by $qty
219 219
 	 * @param int $qty
220 220
 	 */
221
-	public function decrease_sold( $qty = 1 ) {
221
+	public function decrease_sold($qty = 1) {
222 222
 		$sold = $this->sold() - $qty;
223
-		$this->set_sold( $sold );
223
+		$this->set_sold($sold);
224 224
 	}
225 225
 
226 226
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 	 * @return int
232 232
 	 */
233 233
 	public function reserved() {
234
-		return $this->get_raw( 'DTT_reserved' );
234
+		return $this->get_raw('DTT_reserved');
235 235
 	}
236 236
 
237 237
 
@@ -241,10 +241,10 @@  discard block
 block discarded – undo
241 241
 	 *
242 242
 	 * @param int $reserved
243 243
 	 */
244
-	public function set_reserved( $reserved ) {
244
+	public function set_reserved($reserved) {
245 245
 		// reserved can not go below zero
246
-		$reserved = max( 0, (int) $reserved );
247
-		$this->set( 'DTT_reserved', $reserved );
246
+		$reserved = max(0, (int) $reserved);
247
+		$this->set('DTT_reserved', $reserved);
248 248
 	}
249 249
 
250 250
 
@@ -255,9 +255,9 @@  discard block
 block discarded – undo
255 255
 	 * @param int $qty
256 256
 	 * @return boolean
257 257
 	 */
258
-	public function increase_reserved( $qty = 1 ) {
259
-		$reserved = $this->reserved() + absint( $qty );
260
-		return $this->set_reserved( $reserved );
258
+	public function increase_reserved($qty = 1) {
259
+		$reserved = $this->reserved() + absint($qty);
260
+		return $this->set_reserved($reserved);
261 261
 	}
262 262
 
263 263
 
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
 	 * @param int $qty
269 269
 	 * @return boolean
270 270
 	 */
271
-	public function decrease_reserved( $qty = 1 ) {
272
-		$reserved = $this->reserved() - absint( $qty );
273
-		return $this->set_reserved( $reserved );
271
+	public function decrease_reserved($qty = 1) {
272
+		$reserved = $this->reserved() - absint($qty);
273
+		return $this->set_reserved($reserved);
274 274
 	}
275 275
 
276 276
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 	 * @return string
292 292
 	 */
293 293
 	public function name() {
294
-		return $this->get( 'DTT_name' );
294
+		return $this->get('DTT_name');
295 295
 	}
296 296
 
297 297
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @return string
302 302
 	 */
303 303
 	public function description() {
304
-		return $this->get( 'DTT_description' );
304
+		return $this->get('DTT_description');
305 305
 	}
306 306
 
307 307
 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	 * @return boolean          TRUE if is primary, FALSE if not.
312 312
 	 */
313 313
 	public function is_primary() {
314
-		return $this->get( 'DTT_is_primary' );
314
+		return $this->get('DTT_is_primary');
315 315
 	}
316 316
 
317 317
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 	 * @return int         The order of the datetime for this event.
322 322
 	 */
323 323
 	public function order() {
324
-		return $this->get( 'DTT_order' );
324
+		return $this->get('DTT_order');
325 325
 	}
326 326
 
327 327
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 	 * @return int
332 332
 	 */
333 333
 	public function parent() {
334
-		return $this->get( 'DTT_parent' );
334
+		return $this->get('DTT_parent');
335 335
 	}
336 336
 
337 337
 
@@ -347,10 +347,10 @@  discard block
 block discarded – undo
347 347
 	 * @param    bool   $echo         - whether we echo or return (note echoing uses "pretty" formats, otherwise we use the standard formats)
348 348
 	 * @return    string|bool  string on success, FALSE on fail
349 349
 	 */
350
-	private function _show_datetime( $date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE ) {
350
+	private function _show_datetime($date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE) {
351 351
 		$field_name = "DTT_EVT_{$start_or_end}";
352
-		$dtt = $this->_get_datetime( $field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo );
353
-		if ( ! $echo ) {
352
+		$dtt = $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo);
353
+		if ( ! $echo) {
354 354
 			return $dtt;
355 355
 		}
356 356
 		return '';
@@ -365,8 +365,8 @@  discard block
 block discarded – undo
365 365
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366 366
      * @return        mixed        string on success, FALSE on fail
367 367
      */
368
-	public function start_date( $dt_frmt = '' ) {
369
-		return $this->_show_datetime( 'D', 'start', $dt_frmt );
368
+	public function start_date($dt_frmt = '') {
369
+		return $this->_show_datetime('D', 'start', $dt_frmt);
370 370
 	}
371 371
 
372 372
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * Echoes start_date()
376 376
 	 * @param string $dt_frmt
377 377
 	 */
378
-	public function e_start_date( $dt_frmt = '' ) {
379
-		$this->_show_datetime( 'D', 'start', $dt_frmt, NULL, TRUE );
378
+	public function e_start_date($dt_frmt = '') {
379
+		$this->_show_datetime('D', 'start', $dt_frmt, NULL, TRUE);
380 380
 	}
381 381
 
382 382
 
@@ -388,8 +388,8 @@  discard block
 block discarded – undo
388 388
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389 389
      * @return        mixed        string on success, FALSE on fail
390 390
      */
391
-	public function end_date( $dt_frmt = '' ) {
392
-		return $this->_show_datetime( 'D', 'end', $dt_frmt );
391
+	public function end_date($dt_frmt = '') {
392
+		return $this->_show_datetime('D', 'end', $dt_frmt);
393 393
 	}
394 394
 
395 395
 
@@ -398,8 +398,8 @@  discard block
 block discarded – undo
398 398
 	 * Echoes the end date. See end_date()
399 399
 	 * @param string $dt_frmt
400 400
 	 */
401
-	public function e_end_date( $dt_frmt = '' ) {
402
-		$this->_show_datetime( 'D', 'end', $dt_frmt, NULL, TRUE );
401
+	public function e_end_date($dt_frmt = '') {
402
+		$this->_show_datetime('D', 'end', $dt_frmt, NULL, TRUE);
403 403
 	}
404 404
 
405 405
 
@@ -414,11 +414,11 @@  discard block
 block discarded – undo
414 414
 	 * @return mixed        string on success, FALSE on fail
415 415
 	 * @throws \EE_Error
416 416
 	 */
417
-	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
418
-		$dt_frmt = ! empty( $dt_frmt ) ? $dt_frmt : $this->_dt_frmt;
419
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $dt_frmt ) );
420
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end', $dt_frmt ) );
421
-		return $start !== $end ? $start . $conjunction . $end : $start;
417
+	public function date_range($dt_frmt = '', $conjunction = ' - ') {
418
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
419
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt));
420
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt));
421
+		return $start !== $end ? $start.$conjunction.$end : $start;
422 422
 	}
423 423
 
424 424
 
@@ -428,8 +428,8 @@  discard block
 block discarded – undo
428 428
 	 * @param string $conjunction
429 429
 	 * @throws \EE_Error
430 430
 	 */
431
-	public function e_date_range( $dt_frmt = '', $conjunction = ' - ' ) {
432
-		echo $this->date_range( $dt_frmt, $conjunction );
431
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ') {
432
+		echo $this->date_range($dt_frmt, $conjunction);
433 433
 	}
434 434
 
435 435
 
@@ -440,8 +440,8 @@  discard block
 block discarded – undo
440 440
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
441 441
 	 * @return mixed        string on success, FALSE on fail
442 442
 	 */
443
-	public function start_time( $tm_format = '' ) {
444
-		return $this->_show_datetime( 'T', 'start', NULL, $tm_format );
443
+	public function start_time($tm_format = '') {
444
+		return $this->_show_datetime('T', 'start', NULL, $tm_format);
445 445
 	}
446 446
 
447 447
 
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
 	/**
450 450
 	 * @param string $tm_format
451 451
 	 */
452
-	public function e_start_time( $tm_format = '' ) {
453
-		$this->_show_datetime( 'T', 'start', NULL, $tm_format, TRUE );
452
+	public function e_start_time($tm_format = '') {
453
+		$this->_show_datetime('T', 'start', NULL, $tm_format, TRUE);
454 454
 	}
455 455
 
456 456
 
@@ -461,8 +461,8 @@  discard block
 block discarded – undo
461 461
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
462 462
 	 * @return mixed        string on success, FALSE on fail
463 463
 	 */
464
-	public function end_time( $tm_format = '' ) {
465
-		return $this->_show_datetime( 'T', 'end', NULL, $tm_format );
464
+	public function end_time($tm_format = '') {
465
+		return $this->_show_datetime('T', 'end', NULL, $tm_format);
466 466
 	}
467 467
 
468 468
 
@@ -470,8 +470,8 @@  discard block
 block discarded – undo
470 470
 	/**
471 471
 	 * @param string $tm_format
472 472
 	 */
473
-	public function e_end_time( $tm_format = '' ) {
474
-		$this->_show_datetime( 'T', 'end', NULL, $tm_format, TRUE );
473
+	public function e_end_time($tm_format = '') {
474
+		$this->_show_datetime('T', 'end', NULL, $tm_format, TRUE);
475 475
 	}
476 476
 
477 477
 
@@ -486,11 +486,11 @@  discard block
 block discarded – undo
486 486
 	 * @return mixed              string on success, FALSE on fail
487 487
 	 * @throws \EE_Error
488 488
 	 */
489
-	public function time_range( $tm_format = '', $conjunction = ' - ' ) {
490
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
491
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $tm_format ) );
492
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end',  $tm_format ) );
493
-		return $start !== $end ? $start . $conjunction . $end : $start;
489
+	public function time_range($tm_format = '', $conjunction = ' - ') {
490
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
491
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $tm_format));
492
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $tm_format));
493
+		return $start !== $end ? $start.$conjunction.$end : $start;
494 494
 	}
495 495
 
496 496
 
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param string $conjunction
501 501
 	 * @throws \EE_Error
502 502
 	 */
503
-	public function e_time_range( $tm_format = '', $conjunction = ' - ' ) {
504
-		echo $this->time_range( $tm_format, $conjunction );
503
+	public function e_time_range($tm_format = '', $conjunction = ' - ') {
504
+		echo $this->time_range($tm_format, $conjunction);
505 505
 	}
506 506
 
507 507
 
@@ -523,30 +523,30 @@  discard block
 block discarded – undo
523 523
 	public function date_and_time_range(
524 524
 	    $dt_format = '',
525 525
         $tm_format = '',
526
-        $conjunction = ' - ' ,
526
+        $conjunction = ' - ',
527 527
         $separator = ' '
528 528
     ) {
529
-		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531
-		$full_format = $dt_format . $separator . $tm_format;
529
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
530
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
531
+		$full_format = $dt_format.$separator.$tm_format;
532 532
 
533 533
 		//the range output depends on various conditions
534
-		switch ( true ) {
534
+		switch (true) {
535 535
 			//start date timestamp and end date timestamp are the same.
536
-			case ( $this->get_raw( 'DTT_EVT_start' ) === $this->get_raw( 'DTT_EVT_end' ) ) :
537
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format );
536
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')) :
537
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
538 538
 				break;
539 539
 			//start and end date are the same but times are different
540
-			case ( $this->start_date() === $this->end_date() ) :
541
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
540
+			case ($this->start_date() === $this->end_date()) :
541
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
542 542
 				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
543
+				          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
547
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
548 548
 				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
549
+				          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -564,8 +564,8 @@  discard block
 block discarded – undo
564 564
 	 * @return void
565 565
 	 * @throws \EE_Error
566 566
 	 */
567
-	public function e_date_and_time_range( $dt_format = '', $tm_format = '', $conjunction = ' - ' ) {
568
-		echo $this->date_and_time_range( $dt_format, $tm_format, $conjunction );
567
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ') {
568
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
569 569
 	}
570 570
 
571 571
 
@@ -577,8 +577,8 @@  discard block
 block discarded – undo
577 577
 	 * @param 	string 	$tm_format - string representation of time format defaults to 'g:i a'
578 578
 	 * @return 	mixed 	string on success, FALSE on fail
579 579
 	 */
580
-	public function start_date_and_time( $dt_format = '', $tm_format = '' ) {
581
-		return $this->_show_datetime( '', 'start', $dt_format, $tm_format );
580
+	public function start_date_and_time($dt_format = '', $tm_format = '') {
581
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
582 582
 	}
583 583
 
584 584
 
@@ -587,8 +587,8 @@  discard block
 block discarded – undo
587 587
 	 * @param string $dt_frmt
588 588
 	 * @param string $tm_format
589 589
 	 */
590
-	public function e_start_date_and_time( $dt_frmt = '', $tm_format = '' ) {
591
-		$this->_show_datetime( '', 'start', $dt_frmt, $tm_format, TRUE );
590
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '') {
591
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, TRUE);
592 592
 	}
593 593
 
594 594
 
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
 	 * @param bool   $round_up
603 603
 	 * @return float|int|mixed
604 604
 	 */
605
-	public function length( $units = 'seconds', $round_up = FALSE ) {
606
-		$start = $this->get_raw( 'DTT_EVT_start' );
607
-		$end = $this->get_raw( 'DTT_EVT_end' );
605
+	public function length($units = 'seconds', $round_up = FALSE) {
606
+		$start = $this->get_raw('DTT_EVT_start');
607
+		$end = $this->get_raw('DTT_EVT_end');
608 608
 		$length_in_units = $end - $start;
609
-		switch ( $units ) {
609
+		switch ($units) {
610 610
 			//NOTE: We purposefully don't use "break;" in order to chain the divisions
611 611
 			/** @noinspection PhpMissingBreakStatementInspection */
612 612
 			case 'days':
@@ -619,10 +619,10 @@  discard block
 block discarded – undo
619 619
 				$length_in_units /= 60;
620 620
 			case 'seconds':
621 621
 			default:
622
-				$length_in_units = ceil( $length_in_units );
622
+				$length_in_units = ceil($length_in_units);
623 623
 		}
624
-		if ( $round_up ) {
625
-			$length_in_units = max( $length_in_units, 1 );
624
+		if ($round_up) {
625
+			$length_in_units = max($length_in_units, 1);
626 626
 		}
627 627
 		return $length_in_units;
628 628
 	}
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
      * @return    mixed                string on success, FALSE on fail
638 638
      */
639 639
     public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640
-		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
640
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
641 641
 	}
642 642
 
643 643
 
@@ -646,8 +646,8 @@  discard block
 block discarded – undo
646 646
 	 * @param string $dt_frmt
647 647
 	 * @param string $tm_format
648 648
 	 */
649
-	public function e_end_date_and_time( $dt_frmt = '', $tm_format = '' ) {
650
-		$this->_show_datetime( '', 'end', $dt_frmt, $tm_format, TRUE );
649
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '') {
650
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, TRUE);
651 651
 	}
652 652
 
653 653
 
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 	 * @return        int
659 659
 	 */
660 660
 	public function start() {
661
-		return $this->get_raw( 'DTT_EVT_start' );
661
+		return $this->get_raw('DTT_EVT_start');
662 662
 	}
663 663
 
664 664
 
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 	 * @return        int
670 670
 	 */
671 671
 	public function end() {
672
-		return $this->get_raw( 'DTT_EVT_end' );
672
+		return $this->get_raw('DTT_EVT_end');
673 673
 	}
674 674
 
675 675
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 	 * @return        mixed        int on success, FALSE on fail
681 681
 	 */
682 682
 	public function reg_limit() {
683
-		return $this->get_raw( 'DTT_reg_limit' );
683
+		return $this->get_raw('DTT_reg_limit');
684 684
 	}
685 685
 
686 686
 
@@ -708,15 +708,15 @@  discard block
 block discarded – undo
708 708
 	 * 																	the spaces remaining for this particular datetime, hence the flag.
709 709
 	 * @return 	int
710 710
 	 */
711
-	public function spaces_remaining( $consider_tickets = FALSE ) {
711
+	public function spaces_remaining($consider_tickets = FALSE) {
712 712
 		// tickets remaining available for purchase
713 713
 		//no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
714 714
 		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
715
-		if ( ! $consider_tickets ) {
715
+		if ( ! $consider_tickets) {
716 716
 			return $dtt_remaining;
717 717
 		}
718 718
 		$tickets_remaining = $this->tickets_remaining();
719
-		return min( $dtt_remaining, $tickets_remaining );
719
+		return min($dtt_remaining, $tickets_remaining);
720 720
 	}
721 721
 
722 722
 
@@ -727,19 +727,19 @@  discard block
 block discarded – undo
727 727
 	 * @param array $query_params like EEM_Base::get_all's
728 728
 	 * @return int
729 729
 	 */
730
-	public function tickets_remaining( $query_params = array() ) {
730
+	public function tickets_remaining($query_params = array()) {
731 731
 		$sum = 0;
732
-		$tickets = $this->tickets( $query_params );
733
-		if ( ! empty( $tickets ) ) {
734
-			foreach ( $tickets as $ticket ) {
735
-				if ( $ticket instanceof EE_Ticket ) {
732
+		$tickets = $this->tickets($query_params);
733
+		if ( ! empty($tickets)) {
734
+			foreach ($tickets as $ticket) {
735
+				if ($ticket instanceof EE_Ticket) {
736 736
 					// get the actual amount of tickets that can be sold
737
-					$qty = $ticket->qty( 'saleable' );
738
-					if ( $qty === EE_INF ) {
737
+					$qty = $ticket->qty('saleable');
738
+					if ($qty === EE_INF) {
739 739
 						return EE_INF;
740 740
 					}
741 741
 					// no negative ticket quantities plz
742
-					if ( $qty > 0 ) {
742
+					if ($qty > 0) {
743 743
 						$sum += $qty;
744 744
 					}
745 745
 				}
@@ -756,8 +756,8 @@  discard block
 block discarded – undo
756 756
 	 * @param array $query_params like EEM_Base::get_all's
757 757
 	 * @return int
758 758
 	 */
759
-	public function sum_tickets_initially_available( $query_params = array() ) {
760
-		return $this->sum_related( 'Ticket', $query_params, 'TKT_qty' );
759
+	public function sum_tickets_initially_available($query_params = array()) {
760
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
761 761
 	}
762 762
 
763 763
 
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
 	 * @return int
770 770
 	 */
771 771
 	public function total_tickets_available_at_this_datetime() {
772
-		return $this->spaces_remaining( true );
772
+		return $this->spaces_remaining(true);
773 773
 	}
774 774
 
775 775
 
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 	 * @return boolean
781 781
 	 */
782 782
 	public function is_upcoming() {
783
-		return ( $this->get_raw( 'DTT_EVT_start' ) > time() );
783
+		return ($this->get_raw('DTT_EVT_start') > time());
784 784
 	}
785 785
 
786 786
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
 	 * @return boolean
791 791
 	 */
792 792
 	public function is_active() {
793
-		return ( $this->get_raw( 'DTT_EVT_start' ) < time() && $this->get_raw( 'DTT_EVT_end' ) > time() );
793
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
794 794
 	}
795 795
 
796 796
 
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 	 * @return boolean
801 801
 	 */
802 802
 	public function is_expired() {
803
-		return ( $this->get_raw( 'DTT_EVT_end' ) < time() );
803
+		return ($this->get_raw('DTT_EVT_end') < time());
804 804
 	}
805 805
 
806 806
 
@@ -811,16 +811,16 @@  discard block
 block discarded – undo
811 811
 	 */
812 812
 	public function get_active_status() {
813 813
 		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
814
-		if ( $total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1 ) {
814
+		if ($total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1) {
815 815
 			return EE_Datetime::sold_out;
816 816
 		}
817
-		if ( $this->is_expired() ) {
817
+		if ($this->is_expired()) {
818 818
 			return EE_Datetime::expired;
819 819
 		}
820
-		if ( $this->is_upcoming() ) {
820
+		if ($this->is_upcoming()) {
821 821
 			return EE_Datetime::upcoming;
822 822
 		}
823
-		if ( $this->is_active() ) {
823
+		if ($this->is_active()) {
824 824
 			return EE_Datetime::active;
825 825
 		}
826 826
 		return NULL;
@@ -834,24 +834,24 @@  discard block
 block discarded – undo
834 834
 	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
835 835
 	 * @return string
836 836
 	 */
837
-	public function get_dtt_display_name( $use_dtt_name = FALSE ) {
838
-		if ( $use_dtt_name ) {
837
+	public function get_dtt_display_name($use_dtt_name = FALSE) {
838
+		if ($use_dtt_name) {
839 839
 			$dtt_name = $this->name();
840
-			if ( !empty( $dtt_name ) ) {
840
+			if ( ! empty($dtt_name)) {
841 841
 				return $dtt_name;
842 842
 			}
843 843
 		}
844 844
 		//first condition is to see if the months are different
845
-		if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) ) {
846
-			$display_date = $this->start_date( 'M j\, Y g:i a' ) . ' - ' . $this->end_date( 'M j\, Y g:i a' );
845
+		if (date('m', $this->get_raw('DTT_EVT_start')) != date('m', $this->get_raw('DTT_EVT_end'))) {
846
+			$display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
847 847
 			//next condition is if its the same month but different day
848 848
 		}
849 849
 		else {
850
-			if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) == date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) && date( 'd', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'd', $this->get_raw( 'DTT_EVT_end' ) ) ) {
851
-				$display_date = $this->start_date( 'M j\, g:i a' ) . ' - ' . $this->end_date( 'M j\, g:i a Y' );
850
+			if (date('m', $this->get_raw('DTT_EVT_start')) == date('m', $this->get_raw('DTT_EVT_end')) && date('d', $this->get_raw('DTT_EVT_start')) != date('d', $this->get_raw('DTT_EVT_end'))) {
851
+				$display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
852 852
 			}
853 853
 			else {
854
-				$display_date = $this->start_date( 'F j\, Y' ) . ' @ ' . $this->start_date( 'g:i a' ) . ' - ' . $this->end_date( 'g:i a' );
854
+				$display_date = $this->start_date('F j\, Y').' @ '.$this->start_date('g:i a').' - '.$this->end_date('g:i a');
855 855
 			}
856 856
 		}
857 857
 		return $display_date;
@@ -865,8 +865,8 @@  discard block
 block discarded – undo
865 865
 *@param array $query_params see EEM_Base::get_all()
866 866
 	 * @return EE_Ticket[]
867 867
 	 */
868
-	public function tickets( $query_params = array() ) {
869
-		return $this->get_many_related( 'Ticket', $query_params );
868
+	public function tickets($query_params = array()) {
869
+		return $this->get_many_related('Ticket', $query_params);
870 870
 	}
871 871
 
872 872
 
@@ -876,21 +876,21 @@  discard block
 block discarded – undo
876 876
 	 * @param array $query_params like EEM_Base::get_all's
877 877
 	 * @return EE_Ticket[]
878 878
 	 */
879
-	public function ticket_types_available_for_purchase( $query_params = array() ) {
879
+	public function ticket_types_available_for_purchase($query_params = array()) {
880 880
 		// first check if datetime is valid
881
-		if ( ! ( $this->is_upcoming() || $this->is_active() ) || $this->sold_out() ) {
881
+		if ( ! ($this->is_upcoming() || $this->is_active()) || $this->sold_out()) {
882 882
 			return array();
883 883
 		}
884
-		if ( empty( $query_params ) ) {
884
+		if (empty($query_params)) {
885 885
 			$query_params = array(
886 886
 				array(
887
-					'TKT_start_date' => array( '<=', EEM_Ticket::instance()->current_time_for_query( 'TKT_start_date' ) ),
888
-					'TKT_end_date'   => array( '>=', EEM_Ticket::instance()->current_time_for_query( 'TKT_end_date' ) ),
887
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
888
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
889 889
 					'TKT_deleted'    => false
890 890
 				)
891 891
 			);
892 892
 		}
893
-		return $this->tickets( $query_params );
893
+		return $this->tickets($query_params);
894 894
 	}
895 895
 
896 896
 
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 	 * @return EE_Event
901 901
 	 */
902 902
 	public function event() {
903
-		return $this->get_first_related( 'Event' );
903
+		return $this->get_first_related('Event');
904 904
 	}
905 905
 
906 906
 
@@ -912,13 +912,13 @@  discard block
 block discarded – undo
912 912
 	 */
913 913
 	public function update_sold() {
914 914
 		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
915
-			array( array(
915
+			array(array(
916 916
 				'STS_ID' 					=> EEM_Registration::status_id_approved,
917 917
 				'REG_deleted' 				=> 0,
918 918
 				'Ticket.Datetime.DTT_ID' 	=> $this->ID(),
919
-			) )
919
+			))
920 920
 		);
921
-		$this->set( 'DTT_sold', $count_regs_for_this_datetime );
921
+		$this->set('DTT_sold', $count_regs_for_this_datetime);
922 922
 		$this->save();
923 923
 		return $count_regs_for_this_datetime;
924 924
 	}
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +2647 added lines, -2647 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2652 +25,2652 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-
109
-
110
-    /**
111
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
-     * play nice
113
-     *
114
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
-     *                                                         TXN_amount, QST_name, etc) and values are their values
117
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
-     *                                                         corresponding db model or not.
119
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
-     *                                                         be in when instantiating a EE_Base_Class object.
121
-     * @param array   $date_formats                            An array of date formats to set on construct where first
122
-     *                                                         value is the date_format and second value is the time
123
-     *                                                         format.
124
-     * @throws EE_Error
125
-     */
126
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
-    {
128
-        $className = get_class($this);
129
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
-        $model = $this->get_model();
131
-        $model_fields = $model->field_settings(false);
132
-        // ensure $fieldValues is an array
133
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
-        // verify client code has not passed any invalid field names
136
-        foreach ($fieldValues as $field_name => $field_value) {
137
-            if ( ! isset($model_fields[$field_name])) {
138
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
-            }
141
-        }
142
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
-        if ( ! empty($date_formats) && is_array($date_formats)) {
145
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
-        } else {
147
-            //set default formats for date and time
148
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
-        }
151
-        //if db model is instantiating
152
-        if ($bydb) {
153
-            //client code has indicated these field values are from the database
154
-            foreach ($model_fields as $fieldName => $field) {
155
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
-            }
157
-        } else {
158
-            //we're constructing a brand
159
-            //new instance of the model object. Generally, this means we'll need to do more field validation
160
-            foreach ($model_fields as $fieldName => $field) {
161
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
-            }
163
-        }
164
-        //remember what values were passed to this constructor
165
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
166
-        //remember in entity mapper
167
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
-            $model->add_to_entity_map($this);
169
-        }
170
-        //setup all the relations
171
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
-                $this->_model_relations[$relation_name] = null;
174
-            } else {
175
-                $this->_model_relations[$relation_name] = array();
176
-            }
177
-        }
178
-        /**
179
-         * Action done at the end of each model object construction
180
-         *
181
-         * @param EE_Base_Class $this the model object just created
182
-         */
183
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
190
-     *
191
-     * @return boolean
192
-     */
193
-    public function allow_persist()
194
-    {
195
-        return $this->_allow_persist;
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * Sets whether or not this model object should be allowed to be saved to the DB.
202
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
-     * you got new information that somehow made you change your mind.
204
-     *
205
-     * @param boolean $allow_persist
206
-     * @return boolean
207
-     */
208
-    public function set_allow_persist($allow_persist)
209
-    {
210
-        return $this->_allow_persist = $allow_persist;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * Gets the field's original value when this object was constructed during this request.
217
-     * This can be helpful when determining if a model object has changed or not
218
-     *
219
-     * @param string $field_name
220
-     * @return mixed|null
221
-     * @throws \EE_Error
222
-     */
223
-    public function get_original($field_name)
224
-    {
225
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
227
-        ) {
228
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
-        } else {
230
-            return null;
231
-        }
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * @param EE_Base_Class $obj
238
-     * @return string
239
-     */
240
-    public function get_class($obj)
241
-    {
242
-        return get_class($obj);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * Overrides parent because parent expects old models.
249
-     * This also doesn't do any validation, and won't work for serialized arrays
250
-     *
251
-     * @param    string $field_name
252
-     * @param    mixed  $field_value
253
-     * @param bool      $use_default
254
-     * @throws \EE_Error
255
-     */
256
-    public function set($field_name, $field_value, $use_default = false)
257
-    {
258
-        $field_obj = $this->get_model()->field_settings_for($field_name);
259
-        if ($field_obj instanceof EE_Model_Field_Base) {
260
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
261
-            if ($field_obj instanceof EE_Datetime_Field) {
262
-                $field_obj->set_timezone($this->_timezone);
263
-                $field_obj->set_date_format($this->_dt_frmt);
264
-                $field_obj->set_time_format($this->_tm_frmt);
265
-            }
266
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
267
-            //should the value be null?
268
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
-                $this->_fields[$field_name] = $field_obj->get_default_value();
270
-                /**
271
-                 * To save having to refactor all the models, if a default value is used for a
272
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
-                 * object.
275
-                 *
276
-                 * @since 4.6.10+
277
-                 */
278
-                if (
279
-                    $field_obj instanceof EE_Datetime_Field
280
-                    && $this->_fields[$field_name] !== null
281
-                    && ! $this->_fields[$field_name] instanceof DateTime
282
-                ) {
283
-                    empty($this->_fields[$field_name])
284
-                        ? $this->set($field_name, time())
285
-                        : $this->set($field_name, $this->_fields[$field_name]);
286
-                }
287
-            } else {
288
-                $this->_fields[$field_name] = $holder_of_value;
289
-            }
290
-            //if we're not in the constructor...
291
-            //now check if what we set was a primary key
292
-            if (
293
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
-                $this->_props_n_values_provided_in_constructor
295
-                && $field_value
296
-                && $field_name === self::_get_primary_key_name(get_class($this))
297
-            ) {
298
-                //if so, we want all this object's fields to be filled either with
299
-                //what we've explicitly set on this model
300
-                //or what we have in the db
301
-                // echo "setting primary key!";
302
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
303
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
-                foreach ($fields_on_model as $field_obj) {
305
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
-                         && $field_obj->get_name() !== $field_name
307
-                    ) {
308
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
-                    }
310
-                }
311
-                //oh this model object has an ID? well make sure its in the entity mapper
312
-                $this->get_model()->add_to_entity_map($this);
313
-            }
314
-            //let's unset any cache for this field_name from the $_cached_properties property.
315
-            $this->_clear_cached_property($field_name);
316
-        } else {
317
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
-                "event_espresso"), $field_name));
319
-        }
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * This sets the field value on the db column if it exists for the given $column_name or
326
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
-     *
328
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
-     * @param string $field_name  Must be the exact column name.
330
-     * @param mixed  $field_value The value to set.
331
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
-     * @throws \EE_Error
333
-     */
334
-    public function set_field_or_extra_meta($field_name, $field_value)
335
-    {
336
-        if ($this->get_model()->has_field($field_name)) {
337
-            $this->set($field_name, $field_value);
338
-            return true;
339
-        } else {
340
-            //ensure this object is saved first so that extra meta can be properly related.
341
-            $this->save();
342
-            return $this->update_extra_meta($field_name, $field_value);
343
-        }
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * This retrieves the value of the db column set on this class or if that's not present
350
-     * it will attempt to retrieve from extra_meta if found.
351
-     * Example Usage:
352
-     * Via EE_Message child class:
353
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
356
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
-     * value for those extra fields dynamically via the EE_message object.
358
-     *
359
-     * @param  string $field_name expecting the fully qualified field name.
360
-     * @return mixed|null  value for the field if found.  null if not found.
361
-     * @throws \EE_Error
362
-     */
363
-    public function get_field_or_extra_meta($field_name)
364
-    {
365
-        if ($this->get_model()->has_field($field_name)) {
366
-            $column_value = $this->get($field_name);
367
-        } else {
368
-            //This isn't a column in the main table, let's see if it is in the extra meta.
369
-            $column_value = $this->get_extra_meta($field_name, true, null);
370
-        }
371
-        return $column_value;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
-     *
382
-     * @access public
383
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
-     * @return void
385
-     * @throws \EE_Error
386
-     */
387
-    public function set_timezone($timezone = '')
388
-    {
389
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
-        //make sure we clear all cached properties because they won't be relevant now
391
-        $this->_clear_cached_properties();
392
-        //make sure we update field settings and the date for all EE_Datetime_Fields
393
-        $model_fields = $this->get_model()->field_settings(false);
394
-        foreach ($model_fields as $field_name => $field_obj) {
395
-            if ($field_obj instanceof EE_Datetime_Field) {
396
-                $field_obj->set_timezone($this->_timezone);
397
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
-                }
400
-            }
401
-        }
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * This just returns whatever is set for the current timezone.
408
-     *
409
-     * @access public
410
-     * @return string timezone string
411
-     */
412
-    public function get_timezone()
413
-    {
414
-        return $this->_timezone;
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * This sets the internal date format to what is sent in to be used as the new default for the class
421
-     * internally instead of wp set date format options
422
-     *
423
-     * @since 4.6
424
-     * @param string $format should be a format recognizable by PHP date() functions.
425
-     */
426
-    public function set_date_format($format)
427
-    {
428
-        $this->_dt_frmt = $format;
429
-        //clear cached_properties because they won't be relevant now.
430
-        $this->_clear_cached_properties();
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * This sets the internal time format string to what is sent in to be used as the new default for the
437
-     * class internally instead of wp set time format options.
438
-     *
439
-     * @since 4.6
440
-     * @param string $format should be a format recognizable by PHP date() functions.
441
-     */
442
-    public function set_time_format($format)
443
-    {
444
-        $this->_tm_frmt = $format;
445
-        //clear cached_properties because they won't be relevant now.
446
-        $this->_clear_cached_properties();
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * This returns the current internal set format for the date and time formats.
453
-     *
454
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
-     *                             where the first value is the date format and the second value is the time format.
456
-     * @return mixed string|array
457
-     */
458
-    public function get_format($full = true)
459
-    {
460
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
-    }
462
-
463
-
464
-
465
-    /**
466
-     * cache
467
-     * stores the passed model object on the current model object.
468
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
-     *
470
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
-     *                                       'Registration' associated with this model object
472
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
-     *                                       that could be a payment or a registration)
474
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
-     *                                       items which will be stored in an array on this object
476
-     * @throws EE_Error
477
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
-     *                  related thing, no array)
479
-     */
480
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
-    {
482
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
484
-            return false;
485
-        }
486
-        // also get "how" the object is related, or throw an error
487
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
-                $relationName, get_class($this)));
490
-        }
491
-        // how many things are related ?
492
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
-            // so for these model objects just set it to be cached
495
-            $this->_model_relations[$relationName] = $object_to_cache;
496
-            $return = true;
497
-        } else {
498
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
-            if ( ! is_array($this->_model_relations[$relationName])) {
501
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
-                    ? array($this->_model_relations[$relationName]) : array();
504
-            }
505
-            // first check for a cache_id which is normally empty
506
-            if ( ! empty($cache_id)) {
507
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
-                $return = $cache_id;
510
-            } elseif ($object_to_cache->ID()) {
511
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
512
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
-                $return = $object_to_cache->ID();
514
-            } else {
515
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
-                $this->_model_relations[$relationName][] = $object_to_cache;
517
-                // move the internal pointer to the end of the array
518
-                end($this->_model_relations[$relationName]);
519
-                // and grab the key so that we can return it
520
-                $return = key($this->_model_relations[$relationName]);
521
-            }
522
-        }
523
-        return $return;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * For adding an item to the cached_properties property.
530
-     *
531
-     * @access protected
532
-     * @param string      $fieldname the property item the corresponding value is for.
533
-     * @param mixed       $value     The value we are caching.
534
-     * @param string|null $cache_type
535
-     * @return void
536
-     * @throws \EE_Error
537
-     */
538
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
-    {
540
-        //first make sure this property exists
541
-        $this->get_model()->field_settings_for($fieldname);
542
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
544
-    }
545
-
546
-
547
-
548
-    /**
549
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
-     * This also SETS the cache if we return the actual property!
551
-     *
552
-     * @param string $fieldname        the name of the property we're trying to retrieve
553
-     * @param bool   $pretty
554
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
-     *                                 (in cases where the same property may be used for different outputs
556
-     *                                 - i.e. datetime, money etc.)
557
-     *                                 It can also accept certain pre-defined "schema" strings
558
-     *                                 to define how to output the property.
559
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
-     * @return mixed                   whatever the value for the property is we're retrieving
561
-     * @throws \EE_Error
562
-     */
563
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
-    {
565
-        //verify the field exists
566
-        $this->get_model()->field_settings_for($fieldname);
567
-        $cache_type = $pretty ? 'pretty' : 'standard';
568
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
-            return $this->_cached_properties[$fieldname][$cache_type];
571
-        }
572
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
573
-        if ($field_obj instanceof EE_Model_Field_Base) {
574
-            // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
575
-            if ($field_obj instanceof EE_Datetime_Field) {
576
-                $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
577
-            }
578
-            if ( ! isset($this->_fields[$fieldname])) {
579
-                $this->_fields[$fieldname] = null;
580
-            }
581
-            $value = $pretty
582
-                ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
583
-                : $field_obj->prepare_for_get($this->_fields[$fieldname]);
584
-            $this->_set_cached_property($fieldname, $value, $cache_type);
585
-            return $value;
586
-        }
587
-        return null;
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * set timezone, formats, and output for EE_Datetime_Field objects
594
-     *
595
-     * @param \EE_Datetime_Field $datetime_field
596
-     * @param bool               $pretty
597
-     * @param null $date_or_time
598
-     * @return void
599
-     * @throws \EE_Error
600
-     */
601
-    protected function _prepare_datetime_field(
602
-        EE_Datetime_Field $datetime_field,
603
-        $pretty = false,
604
-        $date_or_time = null
605
-    ) {
606
-        $datetime_field->set_timezone($this->_timezone);
607
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
608
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
609
-        //set the output returned
610
-        switch ($date_or_time) {
611
-            case 'D' :
612
-                $datetime_field->set_date_time_output('date');
613
-                break;
614
-            case 'T' :
615
-                $datetime_field->set_date_time_output('time');
616
-                break;
617
-            default :
618
-                $datetime_field->set_date_time_output();
619
-        }
620
-    }
621
-
622
-
623
-
624
-    /**
625
-     * This just takes care of clearing out the cached_properties
626
-     *
627
-     * @return void
628
-     */
629
-    protected function _clear_cached_properties()
630
-    {
631
-        $this->_cached_properties = array();
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * This just clears out ONE property if it exists in the cache
638
-     *
639
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
640
-     * @return void
641
-     */
642
-    protected function _clear_cached_property($property_name)
643
-    {
644
-        if (isset($this->_cached_properties[$property_name])) {
645
-            unset($this->_cached_properties[$property_name]);
646
-        }
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * Ensures that this related thing is a model object.
653
-     *
654
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
655
-     * @param string $model_name   name of the related thing, eg 'Attendee',
656
-     * @return EE_Base_Class
657
-     * @throws \EE_Error
658
-     */
659
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
660
-    {
661
-        $other_model_instance = self::_get_model_instance_with_name(
662
-            self::_get_model_classname($model_name),
663
-            $this->_timezone
664
-        );
665
-        return $other_model_instance->ensure_is_obj($object_or_id);
666
-    }
667
-
668
-
669
-
670
-    /**
671
-     * Forgets the cached model of the given relation Name. So the next time we request it,
672
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
673
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
674
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
675
-     *
676
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
677
-     *                                                     Eg 'Registration'
678
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
679
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
680
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
681
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
682
-     *                                                     this is HasMany or HABTM.
683
-     * @throws EE_Error
684
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
685
-     *                       relation from all
686
-     */
687
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
688
-    {
689
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
690
-        $index_in_cache = '';
691
-        if ( ! $relationship_to_model) {
692
-            throw new EE_Error(
693
-                sprintf(
694
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
695
-                    $relationName,
696
-                    get_class($this)
697
-                )
698
-            );
699
-        }
700
-        if ($clear_all) {
701
-            $obj_removed = true;
702
-            $this->_model_relations[$relationName] = null;
703
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
704
-            $obj_removed = $this->_model_relations[$relationName];
705
-            $this->_model_relations[$relationName] = null;
706
-        } else {
707
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
708
-                && $object_to_remove_or_index_into_array->ID()
709
-            ) {
710
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
711
-                if (is_array($this->_model_relations[$relationName])
712
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
713
-                ) {
714
-                    $index_found_at = null;
715
-                    //find this object in the array even though it has a different key
716
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
717
-                        if (
718
-                            $obj instanceof EE_Base_Class
719
-                            && (
720
-                                $obj == $object_to_remove_or_index_into_array
721
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
722
-                            )
723
-                        ) {
724
-                            $index_found_at = $index;
725
-                            break;
726
-                        }
727
-                    }
728
-                    if ($index_found_at) {
729
-                        $index_in_cache = $index_found_at;
730
-                    } else {
731
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
732
-                        //if it wasn't in it to begin with. So we're done
733
-                        return $object_to_remove_or_index_into_array;
734
-                    }
735
-                }
736
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
737
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
738
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
739
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
740
-                        $index_in_cache = $index;
741
-                    }
742
-                }
743
-            } else {
744
-                $index_in_cache = $object_to_remove_or_index_into_array;
745
-            }
746
-            //supposedly we've found it. But it could just be that the client code
747
-            //provided a bad index/object
748
-            if (
749
-            isset(
750
-                $this->_model_relations[$relationName],
751
-                $this->_model_relations[$relationName][$index_in_cache]
752
-            )
753
-            ) {
754
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
755
-                unset($this->_model_relations[$relationName][$index_in_cache]);
756
-            } else {
757
-                //that thing was never cached anyways.
758
-                $obj_removed = null;
759
-            }
760
-        }
761
-        return $obj_removed;
762
-    }
763
-
764
-
765
-
766
-    /**
767
-     * update_cache_after_object_save
768
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
769
-     * obtained after being saved to the db
770
-     *
771
-     * @param string         $relationName       - the type of object that is cached
772
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
773
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
774
-     * @return boolean TRUE on success, FALSE on fail
775
-     * @throws \EE_Error
776
-     */
777
-    public function update_cache_after_object_save(
778
-        $relationName,
779
-        EE_Base_Class $newly_saved_object,
780
-        $current_cache_id = ''
781
-    ) {
782
-        // verify that incoming object is of the correct type
783
-        $obj_class = 'EE_' . $relationName;
784
-        if ($newly_saved_object instanceof $obj_class) {
785
-            /* @type EE_Base_Class $newly_saved_object */
786
-            // now get the type of relation
787
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
788
-            // if this is a 1:1 relationship
789
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
790
-                // then just replace the cached object with the newly saved object
791
-                $this->_model_relations[$relationName] = $newly_saved_object;
792
-                return true;
793
-                // or if it's some kind of sordid feral polyamorous relationship...
794
-            } elseif (is_array($this->_model_relations[$relationName])
795
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
796
-            ) {
797
-                // then remove the current cached item
798
-                unset($this->_model_relations[$relationName][$current_cache_id]);
799
-                // and cache the newly saved object using it's new ID
800
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
801
-                return true;
802
-            }
803
-        }
804
-        return false;
805
-    }
806
-
807
-
808
-
809
-    /**
810
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
811
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
812
-     *
813
-     * @param string $relationName
814
-     * @return EE_Base_Class
815
-     */
816
-    public function get_one_from_cache($relationName)
817
-    {
818
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
819
-            : null;
820
-        if (is_array($cached_array_or_object)) {
821
-            return array_shift($cached_array_or_object);
822
-        } else {
823
-            return $cached_array_or_object;
824
-        }
825
-    }
826
-
827
-
828
-
829
-    /**
830
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
831
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
832
-     *
833
-     * @param string $relationName
834
-     * @throws \EE_Error
835
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
836
-     */
837
-    public function get_all_from_cache($relationName)
838
-    {
839
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
840
-        // if the result is not an array, but exists, make it an array
841
-        $objects = is_array($objects) ? $objects : array($objects);
842
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
843
-        //basically, if this model object was stored in the session, and these cached model objects
844
-        //already have IDs, let's make sure they're in their model's entity mapper
845
-        //otherwise we will have duplicates next time we call
846
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
847
-        $model = EE_Registry::instance()->load_model($relationName);
848
-        foreach ($objects as $model_object) {
849
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
850
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
851
-                if ($model_object->ID()) {
852
-                    $model->add_to_entity_map($model_object);
853
-                }
854
-            } else {
855
-                throw new EE_Error(
856
-                    sprintf(
857
-                        __(
858
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
859
-                            'event_espresso'
860
-                        ),
861
-                        $relationName,
862
-                        gettype($model_object)
863
-                    )
864
-                );
865
-            }
866
-        }
867
-        return $objects;
868
-    }
869
-
870
-
871
-
872
-    /**
873
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
874
-     * matching the given query conditions.
875
-     *
876
-     * @param null  $field_to_order_by  What field is being used as the reference point.
877
-     * @param int   $limit              How many objects to return.
878
-     * @param array $query_params       Any additional conditions on the query.
879
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
880
-     *                                  you can indicate just the columns you want returned
881
-     * @return array|EE_Base_Class[]
882
-     * @throws \EE_Error
883
-     */
884
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
885
-    {
886
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
887
-            ? $this->get_model()->get_primary_key_field()->get_name()
888
-            : $field_to_order_by;
889
-        $current_value = ! empty($field) ? $this->get($field) : null;
890
-        if (empty($field) || empty($current_value)) {
891
-            return array();
892
-        }
893
-        return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
894
-    }
895
-
896
-
897
-
898
-    /**
899
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
900
-     * matching the given query conditions.
901
-     *
902
-     * @param null  $field_to_order_by  What field is being used as the reference point.
903
-     * @param int   $limit              How many objects to return.
904
-     * @param array $query_params       Any additional conditions on the query.
905
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
906
-     *                                  you can indicate just the columns you want returned
907
-     * @return array|EE_Base_Class[]
908
-     * @throws \EE_Error
909
-     */
910
-    public function previous_x(
911
-        $field_to_order_by = null,
912
-        $limit = 1,
913
-        $query_params = array(),
914
-        $columns_to_select = null
915
-    ) {
916
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
917
-            ? $this->get_model()->get_primary_key_field()->get_name()
918
-            : $field_to_order_by;
919
-        $current_value = ! empty($field) ? $this->get($field) : null;
920
-        if (empty($field) || empty($current_value)) {
921
-            return array();
922
-        }
923
-        return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
930
-     * matching the given query conditions.
931
-     *
932
-     * @param null  $field_to_order_by  What field is being used as the reference point.
933
-     * @param array $query_params       Any additional conditions on the query.
934
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
935
-     *                                  you can indicate just the columns you want returned
936
-     * @return array|EE_Base_Class
937
-     * @throws \EE_Error
938
-     */
939
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
940
-    {
941
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
942
-            ? $this->get_model()->get_primary_key_field()->get_name()
943
-            : $field_to_order_by;
944
-        $current_value = ! empty($field) ? $this->get($field) : null;
945
-        if (empty($field) || empty($current_value)) {
946
-            return array();
947
-        }
948
-        return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
955
-     * matching the given query conditions.
956
-     *
957
-     * @param null  $field_to_order_by  What field is being used as the reference point.
958
-     * @param array $query_params       Any additional conditions on the query.
959
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
960
-     *                                  you can indicate just the column you want returned
961
-     * @return array|EE_Base_Class
962
-     * @throws \EE_Error
963
-     */
964
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
965
-    {
966
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
967
-            ? $this->get_model()->get_primary_key_field()->get_name()
968
-            : $field_to_order_by;
969
-        $current_value = ! empty($field) ? $this->get($field) : null;
970
-        if (empty($field) || empty($current_value)) {
971
-            return array();
972
-        }
973
-        return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
974
-    }
975
-
976
-
977
-
978
-    /**
979
-     * Overrides parent because parent expects old models.
980
-     * This also doesn't do any validation, and won't work for serialized arrays
981
-     *
982
-     * @param string $field_name
983
-     * @param mixed  $field_value_from_db
984
-     * @throws \EE_Error
985
-     */
986
-    public function set_from_db($field_name, $field_value_from_db)
987
-    {
988
-        $field_obj = $this->get_model()->field_settings_for($field_name);
989
-        if ($field_obj instanceof EE_Model_Field_Base) {
990
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
991
-            //eg, a CPT model object could have an entry in the posts table, but no
992
-            //entry in the meta table. Meaning that all its columns in the meta table
993
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
994
-            if ($field_value_from_db === null) {
995
-                if ($field_obj->is_nullable()) {
996
-                    //if the field allows nulls, then let it be null
997
-                    $field_value = null;
998
-                } else {
999
-                    $field_value = $field_obj->get_default_value();
1000
-                }
1001
-            } else {
1002
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1003
-            }
1004
-            $this->_fields[$field_name] = $field_value;
1005
-            $this->_clear_cached_property($field_name);
1006
-        }
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     * verifies that the specified field is of the correct type
1013
-     *
1014
-     * @param string $field_name
1015
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1016
-     *                                (in cases where the same property may be used for different outputs
1017
-     *                                - i.e. datetime, money etc.)
1018
-     * @return mixed
1019
-     * @throws \EE_Error
1020
-     */
1021
-    public function get($field_name, $extra_cache_ref = null)
1022
-    {
1023
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * This method simply returns the RAW unprocessed value for the given property in this class
1030
-     *
1031
-     * @param  string $field_name A valid fieldname
1032
-     * @return mixed              Whatever the raw value stored on the property is.
1033
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1034
-     */
1035
-    public function get_raw($field_name)
1036
-    {
1037
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1038
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1039
-            ? $this->_fields[$field_name]->format('U')
1040
-            : $this->_fields[$field_name];
1041
-    }
1042
-
1043
-
1044
-
1045
-    /**
1046
-     * This is used to return the internal DateTime object used for a field that is a
1047
-     * EE_Datetime_Field.
1048
-     *
1049
-     * @param string $field_name               The field name retrieving the DateTime object.
1050
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1051
-     * @throws \EE_Error
1052
-     *                                         an error is set and false returned.  If the field IS an
1053
-     *                                         EE_Datetime_Field and but the field value is null, then
1054
-     *                                         just null is returned (because that indicates that likely
1055
-     *                                         this field is nullable).
1056
-     */
1057
-    public function get_DateTime_object($field_name)
1058
-    {
1059
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1060
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1061
-            EE_Error::add_error(
1062
-                sprintf(
1063
-                    __(
1064
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1065
-                        'event_espresso'
1066
-                    ),
1067
-                    $field_name
1068
-                ),
1069
-                __FILE__,
1070
-                __FUNCTION__,
1071
-                __LINE__
1072
-            );
1073
-            return false;
1074
-        }
1075
-        return $this->_fields[$field_name];
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * To be used in template to immediately echo out the value, and format it for output.
1082
-     * Eg, should call stripslashes and whatnot before echoing
1083
-     *
1084
-     * @param string $field_name      the name of the field as it appears in the DB
1085
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1086
-     *                                (in cases where the same property may be used for different outputs
1087
-     *                                - i.e. datetime, money etc.)
1088
-     * @return void
1089
-     * @throws \EE_Error
1090
-     */
1091
-    public function e($field_name, $extra_cache_ref = null)
1092
-    {
1093
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1100
-     * can be easily used as the value of form input.
1101
-     *
1102
-     * @param string $field_name
1103
-     * @return void
1104
-     * @throws \EE_Error
1105
-     */
1106
-    public function f($field_name)
1107
-    {
1108
-        $this->e($field_name, 'form_input');
1109
-    }
1110
-
1111
-
1112
-
1113
-    /**
1114
-     * @param string $field_name
1115
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1116
-     *                                (in cases where the same property may be used for different outputs
1117
-     *                                - i.e. datetime, money etc.)
1118
-     * @return mixed
1119
-     * @throws \EE_Error
1120
-     */
1121
-    public function get_pretty($field_name, $extra_cache_ref = null)
1122
-    {
1123
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * This simply returns the datetime for the given field name
1130
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1131
-     * (and the equivalent e_date, e_time, e_datetime).
1132
-     *
1133
-     * @access   protected
1134
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1135
-     * @param string   $dt_frmt      valid datetime format used for date
1136
-     *                               (if '' then we just use the default on the field,
1137
-     *                               if NULL we use the last-used format)
1138
-     * @param string   $tm_frmt      Same as above except this is for time format
1139
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1140
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1141
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1142
-     *                               if field is not a valid dtt field, or void if echoing
1143
-     * @throws \EE_Error
1144
-     */
1145
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1146
-    {
1147
-        // clear cached property
1148
-        $this->_clear_cached_property($field_name);
1149
-        //reset format properties because they are used in get()
1150
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1151
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1152
-        if ($echo) {
1153
-            $this->e($field_name, $date_or_time);
1154
-            return '';
1155
-        }
1156
-        return $this->get($field_name, $date_or_time);
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1163
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1164
-     * other echoes the pretty value for dtt)
1165
-     *
1166
-     * @param  string $field_name name of model object datetime field holding the value
1167
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1168
-     * @return string            datetime value formatted
1169
-     * @throws \EE_Error
1170
-     */
1171
-    public function get_date($field_name, $format = '')
1172
-    {
1173
-        return $this->_get_datetime($field_name, $format, null, 'D');
1174
-    }
1175
-
1176
-
1177
-
1178
-    /**
1179
-     * @param      $field_name
1180
-     * @param string $format
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function e_date($field_name, $format = '')
1184
-    {
1185
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1186
-    }
1187
-
1188
-
1189
-
1190
-    /**
1191
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1192
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1193
-     * other echoes the pretty value for dtt)
1194
-     *
1195
-     * @param  string $field_name name of model object datetime field holding the value
1196
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1197
-     * @return string             datetime value formatted
1198
-     * @throws \EE_Error
1199
-     */
1200
-    public function get_time($field_name, $format = '')
1201
-    {
1202
-        return $this->_get_datetime($field_name, null, $format, 'T');
1203
-    }
1204
-
1205
-
1206
-
1207
-    /**
1208
-     * @param      $field_name
1209
-     * @param string $format
1210
-     * @throws \EE_Error
1211
-     */
1212
-    public function e_time($field_name, $format = '')
1213
-    {
1214
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1215
-    }
1216
-
1217
-
1218
-
1219
-    /**
1220
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1221
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1222
-     * other echoes the pretty value for dtt)
1223
-     *
1224
-     * @param  string $field_name name of model object datetime field holding the value
1225
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1226
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1227
-     * @return string             datetime value formatted
1228
-     * @throws \EE_Error
1229
-     */
1230
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1231
-    {
1232
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1233
-    }
1234
-
1235
-
1236
-
1237
-    /**
1238
-     * @param string $field_name
1239
-     * @param string $dt_frmt
1240
-     * @param string $tm_frmt
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1244
-    {
1245
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1246
-    }
1247
-
1248
-
1249
-
1250
-    /**
1251
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1252
-     *
1253
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1254
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1255
-     *                           on the object will be used.
1256
-     * @return string Date and time string in set locale or false if no field exists for the given
1257
-     * @throws \EE_Error
1258
-     *                           field name.
1259
-     */
1260
-    public function get_i18n_datetime($field_name, $format = '')
1261
-    {
1262
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1263
-        return date_i18n(
1264
-            $format,
1265
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1266
-        );
1267
-    }
1268
-
1269
-
1270
-
1271
-    /**
1272
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1273
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1274
-     * thrown.
1275
-     *
1276
-     * @param  string $field_name The field name being checked
1277
-     * @throws EE_Error
1278
-     * @return EE_Datetime_Field
1279
-     */
1280
-    protected function _get_dtt_field_settings($field_name)
1281
-    {
1282
-        $field = $this->get_model()->field_settings_for($field_name);
1283
-        //check if field is dtt
1284
-        if ($field instanceof EE_Datetime_Field) {
1285
-            return $field;
1286
-        } else {
1287
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1288
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1289
-        }
1290
-    }
1291
-
1292
-
1293
-
1294
-
1295
-    /**
1296
-     * NOTE ABOUT BELOW:
1297
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1298
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1299
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1300
-     * method and make sure you send the entire datetime value for setting.
1301
-     */
1302
-    /**
1303
-     * sets the time on a datetime property
1304
-     *
1305
-     * @access protected
1306
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1307
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1308
-     * @throws \EE_Error
1309
-     */
1310
-    protected function _set_time_for($time, $fieldname)
1311
-    {
1312
-        $this->_set_date_time('T', $time, $fieldname);
1313
-    }
1314
-
1315
-
1316
-
1317
-    /**
1318
-     * sets the date on a datetime property
1319
-     *
1320
-     * @access protected
1321
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1322
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1323
-     * @throws \EE_Error
1324
-     */
1325
-    protected function _set_date_for($date, $fieldname)
1326
-    {
1327
-        $this->_set_date_time('D', $date, $fieldname);
1328
-    }
1329
-
1330
-
1331
-
1332
-    /**
1333
-     * This takes care of setting a date or time independently on a given model object property. This method also
1334
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1335
-     *
1336
-     * @access protected
1337
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1338
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1339
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1340
-     *                                        EE_Datetime_Field property)
1341
-     * @throws \EE_Error
1342
-     */
1343
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1344
-    {
1345
-        $field = $this->_get_dtt_field_settings($fieldname);
1346
-        $field->set_timezone($this->_timezone);
1347
-        $field->set_date_format($this->_dt_frmt);
1348
-        $field->set_time_format($this->_tm_frmt);
1349
-        switch ($what) {
1350
-            case 'T' :
1351
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1352
-                    $datetime_value,
1353
-                    $this->_fields[$fieldname]
1354
-                );
1355
-                break;
1356
-            case 'D' :
1357
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1358
-                    $datetime_value,
1359
-                    $this->_fields[$fieldname]
1360
-                );
1361
-                break;
1362
-            case 'B' :
1363
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1364
-                break;
1365
-        }
1366
-        $this->_clear_cached_property($fieldname);
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1373
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1374
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1375
-     * that could lead to some unexpected results!
1376
-     *
1377
-     * @access public
1378
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1379
-     *                                         value being returned.
1380
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1381
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1382
-     * @param string               $prepend    You can include something to prepend on the timestamp
1383
-     * @param string               $append     You can include something to append on the timestamp
1384
-     * @throws EE_Error
1385
-     * @return string timestamp
1386
-     */
1387
-    public function display_in_my_timezone(
1388
-        $field_name,
1389
-        $callback = 'get_datetime',
1390
-        $args = null,
1391
-        $prepend = '',
1392
-        $append = ''
1393
-    ) {
1394
-        $timezone = EEH_DTT_Helper::get_timezone();
1395
-        if ($timezone === $this->_timezone) {
1396
-            return '';
1397
-        }
1398
-        $original_timezone = $this->_timezone;
1399
-        $this->set_timezone($timezone);
1400
-        $fn = (array)$field_name;
1401
-        $args = array_merge($fn, (array)$args);
1402
-        if ( ! method_exists($this, $callback)) {
1403
-            throw new EE_Error(
1404
-                sprintf(
1405
-                    __(
1406
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1407
-                        'event_espresso'
1408
-                    ),
1409
-                    $callback
1410
-                )
1411
-            );
1412
-        }
1413
-        $args = (array)$args;
1414
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1415
-        $this->set_timezone($original_timezone);
1416
-        return $return;
1417
-    }
1418
-
1419
-
1420
-
1421
-    /**
1422
-     * Deletes this model object.
1423
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1424
-     * override
1425
-     * `EE_Base_Class::_delete` NOT this class.
1426
-     *
1427
-     * @return boolean | int
1428
-     * @throws \EE_Error
1429
-     */
1430
-    public function delete()
1431
-    {
1432
-        /**
1433
-         * Called just before the `EE_Base_Class::_delete` method call.
1434
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1435
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1436
-         * soft deletes (trash) the object and does not permanently delete it.
1437
-         *
1438
-         * @param EE_Base_Class $model_object about to be 'deleted'
1439
-         */
1440
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1441
-        $result = $this->_delete();
1442
-        /**
1443
-         * Called just after the `EE_Base_Class::_delete` method call.
1444
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1445
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1446
-         * soft deletes (trash) the object and does not permanently delete it.
1447
-         *
1448
-         * @param EE_Base_Class $model_object that was just 'deleted'
1449
-         * @param boolean       $result
1450
-         */
1451
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1452
-        return $result;
1453
-    }
1454
-
1455
-
1456
-
1457
-    /**
1458
-     * Calls the specific delete method for the instantiated class.
1459
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1460
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1461
-     * `EE_Base_Class::delete`
1462
-     *
1463
-     * @return bool|int
1464
-     * @throws \EE_Error
1465
-     */
1466
-    protected function _delete()
1467
-    {
1468
-        return $this->delete_permanently();
1469
-    }
1470
-
1471
-
1472
-
1473
-    /**
1474
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1475
-     * error)
1476
-     *
1477
-     * @return bool | int
1478
-     * @throws \EE_Error
1479
-     */
1480
-    public function delete_permanently()
1481
-    {
1482
-        /**
1483
-         * Called just before HARD deleting a model object
1484
-         *
1485
-         * @param EE_Base_Class $model_object about to be 'deleted'
1486
-         */
1487
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1488
-        $model = $this->get_model();
1489
-        $result = $model->delete_permanently_by_ID($this->ID());
1490
-        $this->refresh_cache_of_related_objects();
1491
-        /**
1492
-         * Called just after HARD deleting a model object
1493
-         *
1494
-         * @param EE_Base_Class $model_object that was just 'deleted'
1495
-         * @param boolean       $result
1496
-         */
1497
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1498
-        return $result;
1499
-    }
1500
-
1501
-
1502
-
1503
-    /**
1504
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1505
-     * related model objects
1506
-     *
1507
-     * @throws \EE_Error
1508
-     */
1509
-    public function refresh_cache_of_related_objects()
1510
-    {
1511
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1512
-            if ( ! empty($this->_model_relations[$relation_name])) {
1513
-                $related_objects = $this->_model_relations[$relation_name];
1514
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1515
-                    //this relation only stores a single model object, not an array
1516
-                    //but let's make it consistent
1517
-                    $related_objects = array($related_objects);
1518
-                }
1519
-                foreach ($related_objects as $related_object) {
1520
-                    //only refresh their cache if they're in memory
1521
-                    if ($related_object instanceof EE_Base_Class) {
1522
-                        $related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1523
-                    }
1524
-                }
1525
-            }
1526
-        }
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     *        Saves this object to the database. An array may be supplied to set some values on this
1533
-     * object just before saving.
1534
-     *
1535
-     * @access public
1536
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1537
-     *                                 if provided during the save() method (often client code will change the fields'
1538
-     *                                 values before calling save)
1539
-     * @throws \EE_Error
1540
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1541
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1542
-     */
1543
-    public function save($set_cols_n_values = array())
1544
-    {
1545
-        /**
1546
-         * Filters the fields we're about to save on the model object
1547
-         *
1548
-         * @param array         $set_cols_n_values
1549
-         * @param EE_Base_Class $model_object
1550
-         */
1551
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552
-            $this);
1553
-        //set attributes as provided in $set_cols_n_values
1554
-        foreach ($set_cols_n_values as $column => $value) {
1555
-            $this->set($column, $value);
1556
-        }
1557
-        /**
1558
-         * Saving a model object.
1559
-         * Before we perform a save, this action is fired.
1560
-         *
1561
-         * @param EE_Base_Class $model_object the model object about to be saved.
1562
-         */
1563
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1564
-        if ( ! $this->allow_persist()) {
1565
-            return 0;
1566
-        }
1567
-        //now get current attribute values
1568
-        $save_cols_n_values = $this->_fields;
1569
-        //if the object already has an ID, update it. Otherwise, insert it
1570
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1571
-        $old_assumption_concerning_value_preparation = $this->get_model()
1572
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1573
-        $this->get_model()->assume_values_already_prepared_by_model_object(true);
1574
-        //does this model have an autoincrement PK?
1575
-        if ($this->get_model()->has_primary_key_field()) {
1576
-            if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
-                //ok check if it's set, if so: update; if not, insert
1578
-                if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1579
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1580
-                } else {
1581
-                    unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1582
-                    $results = $this->get_model()->insert($save_cols_n_values);
1583
-                    if ($results) {
1584
-                        //if successful, set the primary key
1585
-                        //but don't use the normal SET method, because it will check if
1586
-                        //an item with the same ID exists in the mapper & db, then
1587
-                        //will find it in the db (because we just added it) and THAT object
1588
-                        //will get added to the mapper before we can add this one!
1589
-                        //but if we just avoid using the SET method, all that headache can be avoided
1590
-                        $pk_field_name = self::_get_primary_key_name(get_class($this));
1591
-                        $this->_fields[$pk_field_name] = $results;
1592
-                        $this->_clear_cached_property($pk_field_name);
1593
-                        $this->get_model()->add_to_entity_map($this);
1594
-                        $this->_update_cached_related_model_objs_fks();
1595
-                    }
1596
-                }
1597
-            } else {//PK is NOT auto-increment
1598
-                //so check if one like it already exists in the db
1599
-                if ($this->get_model()->exists_by_ID($this->ID())) {
1600
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1601
-                        throw new EE_Error(
1602
-                            sprintf(
1603
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604
-                                    'event_espresso'),
1605
-                                get_class($this),
1606
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1608
-                                '<br />'
1609
-                            )
1610
-                        );
1611
-                    }
1612
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1613
-                } else {
1614
-                    $results = $this->get_model()->insert($save_cols_n_values);
1615
-                    $this->_update_cached_related_model_objs_fks();
1616
-                }
1617
-            }
1618
-        } else {//there is NO primary key
1619
-            $already_in_db = false;
1620
-            foreach ($this->get_model()->unique_indexes() as $index) {
1621
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1622
-                if ($this->get_model()->exists(array($uniqueness_where_params))) {
1623
-                    $already_in_db = true;
1624
-                }
1625
-            }
1626
-            if ($already_in_db) {
1627
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1628
-                    $this->get_model()->get_combined_primary_key_fields());
1629
-                $results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1630
-            } else {
1631
-                $results = $this->get_model()->insert($save_cols_n_values);
1632
-            }
1633
-        }
1634
-        //restore the old assumption about values being prepared by the model object
1635
-        $this->get_model()
1636
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1637
-        /**
1638
-         * After saving the model object this action is called
1639
-         *
1640
-         * @param EE_Base_Class $model_object which was just saved
1641
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1642
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1643
-         */
1644
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1645
-        return $results;
1646
-    }
1647
-
1648
-
1649
-
1650
-    /**
1651
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1652
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1653
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1654
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1655
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1656
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1657
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1658
-     *
1659
-     * @return void
1660
-     * @throws \EE_Error
1661
-     */
1662
-    protected function _update_cached_related_model_objs_fks()
1663
-    {
1664
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1665
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1666
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1667
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1668
-                        $this->get_model()->get_this_model_name()
1669
-                    );
1670
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1671
-                    if ($related_model_obj_in_cache->ID()) {
1672
-                        $related_model_obj_in_cache->save();
1673
-                    }
1674
-                }
1675
-            }
1676
-        }
1677
-    }
1678
-
1679
-
1680
-
1681
-    /**
1682
-     * Saves this model object and its NEW cached relations to the database.
1683
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1684
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1685
-     * because otherwise, there's a potential for infinite looping of saving
1686
-     * Saves the cached related model objects, and ensures the relation between them
1687
-     * and this object and properly setup
1688
-     *
1689
-     * @return int ID of new model object on save; 0 on failure+
1690
-     * @throws \EE_Error
1691
-     */
1692
-    public function save_new_cached_related_model_objs()
1693
-    {
1694
-        //make sure this has been saved
1695
-        if ( ! $this->ID()) {
1696
-            $id = $this->save();
1697
-        } else {
1698
-            $id = $this->ID();
1699
-        }
1700
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1701
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1702
-            if ($this->_model_relations[$relationName]) {
1703
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1704
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1705
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1706
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1707
-                    //but ONLY if it DOES NOT exist in the DB
1708
-                    /* @var $related_model_obj EE_Base_Class */
1709
-                    $related_model_obj = $this->_model_relations[$relationName];
1710
-                    //					if( ! $related_model_obj->ID()){
1711
-                    $this->_add_relation_to($related_model_obj, $relationName);
1712
-                    $related_model_obj->save_new_cached_related_model_objs();
1713
-                    //					}
1714
-                } else {
1715
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1716
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1717
-                        //but ONLY if it DOES NOT exist in the DB
1718
-                        //						if( ! $related_model_obj->ID()){
1719
-                        $this->_add_relation_to($related_model_obj, $relationName);
1720
-                        $related_model_obj->save_new_cached_related_model_objs();
1721
-                        //						}
1722
-                    }
1723
-                }
1724
-            }
1725
-        }
1726
-        return $id;
1727
-    }
1728
-
1729
-
1730
-
1731
-    /**
1732
-     * for getting a model while instantiated.
1733
-     *
1734
-     * @return \EEM_Base | \EEM_CPT_Base
1735
-     */
1736
-    public function get_model()
1737
-    {
1738
-        $modelName = self::_get_model_classname(get_class($this));
1739
-        return self::_get_model_instance_with_name($modelName, $this->_timezone);
1740
-    }
1741
-
1742
-
1743
-
1744
-    /**
1745
-     * @param $props_n_values
1746
-     * @param $classname
1747
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1748
-     * @throws \EE_Error
1749
-     */
1750
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1751
-    {
1752
-        //TODO: will not work for Term_Relationships because they have no PK!
1753
-        $primary_id_ref = self::_get_primary_key_name($classname);
1754
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1755
-            $id = $props_n_values[$primary_id_ref];
1756
-            return self::_get_model($classname)->get_from_entity_map($id);
1757
-        }
1758
-        return false;
1759
-    }
1760
-
1761
-
1762
-
1763
-    /**
1764
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1765
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1766
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1767
-     * we return false.
1768
-     *
1769
-     * @param  array  $props_n_values   incoming array of properties and their values
1770
-     * @param  string $classname        the classname of the child class
1771
-     * @param null    $timezone
1772
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1773
-     *                                  date_format and the second value is the time format
1774
-     * @return mixed (EE_Base_Class|bool)
1775
-     * @throws \EE_Error
1776
-     */
1777
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1778
-    {
1779
-        $existing = null;
1780
-        if (self::_get_model($classname)->has_primary_key_field()) {
1781
-            $primary_id_ref = self::_get_primary_key_name($classname);
1782
-            if (array_key_exists($primary_id_ref, $props_n_values)
1783
-                && ! empty($props_n_values[$primary_id_ref])
1784
-            ) {
1785
-                $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1786
-                    $props_n_values[$primary_id_ref]
1787
-                );
1788
-            }
1789
-        } elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1790
-            //no primary key on this model, but there's still a matching item in the DB
1791
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1792
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1793
-            );
1794
-        }
1795
-        if ($existing) {
1796
-            //set date formats if present before setting values
1797
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1798
-                $existing->set_date_format($date_formats[0]);
1799
-                $existing->set_time_format($date_formats[1]);
1800
-            } else {
1801
-                //set default formats for date and time
1802
-                $existing->set_date_format(get_option('date_format'));
1803
-                $existing->set_time_format(get_option('time_format'));
1804
-            }
1805
-            foreach ($props_n_values as $property => $field_value) {
1806
-                $existing->set($property, $field_value);
1807
-            }
1808
-            return $existing;
1809
-        } else {
1810
-            return false;
1811
-        }
1812
-    }
1813
-
1814
-
1815
-
1816
-    /**
1817
-     * Gets the EEM_*_Model for this class
1818
-     *
1819
-     * @access public now, as this is more convenient
1820
-     * @param      $classname
1821
-     * @param null $timezone
1822
-     * @throws EE_Error
1823
-     * @return EEM_Base
1824
-     */
1825
-    protected static function _get_model($classname, $timezone = null)
1826
-    {
1827
-        //find model for this class
1828
-        if ( ! $classname) {
1829
-            throw new EE_Error(
1830
-                sprintf(
1831
-                    __(
1832
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1833
-                        "event_espresso"
1834
-                    ),
1835
-                    $classname
1836
-                )
1837
-            );
1838
-        }
1839
-        $modelName = self::_get_model_classname($classname);
1840
-        return self::_get_model_instance_with_name($modelName, $timezone);
1841
-    }
1842
-
1843
-
1844
-
1845
-    /**
1846
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1847
-     *
1848
-     * @param string $model_classname
1849
-     * @param null   $timezone
1850
-     * @return EEM_Base
1851
-     */
1852
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1853
-    {
1854
-        $model_classname = str_replace('EEM_', '', $model_classname);
1855
-        $model = EE_Registry::instance()->load_model($model_classname);
1856
-        $model->set_timezone($timezone);
1857
-        return $model;
1858
-    }
1859
-
1860
-
1861
-
1862
-    /**
1863
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1864
-     * Also works if a model class's classname is provided (eg EE_Registration).
1865
-     *
1866
-     * @param null $model_name
1867
-     * @return string like EEM_Attendee
1868
-     */
1869
-    private static function _get_model_classname($model_name = null)
1870
-    {
1871
-        if (strpos($model_name, "EE_") === 0) {
1872
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1873
-        } else {
1874
-            $model_classname = "EEM_" . $model_name;
1875
-        }
1876
-        return $model_classname;
1877
-    }
1878
-
1879
-
1880
-
1881
-    /**
1882
-     * returns the name of the primary key attribute
1883
-     *
1884
-     * @param null $classname
1885
-     * @throws EE_Error
1886
-     * @return string
1887
-     */
1888
-    protected static function _get_primary_key_name($classname = null)
1889
-    {
1890
-        if ( ! $classname) {
1891
-            throw new EE_Error(
1892
-                sprintf(
1893
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1894
-                    $classname
1895
-                )
1896
-            );
1897
-        }
1898
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1899
-    }
1900
-
1901
-
1902
-
1903
-    /**
1904
-     * Gets the value of the primary key.
1905
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1906
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1907
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1908
-     *
1909
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1910
-     * @throws \EE_Error
1911
-     */
1912
-    public function ID()
1913
-    {
1914
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1915
-        if ($this->get_model()->has_primary_key_field()) {
1916
-            return $this->_fields[self::_get_primary_key_name(get_class($this))];
1917
-        } else {
1918
-            return $this->get_model()->get_index_primary_key_string($this->_fields);
1919
-        }
1920
-    }
1921
-
1922
-
1923
-
1924
-    /**
1925
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1926
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1927
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1928
-     *
1929
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1930
-     * @param string $relationName                     eg 'Events','Question',etc.
1931
-     *                                                 an attendee to a group, you also want to specify which role they
1932
-     *                                                 will have in that group. So you would use this parameter to
1933
-     *                                                 specify array('role-column-name'=>'role-id')
1934
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1935
-     *                                                 allow you to further constrict the relation to being added.
1936
-     *                                                 However, keep in mind that the columns (keys) given must match a
1937
-     *                                                 column on the JOIN table and currently only the HABTM models
1938
-     *                                                 accept these additional conditions.  Also remember that if an
1939
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
1940
-     *                                                 NEW row is created in the join table.
1941
-     * @param null   $cache_id
1942
-     * @throws EE_Error
1943
-     * @return EE_Base_Class the object the relation was added to
1944
-     */
1945
-    public function _add_relation_to(
1946
-        $otherObjectModelObjectOrID,
1947
-        $relationName,
1948
-        $extra_join_model_fields_n_values = array(),
1949
-        $cache_id = null
1950
-    ) {
1951
-        //if this thing exists in the DB, save the relation to the DB
1952
-        if ($this->ID()) {
1953
-            $otherObject = $this->get_model()
1954
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1955
-                                    $extra_join_model_fields_n_values);
1956
-            //clear cache so future get_many_related and get_first_related() return new results.
1957
-            $this->clear_cache($relationName, $otherObject, true);
1958
-            if ($otherObject instanceof EE_Base_Class) {
1959
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1960
-            }
1961
-        } else {
1962
-            //this thing doesn't exist in the DB,  so just cache it
1963
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1964
-                throw new EE_Error(sprintf(
1965
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1966
-                        'event_espresso'),
1967
-                    $otherObjectModelObjectOrID,
1968
-                    get_class($this)
1969
-                ));
1970
-            } else {
1971
-                $otherObject = $otherObjectModelObjectOrID;
1972
-            }
1973
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1974
-        }
1975
-        if ($otherObject instanceof EE_Base_Class) {
1976
-            //fix the reciprocal relation too
1977
-            if ($otherObject->ID()) {
1978
-                //its saved so assumed relations exist in the DB, so we can just
1979
-                //clear the cache so future queries use the updated info in the DB
1980
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1981
-            } else {
1982
-                //it's not saved, so it caches relations like this
1983
-                $otherObject->cache($this->get_model()->get_this_model_name(), $this);
1984
-            }
1985
-        }
1986
-        return $otherObject;
1987
-    }
1988
-
1989
-
1990
-
1991
-    /**
1992
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
1993
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
1994
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
1995
-     * from the cache
1996
-     *
1997
-     * @param mixed  $otherObjectModelObjectOrID
1998
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
1999
-     *                to the DB yet
2000
-     * @param string $relationName
2001
-     * @param array  $where_query
2002
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2003
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2004
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2005
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2006
-     *                created in the join table.
2007
-     * @return EE_Base_Class the relation was removed from
2008
-     * @throws \EE_Error
2009
-     */
2010
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2011
-    {
2012
-        if ($this->ID()) {
2013
-            //if this exists in the DB, save the relation change to the DB too
2014
-            $otherObject = $this->get_model()
2015
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2016
-                                    $where_query);
2017
-            $this->clear_cache($relationName, $otherObject);
2018
-        } else {
2019
-            //this doesn't exist in the DB, just remove it from the cache
2020
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2021
-        }
2022
-        if ($otherObject instanceof EE_Base_Class) {
2023
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2024
-        }
2025
-        return $otherObject;
2026
-    }
2027
-
2028
-
2029
-
2030
-    /**
2031
-     * Removes ALL the related things for the $relationName.
2032
-     *
2033
-     * @param string $relationName
2034
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2035
-     * @return EE_Base_Class
2036
-     * @throws \EE_Error
2037
-     */
2038
-    public function _remove_relations($relationName, $where_query_params = array())
2039
-    {
2040
-        if ($this->ID()) {
2041
-            //if this exists in the DB, save the relation change to the DB too
2042
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2043
-            $this->clear_cache($relationName, null, true);
2044
-        } else {
2045
-            //this doesn't exist in the DB, just remove it from the cache
2046
-            $otherObjects = $this->clear_cache($relationName, null, true);
2047
-        }
2048
-        if (is_array($otherObjects)) {
2049
-            foreach ($otherObjects as $otherObject) {
2050
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2051
-            }
2052
-        }
2053
-        return $otherObjects;
2054
-    }
2055
-
2056
-
2057
-
2058
-    /**
2059
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2060
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2061
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2062
-     * because we want to get even deleted items etc.
2063
-     *
2064
-     * @param string $relationName key in the model's _model_relations array
2065
-     * @param array  $query_params like EEM_Base::get_all
2066
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2067
-     * @throws \EE_Error
2068
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2069
-     *                             you want IDs
2070
-     */
2071
-    public function get_many_related($relationName, $query_params = array())
2072
-    {
2073
-        if ($this->ID()) {
2074
-            //this exists in the DB, so get the related things from either the cache or the DB
2075
-            //if there are query parameters, forget about caching the related model objects.
2076
-            if ($query_params) {
2077
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2078
-            } else {
2079
-                //did we already cache the result of this query?
2080
-                $cached_results = $this->get_all_from_cache($relationName);
2081
-                if ( ! $cached_results) {
2082
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2083
-                    //if no query parameters were passed, then we got all the related model objects
2084
-                    //for that relation. We can cache them then.
2085
-                    foreach ($related_model_objects as $related_model_object) {
2086
-                        $this->cache($relationName, $related_model_object);
2087
-                    }
2088
-                } else {
2089
-                    $related_model_objects = $cached_results;
2090
-                }
2091
-            }
2092
-        } else {
2093
-            //this doesn't exist in the DB, so just get the related things from the cache
2094
-            $related_model_objects = $this->get_all_from_cache($relationName);
2095
-        }
2096
-        return $related_model_objects;
2097
-    }
2098
-
2099
-
2100
-
2101
-    /**
2102
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2103
-     * unless otherwise specified in the $query_params
2104
-     *
2105
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2106
-     * @param array  $query_params   like EEM_Base::get_all's
2107
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2108
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2109
-     *                               that by the setting $distinct to TRUE;
2110
-     * @return int
2111
-     */
2112
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2113
-    {
2114
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2115
-    }
2116
-
2117
-
2118
-
2119
-    /**
2120
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2121
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2122
-     *
2123
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2124
-     * @param array  $query_params  like EEM_Base::get_all's
2125
-     * @param string $field_to_sum  name of field to count by.
2126
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2127
-     *                              change it)
2128
-     * @return int
2129
-     */
2130
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2131
-    {
2132
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2133
-    }
2134
-
2135
-
2136
-
2137
-    /**
2138
-     * Gets the first (ie, one) related model object of the specified type.
2139
-     *
2140
-     * @param string $relationName key in the model's _model_relations array
2141
-     * @param array  $query_params like EEM_Base::get_all
2142
-     * @return EE_Base_Class (not an array, a single object)
2143
-     * @throws \EE_Error
2144
-     */
2145
-    public function get_first_related($relationName, $query_params = array())
2146
-    {
2147
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2148
-            //if they've provided some query parameters, don't bother trying to cache the result
2149
-            //also make sure we're not caching the result of get_first_related
2150
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2151
-            if ($query_params
2152
-                || ! $this->get_model()->related_settings_for($relationName)
2153
-                     instanceof
2154
-                     EE_Belongs_To_Relation
2155
-            ) {
2156
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2157
-            } else {
2158
-                //first, check if we've already cached the result of this query
2159
-                $cached_result = $this->get_one_from_cache($relationName);
2160
-                if ( ! $cached_result) {
2161
-                    $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2162
-                    $this->cache($relationName, $related_model_object);
2163
-                } else {
2164
-                    $related_model_object = $cached_result;
2165
-                }
2166
-            }
2167
-        } else {
2168
-            $related_model_object = null;
2169
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2170
-            if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2171
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
-            }
2173
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2174
-            if ( ! $related_model_object) {
2175
-                $related_model_object = $this->get_one_from_cache($relationName);
2176
-            }
2177
-        }
2178
-        return $related_model_object;
2179
-    }
2180
-
2181
-
2182
-
2183
-    /**
2184
-     * Does a delete on all related objects of type $relationName and removes
2185
-     * the current model object's relation to them. If they can't be deleted (because
2186
-     * of blocking related model objects) does nothing. If the related model objects are
2187
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2188
-     * If this model object doesn't exist yet in the DB, just removes its related things
2189
-     *
2190
-     * @param string $relationName
2191
-     * @param array  $query_params like EEM_Base::get_all's
2192
-     * @return int how many deleted
2193
-     * @throws \EE_Error
2194
-     */
2195
-    public function delete_related($relationName, $query_params = array())
2196
-    {
2197
-        if ($this->ID()) {
2198
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2199
-        } else {
2200
-            $count = count($this->get_all_from_cache($relationName));
2201
-            $this->clear_cache($relationName, null, true);
2202
-        }
2203
-        return $count;
2204
-    }
2205
-
2206
-
2207
-
2208
-    /**
2209
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2210
-     * the current model object's relation to them. If they can't be deleted (because
2211
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2212
-     * If the related thing isn't a soft-deletable model object, this function is identical
2213
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2214
-     *
2215
-     * @param string $relationName
2216
-     * @param array  $query_params like EEM_Base::get_all's
2217
-     * @return int how many deleted (including those soft deleted)
2218
-     * @throws \EE_Error
2219
-     */
2220
-    public function delete_related_permanently($relationName, $query_params = array())
2221
-    {
2222
-        if ($this->ID()) {
2223
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2224
-        } else {
2225
-            $count = count($this->get_all_from_cache($relationName));
2226
-        }
2227
-        $this->clear_cache($relationName, null, true);
2228
-        return $count;
2229
-    }
2230
-
2231
-
2232
-
2233
-    /**
2234
-     * is_set
2235
-     * Just a simple utility function children can use for checking if property exists
2236
-     *
2237
-     * @access  public
2238
-     * @param  string $field_name property to check
2239
-     * @return bool                              TRUE if existing,FALSE if not.
2240
-     */
2241
-    public function is_set($field_name)
2242
-    {
2243
-        return isset($this->_fields[$field_name]);
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2250
-     * EE_Error exception if they don't
2251
-     *
2252
-     * @param  mixed (string|array) $properties properties to check
2253
-     * @throws EE_Error
2254
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2255
-     */
2256
-    protected function _property_exists($properties)
2257
-    {
2258
-        foreach ((array)$properties as $property_name) {
2259
-            //first make sure this property exists
2260
-            if ( ! $this->_fields[$property_name]) {
2261
-                throw new EE_Error(
2262
-                    sprintf(
2263
-                        __(
2264
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2265
-                            'event_espresso'
2266
-                        ),
2267
-                        $property_name
2268
-                    )
2269
-                );
2270
-            }
2271
-        }
2272
-        return true;
2273
-    }
2274
-
2275
-
2276
-
2277
-    /**
2278
-     * This simply returns an array of model fields for this object
2279
-     *
2280
-     * @return array
2281
-     * @throws \EE_Error
2282
-     */
2283
-    public function model_field_array()
2284
-    {
2285
-        $fields = $this->get_model()->field_settings(false);
2286
-        $properties = array();
2287
-        //remove prepended underscore
2288
-        foreach ($fields as $field_name => $settings) {
2289
-            $properties[$field_name] = $this->get($field_name);
2290
-        }
2291
-        return $properties;
2292
-    }
2293
-
2294
-
2295
-
2296
-    /**
2297
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2298
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2299
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2300
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2301
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2302
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2303
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2304
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2305
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2306
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2307
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2308
-     *        return $previousReturnValue.$returnString;
2309
-     * }
2310
-     * require('EE_Answer.class.php');
2311
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2312
-     * echo $answer->my_callback('monkeys',100);
2313
-     * //will output "you called my_callback! and passed args:monkeys,100"
2314
-     *
2315
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2316
-     * @param array  $args       array of original arguments passed to the function
2317
-     * @throws EE_Error
2318
-     * @return mixed whatever the plugin which calls add_filter decides
2319
-     */
2320
-    public function __call($methodName, $args)
2321
-    {
2322
-        $className = get_class($this);
2323
-        $tagName = "FHEE__{$className}__{$methodName}";
2324
-        if ( ! has_filter($tagName)) {
2325
-            throw new EE_Error(
2326
-                sprintf(
2327
-                    __(
2328
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2329
-                        "event_espresso"
2330
-                    ),
2331
-                    $methodName,
2332
-                    $className,
2333
-                    $tagName
2334
-                )
2335
-            );
2336
-        }
2337
-        return apply_filters($tagName, null, $this, $args);
2338
-    }
2339
-
2340
-
2341
-
2342
-    /**
2343
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2344
-     * A $previous_value can be specified in case there are many meta rows with the same key
2345
-     *
2346
-     * @param string $meta_key
2347
-     * @param string $meta_value
2348
-     * @param string $previous_value
2349
-     * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2350
-     * @throws \EE_Error
2351
-     * NOTE: if the values haven't changed, returns 0
2352
-     */
2353
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2354
-    {
2355
-        $query_params = array(
2356
-            array(
2357
-                'EXM_key'  => $meta_key,
2358
-                'OBJ_ID'   => $this->ID(),
2359
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2360
-            ),
2361
-        );
2362
-        if ($previous_value !== null) {
2363
-            $query_params[0]['EXM_value'] = $meta_value;
2364
-        }
2365
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2366
-        if ( ! $existing_rows_like_that) {
2367
-            return $this->add_extra_meta($meta_key, $meta_value);
2368
-        } else {
2369
-            foreach ($existing_rows_like_that as $existing_row) {
2370
-                $existing_row->save(array('EXM_value' => $meta_value));
2371
-            }
2372
-            return count($existing_rows_like_that);
2373
-        }
2374
-    }
2375
-
2376
-
2377
-
2378
-    /**
2379
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2380
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2381
-     * extra meta row was entered, false if not
2382
-     *
2383
-     * @param string  $meta_key
2384
-     * @param string  $meta_value
2385
-     * @param boolean $unique
2386
-     * @return boolean
2387
-     * @throws \EE_Error
2388
-     */
2389
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2390
-    {
2391
-        if ($unique) {
2392
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2393
-                array(
2394
-                    array(
2395
-                        'EXM_key'  => $meta_key,
2396
-                        'OBJ_ID'   => $this->ID(),
2397
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2398
-                    ),
2399
-                )
2400
-            );
2401
-            if ($existing_extra_meta) {
2402
-                return false;
2403
-            }
2404
-        }
2405
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2406
-            array(
2407
-                'EXM_key'   => $meta_key,
2408
-                'EXM_value' => $meta_value,
2409
-                'OBJ_ID'    => $this->ID(),
2410
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2411
-            )
2412
-        );
2413
-        $new_extra_meta->save();
2414
-        return true;
2415
-    }
2416
-
2417
-
2418
-
2419
-    /**
2420
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2421
-     * is specified, only deletes extra meta records with that value.
2422
-     *
2423
-     * @param string $meta_key
2424
-     * @param string $meta_value
2425
-     * @return int number of extra meta rows deleted
2426
-     * @throws \EE_Error
2427
-     */
2428
-    public function delete_extra_meta($meta_key, $meta_value = null)
2429
-    {
2430
-        $query_params = array(
2431
-            array(
2432
-                'EXM_key'  => $meta_key,
2433
-                'OBJ_ID'   => $this->ID(),
2434
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2435
-            ),
2436
-        );
2437
-        if ($meta_value !== null) {
2438
-            $query_params[0]['EXM_value'] = $meta_value;
2439
-        }
2440
-        return EEM_Extra_Meta::instance()->delete($query_params);
2441
-    }
2442
-
2443
-
2444
-
2445
-    /**
2446
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2447
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2448
-     * You can specify $default is case you haven't found the extra meta
2449
-     *
2450
-     * @param string  $meta_key
2451
-     * @param boolean $single
2452
-     * @param mixed   $default if we don't find anything, what should we return?
2453
-     * @return mixed single value if $single; array if ! $single
2454
-     * @throws \EE_Error
2455
-     */
2456
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2457
-    {
2458
-        if ($single) {
2459
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2460
-            if ($result instanceof EE_Extra_Meta) {
2461
-                return $result->value();
2462
-            } else {
2463
-                return $default;
2464
-            }
2465
-        } else {
2466
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2467
-            if ($results) {
2468
-                $values = array();
2469
-                foreach ($results as $result) {
2470
-                    if ($result instanceof EE_Extra_Meta) {
2471
-                        $values[$result->ID()] = $result->value();
2472
-                    }
2473
-                }
2474
-                return $values;
2475
-            } else {
2476
-                return $default;
2477
-            }
2478
-        }
2479
-    }
2480
-
2481
-
2482
-
2483
-    /**
2484
-     * Returns a simple array of all the extra meta associated with this model object.
2485
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2486
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2487
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2488
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2489
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2490
-     * finally the extra meta's value as each sub-value. (eg
2491
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2492
-     *
2493
-     * @param boolean $one_of_each_key
2494
-     * @return array
2495
-     * @throws \EE_Error
2496
-     */
2497
-    public function all_extra_meta_array($one_of_each_key = true)
2498
-    {
2499
-        $return_array = array();
2500
-        if ($one_of_each_key) {
2501
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2502
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2503
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2504
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2505
-                }
2506
-            }
2507
-        } else {
2508
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2509
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2510
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2511
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2512
-                        $return_array[$extra_meta_obj->key()] = array();
2513
-                    }
2514
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2515
-                }
2516
-            }
2517
-        }
2518
-        return $return_array;
2519
-    }
2520
-
2521
-
2522
-
2523
-    /**
2524
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2525
-     *
2526
-     * @return string
2527
-     * @throws \EE_Error
2528
-     */
2529
-    public function name()
2530
-    {
2531
-        //find a field that's not a text field
2532
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2533
-        if ($field_we_can_use) {
2534
-            return $this->get($field_we_can_use->get_name());
2535
-        } else {
2536
-            $first_few_properties = $this->model_field_array();
2537
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2538
-            $name_parts = array();
2539
-            foreach ($first_few_properties as $name => $value) {
2540
-                $name_parts[] = "$name:$value";
2541
-            }
2542
-            return implode(",", $name_parts);
2543
-        }
2544
-    }
2545
-
2546
-
2547
-
2548
-    /**
2549
-     * in_entity_map
2550
-     * Checks if this model object has been proven to already be in the entity map
2551
-     *
2552
-     * @return boolean
2553
-     * @throws \EE_Error
2554
-     */
2555
-    public function in_entity_map()
2556
-    {
2557
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2558
-            //well, if we looked, did we find it in the entity map?
2559
-            return true;
2560
-        } else {
2561
-            return false;
2562
-        }
2563
-    }
2564
-
2565
-
2566
-
2567
-    /**
2568
-     * refresh_from_db
2569
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2570
-     *
2571
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2572
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2573
-     */
2574
-    public function refresh_from_db()
2575
-    {
2576
-        if ($this->ID() && $this->in_entity_map()) {
2577
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2578
-        } else {
2579
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2580
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2581
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2582
-            //absolutely nothing in it for this ID
2583
-            if (WP_DEBUG) {
2584
-                throw new EE_Error(
2585
-                    sprintf(
2586
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587
-                            'event_espresso'),
2588
-                        $this->ID(),
2589
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2591
-                    )
2592
-                );
2593
-            }
2594
-        }
2595
-    }
2596
-
2597
-
2598
-
2599
-    /**
2600
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2601
-     * (probably a bad assumption they have made, oh well)
2602
-     *
2603
-     * @return string
2604
-     */
2605
-    public function __toString()
2606
-    {
2607
-        try {
2608
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2609
-        } catch (Exception $e) {
2610
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2611
-            return '';
2612
-        }
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Clear related model objects if they're already in the DB, because otherwise when we
2619
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2620
-     * This means if we have made changes to those related model objects, and want to unserialize
2621
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2622
-     * Instead, those related model objects should be directly serialized and stored.
2623
-     * Eg, the following won't work:
2624
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2625
-     * $att = $reg->attendee();
2626
-     * $att->set( 'ATT_fname', 'Dirk' );
2627
-     * update_option( 'my_option', serialize( $reg ) );
2628
-     * //END REQUEST
2629
-     * //START NEXT REQUEST
2630
-     * $reg = get_option( 'my_option' );
2631
-     * $reg->attendee()->save();
2632
-     * And would need to be replace with:
2633
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2634
-     * $att = $reg->attendee();
2635
-     * $att->set( 'ATT_fname', 'Dirk' );
2636
-     * update_option( 'my_option', serialize( $reg ) );
2637
-     * //END REQUEST
2638
-     * //START NEXT REQUEST
2639
-     * $att = get_option( 'my_option' );
2640
-     * $att->save();
2641
-     *
2642
-     * @return array
2643
-     * @throws \EE_Error
2644
-     */
2645
-    public function __sleep()
2646
-    {
2647
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2650
-                if (
2651
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2652
-                    && $this->get_one_from_cache($relation_name)->ID()
2653
-                ) {
2654
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2655
-                }
2656
-            }
2657
-        }
2658
-        $this->_props_n_values_provided_in_constructor = array();
2659
-        return array_keys(get_object_vars($this));
2660
-    }
2661
-
2662
-
2663
-
2664
-    /**
2665
-     * restore _props_n_values_provided_in_constructor
2666
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2667
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2668
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2669
-     */
2670
-    public function __wakeup()
2671
-    {
2672
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2673
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+
109
+
110
+	/**
111
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
+	 * play nice
113
+	 *
114
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
117
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
+	 *                                                         corresponding db model or not.
119
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
+	 *                                                         be in when instantiating a EE_Base_Class object.
121
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
122
+	 *                                                         value is the date_format and second value is the time
123
+	 *                                                         format.
124
+	 * @throws EE_Error
125
+	 */
126
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
+	{
128
+		$className = get_class($this);
129
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
+		$model = $this->get_model();
131
+		$model_fields = $model->field_settings(false);
132
+		// ensure $fieldValues is an array
133
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
+		// verify client code has not passed any invalid field names
136
+		foreach ($fieldValues as $field_name => $field_value) {
137
+			if ( ! isset($model_fields[$field_name])) {
138
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
+			}
141
+		}
142
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
+		if ( ! empty($date_formats) && is_array($date_formats)) {
145
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
+		} else {
147
+			//set default formats for date and time
148
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
+		}
151
+		//if db model is instantiating
152
+		if ($bydb) {
153
+			//client code has indicated these field values are from the database
154
+			foreach ($model_fields as $fieldName => $field) {
155
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
+			}
157
+		} else {
158
+			//we're constructing a brand
159
+			//new instance of the model object. Generally, this means we'll need to do more field validation
160
+			foreach ($model_fields as $fieldName => $field) {
161
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
+			}
163
+		}
164
+		//remember what values were passed to this constructor
165
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
166
+		//remember in entity mapper
167
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
+			$model->add_to_entity_map($this);
169
+		}
170
+		//setup all the relations
171
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
+				$this->_model_relations[$relation_name] = null;
174
+			} else {
175
+				$this->_model_relations[$relation_name] = array();
176
+			}
177
+		}
178
+		/**
179
+		 * Action done at the end of each model object construction
180
+		 *
181
+		 * @param EE_Base_Class $this the model object just created
182
+		 */
183
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
190
+	 *
191
+	 * @return boolean
192
+	 */
193
+	public function allow_persist()
194
+	{
195
+		return $this->_allow_persist;
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
202
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
+	 * you got new information that somehow made you change your mind.
204
+	 *
205
+	 * @param boolean $allow_persist
206
+	 * @return boolean
207
+	 */
208
+	public function set_allow_persist($allow_persist)
209
+	{
210
+		return $this->_allow_persist = $allow_persist;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * Gets the field's original value when this object was constructed during this request.
217
+	 * This can be helpful when determining if a model object has changed or not
218
+	 *
219
+	 * @param string $field_name
220
+	 * @return mixed|null
221
+	 * @throws \EE_Error
222
+	 */
223
+	public function get_original($field_name)
224
+	{
225
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
227
+		) {
228
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
+		} else {
230
+			return null;
231
+		}
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * @param EE_Base_Class $obj
238
+	 * @return string
239
+	 */
240
+	public function get_class($obj)
241
+	{
242
+		return get_class($obj);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * Overrides parent because parent expects old models.
249
+	 * This also doesn't do any validation, and won't work for serialized arrays
250
+	 *
251
+	 * @param    string $field_name
252
+	 * @param    mixed  $field_value
253
+	 * @param bool      $use_default
254
+	 * @throws \EE_Error
255
+	 */
256
+	public function set($field_name, $field_value, $use_default = false)
257
+	{
258
+		$field_obj = $this->get_model()->field_settings_for($field_name);
259
+		if ($field_obj instanceof EE_Model_Field_Base) {
260
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
261
+			if ($field_obj instanceof EE_Datetime_Field) {
262
+				$field_obj->set_timezone($this->_timezone);
263
+				$field_obj->set_date_format($this->_dt_frmt);
264
+				$field_obj->set_time_format($this->_tm_frmt);
265
+			}
266
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
267
+			//should the value be null?
268
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
+				$this->_fields[$field_name] = $field_obj->get_default_value();
270
+				/**
271
+				 * To save having to refactor all the models, if a default value is used for a
272
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
+				 * object.
275
+				 *
276
+				 * @since 4.6.10+
277
+				 */
278
+				if (
279
+					$field_obj instanceof EE_Datetime_Field
280
+					&& $this->_fields[$field_name] !== null
281
+					&& ! $this->_fields[$field_name] instanceof DateTime
282
+				) {
283
+					empty($this->_fields[$field_name])
284
+						? $this->set($field_name, time())
285
+						: $this->set($field_name, $this->_fields[$field_name]);
286
+				}
287
+			} else {
288
+				$this->_fields[$field_name] = $holder_of_value;
289
+			}
290
+			//if we're not in the constructor...
291
+			//now check if what we set was a primary key
292
+			if (
293
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
+				$this->_props_n_values_provided_in_constructor
295
+				&& $field_value
296
+				&& $field_name === self::_get_primary_key_name(get_class($this))
297
+			) {
298
+				//if so, we want all this object's fields to be filled either with
299
+				//what we've explicitly set on this model
300
+				//or what we have in the db
301
+				// echo "setting primary key!";
302
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
303
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
+				foreach ($fields_on_model as $field_obj) {
305
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
+						 && $field_obj->get_name() !== $field_name
307
+					) {
308
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
+					}
310
+				}
311
+				//oh this model object has an ID? well make sure its in the entity mapper
312
+				$this->get_model()->add_to_entity_map($this);
313
+			}
314
+			//let's unset any cache for this field_name from the $_cached_properties property.
315
+			$this->_clear_cached_property($field_name);
316
+		} else {
317
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
+				"event_espresso"), $field_name));
319
+		}
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * This sets the field value on the db column if it exists for the given $column_name or
326
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
+	 *
328
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
+	 * @param string $field_name  Must be the exact column name.
330
+	 * @param mixed  $field_value The value to set.
331
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
+	 * @throws \EE_Error
333
+	 */
334
+	public function set_field_or_extra_meta($field_name, $field_value)
335
+	{
336
+		if ($this->get_model()->has_field($field_name)) {
337
+			$this->set($field_name, $field_value);
338
+			return true;
339
+		} else {
340
+			//ensure this object is saved first so that extra meta can be properly related.
341
+			$this->save();
342
+			return $this->update_extra_meta($field_name, $field_value);
343
+		}
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * This retrieves the value of the db column set on this class or if that's not present
350
+	 * it will attempt to retrieve from extra_meta if found.
351
+	 * Example Usage:
352
+	 * Via EE_Message child class:
353
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
356
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
+	 * value for those extra fields dynamically via the EE_message object.
358
+	 *
359
+	 * @param  string $field_name expecting the fully qualified field name.
360
+	 * @return mixed|null  value for the field if found.  null if not found.
361
+	 * @throws \EE_Error
362
+	 */
363
+	public function get_field_or_extra_meta($field_name)
364
+	{
365
+		if ($this->get_model()->has_field($field_name)) {
366
+			$column_value = $this->get($field_name);
367
+		} else {
368
+			//This isn't a column in the main table, let's see if it is in the extra meta.
369
+			$column_value = $this->get_extra_meta($field_name, true, null);
370
+		}
371
+		return $column_value;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
+	 *
382
+	 * @access public
383
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
+	 * @return void
385
+	 * @throws \EE_Error
386
+	 */
387
+	public function set_timezone($timezone = '')
388
+	{
389
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
+		//make sure we clear all cached properties because they won't be relevant now
391
+		$this->_clear_cached_properties();
392
+		//make sure we update field settings and the date for all EE_Datetime_Fields
393
+		$model_fields = $this->get_model()->field_settings(false);
394
+		foreach ($model_fields as $field_name => $field_obj) {
395
+			if ($field_obj instanceof EE_Datetime_Field) {
396
+				$field_obj->set_timezone($this->_timezone);
397
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
+				}
400
+			}
401
+		}
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * This just returns whatever is set for the current timezone.
408
+	 *
409
+	 * @access public
410
+	 * @return string timezone string
411
+	 */
412
+	public function get_timezone()
413
+	{
414
+		return $this->_timezone;
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
421
+	 * internally instead of wp set date format options
422
+	 *
423
+	 * @since 4.6
424
+	 * @param string $format should be a format recognizable by PHP date() functions.
425
+	 */
426
+	public function set_date_format($format)
427
+	{
428
+		$this->_dt_frmt = $format;
429
+		//clear cached_properties because they won't be relevant now.
430
+		$this->_clear_cached_properties();
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
437
+	 * class internally instead of wp set time format options.
438
+	 *
439
+	 * @since 4.6
440
+	 * @param string $format should be a format recognizable by PHP date() functions.
441
+	 */
442
+	public function set_time_format($format)
443
+	{
444
+		$this->_tm_frmt = $format;
445
+		//clear cached_properties because they won't be relevant now.
446
+		$this->_clear_cached_properties();
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * This returns the current internal set format for the date and time formats.
453
+	 *
454
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
+	 *                             where the first value is the date format and the second value is the time format.
456
+	 * @return mixed string|array
457
+	 */
458
+	public function get_format($full = true)
459
+	{
460
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
+	}
462
+
463
+
464
+
465
+	/**
466
+	 * cache
467
+	 * stores the passed model object on the current model object.
468
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
+	 *
470
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
+	 *                                       'Registration' associated with this model object
472
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
+	 *                                       that could be a payment or a registration)
474
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
+	 *                                       items which will be stored in an array on this object
476
+	 * @throws EE_Error
477
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
+	 *                  related thing, no array)
479
+	 */
480
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
+	{
482
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
484
+			return false;
485
+		}
486
+		// also get "how" the object is related, or throw an error
487
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
+				$relationName, get_class($this)));
490
+		}
491
+		// how many things are related ?
492
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
+			// so for these model objects just set it to be cached
495
+			$this->_model_relations[$relationName] = $object_to_cache;
496
+			$return = true;
497
+		} else {
498
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
+			if ( ! is_array($this->_model_relations[$relationName])) {
501
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
+					? array($this->_model_relations[$relationName]) : array();
504
+			}
505
+			// first check for a cache_id which is normally empty
506
+			if ( ! empty($cache_id)) {
507
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
+				$return = $cache_id;
510
+			} elseif ($object_to_cache->ID()) {
511
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
512
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
+				$return = $object_to_cache->ID();
514
+			} else {
515
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
+				$this->_model_relations[$relationName][] = $object_to_cache;
517
+				// move the internal pointer to the end of the array
518
+				end($this->_model_relations[$relationName]);
519
+				// and grab the key so that we can return it
520
+				$return = key($this->_model_relations[$relationName]);
521
+			}
522
+		}
523
+		return $return;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * For adding an item to the cached_properties property.
530
+	 *
531
+	 * @access protected
532
+	 * @param string      $fieldname the property item the corresponding value is for.
533
+	 * @param mixed       $value     The value we are caching.
534
+	 * @param string|null $cache_type
535
+	 * @return void
536
+	 * @throws \EE_Error
537
+	 */
538
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
+	{
540
+		//first make sure this property exists
541
+		$this->get_model()->field_settings_for($fieldname);
542
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
544
+	}
545
+
546
+
547
+
548
+	/**
549
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
+	 * This also SETS the cache if we return the actual property!
551
+	 *
552
+	 * @param string $fieldname        the name of the property we're trying to retrieve
553
+	 * @param bool   $pretty
554
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
+	 *                                 (in cases where the same property may be used for different outputs
556
+	 *                                 - i.e. datetime, money etc.)
557
+	 *                                 It can also accept certain pre-defined "schema" strings
558
+	 *                                 to define how to output the property.
559
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
+	 * @return mixed                   whatever the value for the property is we're retrieving
561
+	 * @throws \EE_Error
562
+	 */
563
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
+	{
565
+		//verify the field exists
566
+		$this->get_model()->field_settings_for($fieldname);
567
+		$cache_type = $pretty ? 'pretty' : 'standard';
568
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
+			return $this->_cached_properties[$fieldname][$cache_type];
571
+		}
572
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
573
+		if ($field_obj instanceof EE_Model_Field_Base) {
574
+			// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
575
+			if ($field_obj instanceof EE_Datetime_Field) {
576
+				$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
577
+			}
578
+			if ( ! isset($this->_fields[$fieldname])) {
579
+				$this->_fields[$fieldname] = null;
580
+			}
581
+			$value = $pretty
582
+				? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
583
+				: $field_obj->prepare_for_get($this->_fields[$fieldname]);
584
+			$this->_set_cached_property($fieldname, $value, $cache_type);
585
+			return $value;
586
+		}
587
+		return null;
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * set timezone, formats, and output for EE_Datetime_Field objects
594
+	 *
595
+	 * @param \EE_Datetime_Field $datetime_field
596
+	 * @param bool               $pretty
597
+	 * @param null $date_or_time
598
+	 * @return void
599
+	 * @throws \EE_Error
600
+	 */
601
+	protected function _prepare_datetime_field(
602
+		EE_Datetime_Field $datetime_field,
603
+		$pretty = false,
604
+		$date_or_time = null
605
+	) {
606
+		$datetime_field->set_timezone($this->_timezone);
607
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
608
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
609
+		//set the output returned
610
+		switch ($date_or_time) {
611
+			case 'D' :
612
+				$datetime_field->set_date_time_output('date');
613
+				break;
614
+			case 'T' :
615
+				$datetime_field->set_date_time_output('time');
616
+				break;
617
+			default :
618
+				$datetime_field->set_date_time_output();
619
+		}
620
+	}
621
+
622
+
623
+
624
+	/**
625
+	 * This just takes care of clearing out the cached_properties
626
+	 *
627
+	 * @return void
628
+	 */
629
+	protected function _clear_cached_properties()
630
+	{
631
+		$this->_cached_properties = array();
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * This just clears out ONE property if it exists in the cache
638
+	 *
639
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
640
+	 * @return void
641
+	 */
642
+	protected function _clear_cached_property($property_name)
643
+	{
644
+		if (isset($this->_cached_properties[$property_name])) {
645
+			unset($this->_cached_properties[$property_name]);
646
+		}
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * Ensures that this related thing is a model object.
653
+	 *
654
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
655
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
656
+	 * @return EE_Base_Class
657
+	 * @throws \EE_Error
658
+	 */
659
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
660
+	{
661
+		$other_model_instance = self::_get_model_instance_with_name(
662
+			self::_get_model_classname($model_name),
663
+			$this->_timezone
664
+		);
665
+		return $other_model_instance->ensure_is_obj($object_or_id);
666
+	}
667
+
668
+
669
+
670
+	/**
671
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
672
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
673
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
674
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
675
+	 *
676
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
677
+	 *                                                     Eg 'Registration'
678
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
679
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
680
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
681
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
682
+	 *                                                     this is HasMany or HABTM.
683
+	 * @throws EE_Error
684
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
685
+	 *                       relation from all
686
+	 */
687
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
688
+	{
689
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
690
+		$index_in_cache = '';
691
+		if ( ! $relationship_to_model) {
692
+			throw new EE_Error(
693
+				sprintf(
694
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
695
+					$relationName,
696
+					get_class($this)
697
+				)
698
+			);
699
+		}
700
+		if ($clear_all) {
701
+			$obj_removed = true;
702
+			$this->_model_relations[$relationName] = null;
703
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
704
+			$obj_removed = $this->_model_relations[$relationName];
705
+			$this->_model_relations[$relationName] = null;
706
+		} else {
707
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
708
+				&& $object_to_remove_or_index_into_array->ID()
709
+			) {
710
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
711
+				if (is_array($this->_model_relations[$relationName])
712
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
713
+				) {
714
+					$index_found_at = null;
715
+					//find this object in the array even though it has a different key
716
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
717
+						if (
718
+							$obj instanceof EE_Base_Class
719
+							&& (
720
+								$obj == $object_to_remove_or_index_into_array
721
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
722
+							)
723
+						) {
724
+							$index_found_at = $index;
725
+							break;
726
+						}
727
+					}
728
+					if ($index_found_at) {
729
+						$index_in_cache = $index_found_at;
730
+					} else {
731
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
732
+						//if it wasn't in it to begin with. So we're done
733
+						return $object_to_remove_or_index_into_array;
734
+					}
735
+				}
736
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
737
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
738
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
739
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
740
+						$index_in_cache = $index;
741
+					}
742
+				}
743
+			} else {
744
+				$index_in_cache = $object_to_remove_or_index_into_array;
745
+			}
746
+			//supposedly we've found it. But it could just be that the client code
747
+			//provided a bad index/object
748
+			if (
749
+			isset(
750
+				$this->_model_relations[$relationName],
751
+				$this->_model_relations[$relationName][$index_in_cache]
752
+			)
753
+			) {
754
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
755
+				unset($this->_model_relations[$relationName][$index_in_cache]);
756
+			} else {
757
+				//that thing was never cached anyways.
758
+				$obj_removed = null;
759
+			}
760
+		}
761
+		return $obj_removed;
762
+	}
763
+
764
+
765
+
766
+	/**
767
+	 * update_cache_after_object_save
768
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
769
+	 * obtained after being saved to the db
770
+	 *
771
+	 * @param string         $relationName       - the type of object that is cached
772
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
773
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
774
+	 * @return boolean TRUE on success, FALSE on fail
775
+	 * @throws \EE_Error
776
+	 */
777
+	public function update_cache_after_object_save(
778
+		$relationName,
779
+		EE_Base_Class $newly_saved_object,
780
+		$current_cache_id = ''
781
+	) {
782
+		// verify that incoming object is of the correct type
783
+		$obj_class = 'EE_' . $relationName;
784
+		if ($newly_saved_object instanceof $obj_class) {
785
+			/* @type EE_Base_Class $newly_saved_object */
786
+			// now get the type of relation
787
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
788
+			// if this is a 1:1 relationship
789
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
790
+				// then just replace the cached object with the newly saved object
791
+				$this->_model_relations[$relationName] = $newly_saved_object;
792
+				return true;
793
+				// or if it's some kind of sordid feral polyamorous relationship...
794
+			} elseif (is_array($this->_model_relations[$relationName])
795
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
796
+			) {
797
+				// then remove the current cached item
798
+				unset($this->_model_relations[$relationName][$current_cache_id]);
799
+				// and cache the newly saved object using it's new ID
800
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
801
+				return true;
802
+			}
803
+		}
804
+		return false;
805
+	}
806
+
807
+
808
+
809
+	/**
810
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
811
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
812
+	 *
813
+	 * @param string $relationName
814
+	 * @return EE_Base_Class
815
+	 */
816
+	public function get_one_from_cache($relationName)
817
+	{
818
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
819
+			: null;
820
+		if (is_array($cached_array_or_object)) {
821
+			return array_shift($cached_array_or_object);
822
+		} else {
823
+			return $cached_array_or_object;
824
+		}
825
+	}
826
+
827
+
828
+
829
+	/**
830
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
831
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
832
+	 *
833
+	 * @param string $relationName
834
+	 * @throws \EE_Error
835
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
836
+	 */
837
+	public function get_all_from_cache($relationName)
838
+	{
839
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
840
+		// if the result is not an array, but exists, make it an array
841
+		$objects = is_array($objects) ? $objects : array($objects);
842
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
843
+		//basically, if this model object was stored in the session, and these cached model objects
844
+		//already have IDs, let's make sure they're in their model's entity mapper
845
+		//otherwise we will have duplicates next time we call
846
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
847
+		$model = EE_Registry::instance()->load_model($relationName);
848
+		foreach ($objects as $model_object) {
849
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
850
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
851
+				if ($model_object->ID()) {
852
+					$model->add_to_entity_map($model_object);
853
+				}
854
+			} else {
855
+				throw new EE_Error(
856
+					sprintf(
857
+						__(
858
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
859
+							'event_espresso'
860
+						),
861
+						$relationName,
862
+						gettype($model_object)
863
+					)
864
+				);
865
+			}
866
+		}
867
+		return $objects;
868
+	}
869
+
870
+
871
+
872
+	/**
873
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
874
+	 * matching the given query conditions.
875
+	 *
876
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
877
+	 * @param int   $limit              How many objects to return.
878
+	 * @param array $query_params       Any additional conditions on the query.
879
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
880
+	 *                                  you can indicate just the columns you want returned
881
+	 * @return array|EE_Base_Class[]
882
+	 * @throws \EE_Error
883
+	 */
884
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
885
+	{
886
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
887
+			? $this->get_model()->get_primary_key_field()->get_name()
888
+			: $field_to_order_by;
889
+		$current_value = ! empty($field) ? $this->get($field) : null;
890
+		if (empty($field) || empty($current_value)) {
891
+			return array();
892
+		}
893
+		return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
894
+	}
895
+
896
+
897
+
898
+	/**
899
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
900
+	 * matching the given query conditions.
901
+	 *
902
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
903
+	 * @param int   $limit              How many objects to return.
904
+	 * @param array $query_params       Any additional conditions on the query.
905
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
906
+	 *                                  you can indicate just the columns you want returned
907
+	 * @return array|EE_Base_Class[]
908
+	 * @throws \EE_Error
909
+	 */
910
+	public function previous_x(
911
+		$field_to_order_by = null,
912
+		$limit = 1,
913
+		$query_params = array(),
914
+		$columns_to_select = null
915
+	) {
916
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
917
+			? $this->get_model()->get_primary_key_field()->get_name()
918
+			: $field_to_order_by;
919
+		$current_value = ! empty($field) ? $this->get($field) : null;
920
+		if (empty($field) || empty($current_value)) {
921
+			return array();
922
+		}
923
+		return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
930
+	 * matching the given query conditions.
931
+	 *
932
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
933
+	 * @param array $query_params       Any additional conditions on the query.
934
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
935
+	 *                                  you can indicate just the columns you want returned
936
+	 * @return array|EE_Base_Class
937
+	 * @throws \EE_Error
938
+	 */
939
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
940
+	{
941
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
942
+			? $this->get_model()->get_primary_key_field()->get_name()
943
+			: $field_to_order_by;
944
+		$current_value = ! empty($field) ? $this->get($field) : null;
945
+		if (empty($field) || empty($current_value)) {
946
+			return array();
947
+		}
948
+		return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
955
+	 * matching the given query conditions.
956
+	 *
957
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
958
+	 * @param array $query_params       Any additional conditions on the query.
959
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
960
+	 *                                  you can indicate just the column you want returned
961
+	 * @return array|EE_Base_Class
962
+	 * @throws \EE_Error
963
+	 */
964
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
965
+	{
966
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
967
+			? $this->get_model()->get_primary_key_field()->get_name()
968
+			: $field_to_order_by;
969
+		$current_value = ! empty($field) ? $this->get($field) : null;
970
+		if (empty($field) || empty($current_value)) {
971
+			return array();
972
+		}
973
+		return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
974
+	}
975
+
976
+
977
+
978
+	/**
979
+	 * Overrides parent because parent expects old models.
980
+	 * This also doesn't do any validation, and won't work for serialized arrays
981
+	 *
982
+	 * @param string $field_name
983
+	 * @param mixed  $field_value_from_db
984
+	 * @throws \EE_Error
985
+	 */
986
+	public function set_from_db($field_name, $field_value_from_db)
987
+	{
988
+		$field_obj = $this->get_model()->field_settings_for($field_name);
989
+		if ($field_obj instanceof EE_Model_Field_Base) {
990
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
991
+			//eg, a CPT model object could have an entry in the posts table, but no
992
+			//entry in the meta table. Meaning that all its columns in the meta table
993
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
994
+			if ($field_value_from_db === null) {
995
+				if ($field_obj->is_nullable()) {
996
+					//if the field allows nulls, then let it be null
997
+					$field_value = null;
998
+				} else {
999
+					$field_value = $field_obj->get_default_value();
1000
+				}
1001
+			} else {
1002
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1003
+			}
1004
+			$this->_fields[$field_name] = $field_value;
1005
+			$this->_clear_cached_property($field_name);
1006
+		}
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 * verifies that the specified field is of the correct type
1013
+	 *
1014
+	 * @param string $field_name
1015
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1016
+	 *                                (in cases where the same property may be used for different outputs
1017
+	 *                                - i.e. datetime, money etc.)
1018
+	 * @return mixed
1019
+	 * @throws \EE_Error
1020
+	 */
1021
+	public function get($field_name, $extra_cache_ref = null)
1022
+	{
1023
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1030
+	 *
1031
+	 * @param  string $field_name A valid fieldname
1032
+	 * @return mixed              Whatever the raw value stored on the property is.
1033
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1034
+	 */
1035
+	public function get_raw($field_name)
1036
+	{
1037
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1038
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1039
+			? $this->_fields[$field_name]->format('U')
1040
+			: $this->_fields[$field_name];
1041
+	}
1042
+
1043
+
1044
+
1045
+	/**
1046
+	 * This is used to return the internal DateTime object used for a field that is a
1047
+	 * EE_Datetime_Field.
1048
+	 *
1049
+	 * @param string $field_name               The field name retrieving the DateTime object.
1050
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1051
+	 * @throws \EE_Error
1052
+	 *                                         an error is set and false returned.  If the field IS an
1053
+	 *                                         EE_Datetime_Field and but the field value is null, then
1054
+	 *                                         just null is returned (because that indicates that likely
1055
+	 *                                         this field is nullable).
1056
+	 */
1057
+	public function get_DateTime_object($field_name)
1058
+	{
1059
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1060
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1061
+			EE_Error::add_error(
1062
+				sprintf(
1063
+					__(
1064
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1065
+						'event_espresso'
1066
+					),
1067
+					$field_name
1068
+				),
1069
+				__FILE__,
1070
+				__FUNCTION__,
1071
+				__LINE__
1072
+			);
1073
+			return false;
1074
+		}
1075
+		return $this->_fields[$field_name];
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * To be used in template to immediately echo out the value, and format it for output.
1082
+	 * Eg, should call stripslashes and whatnot before echoing
1083
+	 *
1084
+	 * @param string $field_name      the name of the field as it appears in the DB
1085
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1086
+	 *                                (in cases where the same property may be used for different outputs
1087
+	 *                                - i.e. datetime, money etc.)
1088
+	 * @return void
1089
+	 * @throws \EE_Error
1090
+	 */
1091
+	public function e($field_name, $extra_cache_ref = null)
1092
+	{
1093
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1100
+	 * can be easily used as the value of form input.
1101
+	 *
1102
+	 * @param string $field_name
1103
+	 * @return void
1104
+	 * @throws \EE_Error
1105
+	 */
1106
+	public function f($field_name)
1107
+	{
1108
+		$this->e($field_name, 'form_input');
1109
+	}
1110
+
1111
+
1112
+
1113
+	/**
1114
+	 * @param string $field_name
1115
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1116
+	 *                                (in cases where the same property may be used for different outputs
1117
+	 *                                - i.e. datetime, money etc.)
1118
+	 * @return mixed
1119
+	 * @throws \EE_Error
1120
+	 */
1121
+	public function get_pretty($field_name, $extra_cache_ref = null)
1122
+	{
1123
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * This simply returns the datetime for the given field name
1130
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1131
+	 * (and the equivalent e_date, e_time, e_datetime).
1132
+	 *
1133
+	 * @access   protected
1134
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1135
+	 * @param string   $dt_frmt      valid datetime format used for date
1136
+	 *                               (if '' then we just use the default on the field,
1137
+	 *                               if NULL we use the last-used format)
1138
+	 * @param string   $tm_frmt      Same as above except this is for time format
1139
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1140
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1141
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1142
+	 *                               if field is not a valid dtt field, or void if echoing
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1146
+	{
1147
+		// clear cached property
1148
+		$this->_clear_cached_property($field_name);
1149
+		//reset format properties because they are used in get()
1150
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1151
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1152
+		if ($echo) {
1153
+			$this->e($field_name, $date_or_time);
1154
+			return '';
1155
+		}
1156
+		return $this->get($field_name, $date_or_time);
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1163
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1164
+	 * other echoes the pretty value for dtt)
1165
+	 *
1166
+	 * @param  string $field_name name of model object datetime field holding the value
1167
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1168
+	 * @return string            datetime value formatted
1169
+	 * @throws \EE_Error
1170
+	 */
1171
+	public function get_date($field_name, $format = '')
1172
+	{
1173
+		return $this->_get_datetime($field_name, $format, null, 'D');
1174
+	}
1175
+
1176
+
1177
+
1178
+	/**
1179
+	 * @param      $field_name
1180
+	 * @param string $format
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function e_date($field_name, $format = '')
1184
+	{
1185
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1186
+	}
1187
+
1188
+
1189
+
1190
+	/**
1191
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1192
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1193
+	 * other echoes the pretty value for dtt)
1194
+	 *
1195
+	 * @param  string $field_name name of model object datetime field holding the value
1196
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1197
+	 * @return string             datetime value formatted
1198
+	 * @throws \EE_Error
1199
+	 */
1200
+	public function get_time($field_name, $format = '')
1201
+	{
1202
+		return $this->_get_datetime($field_name, null, $format, 'T');
1203
+	}
1204
+
1205
+
1206
+
1207
+	/**
1208
+	 * @param      $field_name
1209
+	 * @param string $format
1210
+	 * @throws \EE_Error
1211
+	 */
1212
+	public function e_time($field_name, $format = '')
1213
+	{
1214
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1215
+	}
1216
+
1217
+
1218
+
1219
+	/**
1220
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1221
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1222
+	 * other echoes the pretty value for dtt)
1223
+	 *
1224
+	 * @param  string $field_name name of model object datetime field holding the value
1225
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1226
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1227
+	 * @return string             datetime value formatted
1228
+	 * @throws \EE_Error
1229
+	 */
1230
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1231
+	{
1232
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1233
+	}
1234
+
1235
+
1236
+
1237
+	/**
1238
+	 * @param string $field_name
1239
+	 * @param string $dt_frmt
1240
+	 * @param string $tm_frmt
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1244
+	{
1245
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1246
+	}
1247
+
1248
+
1249
+
1250
+	/**
1251
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1252
+	 *
1253
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1254
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1255
+	 *                           on the object will be used.
1256
+	 * @return string Date and time string in set locale or false if no field exists for the given
1257
+	 * @throws \EE_Error
1258
+	 *                           field name.
1259
+	 */
1260
+	public function get_i18n_datetime($field_name, $format = '')
1261
+	{
1262
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1263
+		return date_i18n(
1264
+			$format,
1265
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1266
+		);
1267
+	}
1268
+
1269
+
1270
+
1271
+	/**
1272
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1273
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1274
+	 * thrown.
1275
+	 *
1276
+	 * @param  string $field_name The field name being checked
1277
+	 * @throws EE_Error
1278
+	 * @return EE_Datetime_Field
1279
+	 */
1280
+	protected function _get_dtt_field_settings($field_name)
1281
+	{
1282
+		$field = $this->get_model()->field_settings_for($field_name);
1283
+		//check if field is dtt
1284
+		if ($field instanceof EE_Datetime_Field) {
1285
+			return $field;
1286
+		} else {
1287
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1288
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1289
+		}
1290
+	}
1291
+
1292
+
1293
+
1294
+
1295
+	/**
1296
+	 * NOTE ABOUT BELOW:
1297
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1298
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1299
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1300
+	 * method and make sure you send the entire datetime value for setting.
1301
+	 */
1302
+	/**
1303
+	 * sets the time on a datetime property
1304
+	 *
1305
+	 * @access protected
1306
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1307
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1308
+	 * @throws \EE_Error
1309
+	 */
1310
+	protected function _set_time_for($time, $fieldname)
1311
+	{
1312
+		$this->_set_date_time('T', $time, $fieldname);
1313
+	}
1314
+
1315
+
1316
+
1317
+	/**
1318
+	 * sets the date on a datetime property
1319
+	 *
1320
+	 * @access protected
1321
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1322
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1323
+	 * @throws \EE_Error
1324
+	 */
1325
+	protected function _set_date_for($date, $fieldname)
1326
+	{
1327
+		$this->_set_date_time('D', $date, $fieldname);
1328
+	}
1329
+
1330
+
1331
+
1332
+	/**
1333
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1334
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1335
+	 *
1336
+	 * @access protected
1337
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1338
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1339
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1340
+	 *                                        EE_Datetime_Field property)
1341
+	 * @throws \EE_Error
1342
+	 */
1343
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1344
+	{
1345
+		$field = $this->_get_dtt_field_settings($fieldname);
1346
+		$field->set_timezone($this->_timezone);
1347
+		$field->set_date_format($this->_dt_frmt);
1348
+		$field->set_time_format($this->_tm_frmt);
1349
+		switch ($what) {
1350
+			case 'T' :
1351
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1352
+					$datetime_value,
1353
+					$this->_fields[$fieldname]
1354
+				);
1355
+				break;
1356
+			case 'D' :
1357
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1358
+					$datetime_value,
1359
+					$this->_fields[$fieldname]
1360
+				);
1361
+				break;
1362
+			case 'B' :
1363
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1364
+				break;
1365
+		}
1366
+		$this->_clear_cached_property($fieldname);
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1373
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1374
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1375
+	 * that could lead to some unexpected results!
1376
+	 *
1377
+	 * @access public
1378
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1379
+	 *                                         value being returned.
1380
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1381
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1382
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1383
+	 * @param string               $append     You can include something to append on the timestamp
1384
+	 * @throws EE_Error
1385
+	 * @return string timestamp
1386
+	 */
1387
+	public function display_in_my_timezone(
1388
+		$field_name,
1389
+		$callback = 'get_datetime',
1390
+		$args = null,
1391
+		$prepend = '',
1392
+		$append = ''
1393
+	) {
1394
+		$timezone = EEH_DTT_Helper::get_timezone();
1395
+		if ($timezone === $this->_timezone) {
1396
+			return '';
1397
+		}
1398
+		$original_timezone = $this->_timezone;
1399
+		$this->set_timezone($timezone);
1400
+		$fn = (array)$field_name;
1401
+		$args = array_merge($fn, (array)$args);
1402
+		if ( ! method_exists($this, $callback)) {
1403
+			throw new EE_Error(
1404
+				sprintf(
1405
+					__(
1406
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1407
+						'event_espresso'
1408
+					),
1409
+					$callback
1410
+				)
1411
+			);
1412
+		}
1413
+		$args = (array)$args;
1414
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1415
+		$this->set_timezone($original_timezone);
1416
+		return $return;
1417
+	}
1418
+
1419
+
1420
+
1421
+	/**
1422
+	 * Deletes this model object.
1423
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1424
+	 * override
1425
+	 * `EE_Base_Class::_delete` NOT this class.
1426
+	 *
1427
+	 * @return boolean | int
1428
+	 * @throws \EE_Error
1429
+	 */
1430
+	public function delete()
1431
+	{
1432
+		/**
1433
+		 * Called just before the `EE_Base_Class::_delete` method call.
1434
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1435
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1436
+		 * soft deletes (trash) the object and does not permanently delete it.
1437
+		 *
1438
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1439
+		 */
1440
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1441
+		$result = $this->_delete();
1442
+		/**
1443
+		 * Called just after the `EE_Base_Class::_delete` method call.
1444
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1445
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1446
+		 * soft deletes (trash) the object and does not permanently delete it.
1447
+		 *
1448
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1449
+		 * @param boolean       $result
1450
+		 */
1451
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1452
+		return $result;
1453
+	}
1454
+
1455
+
1456
+
1457
+	/**
1458
+	 * Calls the specific delete method for the instantiated class.
1459
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1460
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1461
+	 * `EE_Base_Class::delete`
1462
+	 *
1463
+	 * @return bool|int
1464
+	 * @throws \EE_Error
1465
+	 */
1466
+	protected function _delete()
1467
+	{
1468
+		return $this->delete_permanently();
1469
+	}
1470
+
1471
+
1472
+
1473
+	/**
1474
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1475
+	 * error)
1476
+	 *
1477
+	 * @return bool | int
1478
+	 * @throws \EE_Error
1479
+	 */
1480
+	public function delete_permanently()
1481
+	{
1482
+		/**
1483
+		 * Called just before HARD deleting a model object
1484
+		 *
1485
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1486
+		 */
1487
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1488
+		$model = $this->get_model();
1489
+		$result = $model->delete_permanently_by_ID($this->ID());
1490
+		$this->refresh_cache_of_related_objects();
1491
+		/**
1492
+		 * Called just after HARD deleting a model object
1493
+		 *
1494
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1495
+		 * @param boolean       $result
1496
+		 */
1497
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1498
+		return $result;
1499
+	}
1500
+
1501
+
1502
+
1503
+	/**
1504
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1505
+	 * related model objects
1506
+	 *
1507
+	 * @throws \EE_Error
1508
+	 */
1509
+	public function refresh_cache_of_related_objects()
1510
+	{
1511
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1512
+			if ( ! empty($this->_model_relations[$relation_name])) {
1513
+				$related_objects = $this->_model_relations[$relation_name];
1514
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1515
+					//this relation only stores a single model object, not an array
1516
+					//but let's make it consistent
1517
+					$related_objects = array($related_objects);
1518
+				}
1519
+				foreach ($related_objects as $related_object) {
1520
+					//only refresh their cache if they're in memory
1521
+					if ($related_object instanceof EE_Base_Class) {
1522
+						$related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1523
+					}
1524
+				}
1525
+			}
1526
+		}
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1533
+	 * object just before saving.
1534
+	 *
1535
+	 * @access public
1536
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1537
+	 *                                 if provided during the save() method (often client code will change the fields'
1538
+	 *                                 values before calling save)
1539
+	 * @throws \EE_Error
1540
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1541
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1542
+	 */
1543
+	public function save($set_cols_n_values = array())
1544
+	{
1545
+		/**
1546
+		 * Filters the fields we're about to save on the model object
1547
+		 *
1548
+		 * @param array         $set_cols_n_values
1549
+		 * @param EE_Base_Class $model_object
1550
+		 */
1551
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552
+			$this);
1553
+		//set attributes as provided in $set_cols_n_values
1554
+		foreach ($set_cols_n_values as $column => $value) {
1555
+			$this->set($column, $value);
1556
+		}
1557
+		/**
1558
+		 * Saving a model object.
1559
+		 * Before we perform a save, this action is fired.
1560
+		 *
1561
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1562
+		 */
1563
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1564
+		if ( ! $this->allow_persist()) {
1565
+			return 0;
1566
+		}
1567
+		//now get current attribute values
1568
+		$save_cols_n_values = $this->_fields;
1569
+		//if the object already has an ID, update it. Otherwise, insert it
1570
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1571
+		$old_assumption_concerning_value_preparation = $this->get_model()
1572
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1573
+		$this->get_model()->assume_values_already_prepared_by_model_object(true);
1574
+		//does this model have an autoincrement PK?
1575
+		if ($this->get_model()->has_primary_key_field()) {
1576
+			if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
+				//ok check if it's set, if so: update; if not, insert
1578
+				if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1579
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1580
+				} else {
1581
+					unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1582
+					$results = $this->get_model()->insert($save_cols_n_values);
1583
+					if ($results) {
1584
+						//if successful, set the primary key
1585
+						//but don't use the normal SET method, because it will check if
1586
+						//an item with the same ID exists in the mapper & db, then
1587
+						//will find it in the db (because we just added it) and THAT object
1588
+						//will get added to the mapper before we can add this one!
1589
+						//but if we just avoid using the SET method, all that headache can be avoided
1590
+						$pk_field_name = self::_get_primary_key_name(get_class($this));
1591
+						$this->_fields[$pk_field_name] = $results;
1592
+						$this->_clear_cached_property($pk_field_name);
1593
+						$this->get_model()->add_to_entity_map($this);
1594
+						$this->_update_cached_related_model_objs_fks();
1595
+					}
1596
+				}
1597
+			} else {//PK is NOT auto-increment
1598
+				//so check if one like it already exists in the db
1599
+				if ($this->get_model()->exists_by_ID($this->ID())) {
1600
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1601
+						throw new EE_Error(
1602
+							sprintf(
1603
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604
+									'event_espresso'),
1605
+								get_class($this),
1606
+								get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
+								get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1608
+								'<br />'
1609
+							)
1610
+						);
1611
+					}
1612
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1613
+				} else {
1614
+					$results = $this->get_model()->insert($save_cols_n_values);
1615
+					$this->_update_cached_related_model_objs_fks();
1616
+				}
1617
+			}
1618
+		} else {//there is NO primary key
1619
+			$already_in_db = false;
1620
+			foreach ($this->get_model()->unique_indexes() as $index) {
1621
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1622
+				if ($this->get_model()->exists(array($uniqueness_where_params))) {
1623
+					$already_in_db = true;
1624
+				}
1625
+			}
1626
+			if ($already_in_db) {
1627
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1628
+					$this->get_model()->get_combined_primary_key_fields());
1629
+				$results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1630
+			} else {
1631
+				$results = $this->get_model()->insert($save_cols_n_values);
1632
+			}
1633
+		}
1634
+		//restore the old assumption about values being prepared by the model object
1635
+		$this->get_model()
1636
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1637
+		/**
1638
+		 * After saving the model object this action is called
1639
+		 *
1640
+		 * @param EE_Base_Class $model_object which was just saved
1641
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1642
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1643
+		 */
1644
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1645
+		return $results;
1646
+	}
1647
+
1648
+
1649
+
1650
+	/**
1651
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1652
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1653
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1654
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1655
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1656
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1657
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1658
+	 *
1659
+	 * @return void
1660
+	 * @throws \EE_Error
1661
+	 */
1662
+	protected function _update_cached_related_model_objs_fks()
1663
+	{
1664
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1665
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1666
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1667
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1668
+						$this->get_model()->get_this_model_name()
1669
+					);
1670
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1671
+					if ($related_model_obj_in_cache->ID()) {
1672
+						$related_model_obj_in_cache->save();
1673
+					}
1674
+				}
1675
+			}
1676
+		}
1677
+	}
1678
+
1679
+
1680
+
1681
+	/**
1682
+	 * Saves this model object and its NEW cached relations to the database.
1683
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1684
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1685
+	 * because otherwise, there's a potential for infinite looping of saving
1686
+	 * Saves the cached related model objects, and ensures the relation between them
1687
+	 * and this object and properly setup
1688
+	 *
1689
+	 * @return int ID of new model object on save; 0 on failure+
1690
+	 * @throws \EE_Error
1691
+	 */
1692
+	public function save_new_cached_related_model_objs()
1693
+	{
1694
+		//make sure this has been saved
1695
+		if ( ! $this->ID()) {
1696
+			$id = $this->save();
1697
+		} else {
1698
+			$id = $this->ID();
1699
+		}
1700
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1701
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1702
+			if ($this->_model_relations[$relationName]) {
1703
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1704
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1705
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1706
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1707
+					//but ONLY if it DOES NOT exist in the DB
1708
+					/* @var $related_model_obj EE_Base_Class */
1709
+					$related_model_obj = $this->_model_relations[$relationName];
1710
+					//					if( ! $related_model_obj->ID()){
1711
+					$this->_add_relation_to($related_model_obj, $relationName);
1712
+					$related_model_obj->save_new_cached_related_model_objs();
1713
+					//					}
1714
+				} else {
1715
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1716
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1717
+						//but ONLY if it DOES NOT exist in the DB
1718
+						//						if( ! $related_model_obj->ID()){
1719
+						$this->_add_relation_to($related_model_obj, $relationName);
1720
+						$related_model_obj->save_new_cached_related_model_objs();
1721
+						//						}
1722
+					}
1723
+				}
1724
+			}
1725
+		}
1726
+		return $id;
1727
+	}
1728
+
1729
+
1730
+
1731
+	/**
1732
+	 * for getting a model while instantiated.
1733
+	 *
1734
+	 * @return \EEM_Base | \EEM_CPT_Base
1735
+	 */
1736
+	public function get_model()
1737
+	{
1738
+		$modelName = self::_get_model_classname(get_class($this));
1739
+		return self::_get_model_instance_with_name($modelName, $this->_timezone);
1740
+	}
1741
+
1742
+
1743
+
1744
+	/**
1745
+	 * @param $props_n_values
1746
+	 * @param $classname
1747
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1748
+	 * @throws \EE_Error
1749
+	 */
1750
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1751
+	{
1752
+		//TODO: will not work for Term_Relationships because they have no PK!
1753
+		$primary_id_ref = self::_get_primary_key_name($classname);
1754
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1755
+			$id = $props_n_values[$primary_id_ref];
1756
+			return self::_get_model($classname)->get_from_entity_map($id);
1757
+		}
1758
+		return false;
1759
+	}
1760
+
1761
+
1762
+
1763
+	/**
1764
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1765
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1766
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1767
+	 * we return false.
1768
+	 *
1769
+	 * @param  array  $props_n_values   incoming array of properties and their values
1770
+	 * @param  string $classname        the classname of the child class
1771
+	 * @param null    $timezone
1772
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1773
+	 *                                  date_format and the second value is the time format
1774
+	 * @return mixed (EE_Base_Class|bool)
1775
+	 * @throws \EE_Error
1776
+	 */
1777
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1778
+	{
1779
+		$existing = null;
1780
+		if (self::_get_model($classname)->has_primary_key_field()) {
1781
+			$primary_id_ref = self::_get_primary_key_name($classname);
1782
+			if (array_key_exists($primary_id_ref, $props_n_values)
1783
+				&& ! empty($props_n_values[$primary_id_ref])
1784
+			) {
1785
+				$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1786
+					$props_n_values[$primary_id_ref]
1787
+				);
1788
+			}
1789
+		} elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1790
+			//no primary key on this model, but there's still a matching item in the DB
1791
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1792
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1793
+			);
1794
+		}
1795
+		if ($existing) {
1796
+			//set date formats if present before setting values
1797
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1798
+				$existing->set_date_format($date_formats[0]);
1799
+				$existing->set_time_format($date_formats[1]);
1800
+			} else {
1801
+				//set default formats for date and time
1802
+				$existing->set_date_format(get_option('date_format'));
1803
+				$existing->set_time_format(get_option('time_format'));
1804
+			}
1805
+			foreach ($props_n_values as $property => $field_value) {
1806
+				$existing->set($property, $field_value);
1807
+			}
1808
+			return $existing;
1809
+		} else {
1810
+			return false;
1811
+		}
1812
+	}
1813
+
1814
+
1815
+
1816
+	/**
1817
+	 * Gets the EEM_*_Model for this class
1818
+	 *
1819
+	 * @access public now, as this is more convenient
1820
+	 * @param      $classname
1821
+	 * @param null $timezone
1822
+	 * @throws EE_Error
1823
+	 * @return EEM_Base
1824
+	 */
1825
+	protected static function _get_model($classname, $timezone = null)
1826
+	{
1827
+		//find model for this class
1828
+		if ( ! $classname) {
1829
+			throw new EE_Error(
1830
+				sprintf(
1831
+					__(
1832
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1833
+						"event_espresso"
1834
+					),
1835
+					$classname
1836
+				)
1837
+			);
1838
+		}
1839
+		$modelName = self::_get_model_classname($classname);
1840
+		return self::_get_model_instance_with_name($modelName, $timezone);
1841
+	}
1842
+
1843
+
1844
+
1845
+	/**
1846
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1847
+	 *
1848
+	 * @param string $model_classname
1849
+	 * @param null   $timezone
1850
+	 * @return EEM_Base
1851
+	 */
1852
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1853
+	{
1854
+		$model_classname = str_replace('EEM_', '', $model_classname);
1855
+		$model = EE_Registry::instance()->load_model($model_classname);
1856
+		$model->set_timezone($timezone);
1857
+		return $model;
1858
+	}
1859
+
1860
+
1861
+
1862
+	/**
1863
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1864
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1865
+	 *
1866
+	 * @param null $model_name
1867
+	 * @return string like EEM_Attendee
1868
+	 */
1869
+	private static function _get_model_classname($model_name = null)
1870
+	{
1871
+		if (strpos($model_name, "EE_") === 0) {
1872
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1873
+		} else {
1874
+			$model_classname = "EEM_" . $model_name;
1875
+		}
1876
+		return $model_classname;
1877
+	}
1878
+
1879
+
1880
+
1881
+	/**
1882
+	 * returns the name of the primary key attribute
1883
+	 *
1884
+	 * @param null $classname
1885
+	 * @throws EE_Error
1886
+	 * @return string
1887
+	 */
1888
+	protected static function _get_primary_key_name($classname = null)
1889
+	{
1890
+		if ( ! $classname) {
1891
+			throw new EE_Error(
1892
+				sprintf(
1893
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1894
+					$classname
1895
+				)
1896
+			);
1897
+		}
1898
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1899
+	}
1900
+
1901
+
1902
+
1903
+	/**
1904
+	 * Gets the value of the primary key.
1905
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1906
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1907
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1908
+	 *
1909
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1910
+	 * @throws \EE_Error
1911
+	 */
1912
+	public function ID()
1913
+	{
1914
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1915
+		if ($this->get_model()->has_primary_key_field()) {
1916
+			return $this->_fields[self::_get_primary_key_name(get_class($this))];
1917
+		} else {
1918
+			return $this->get_model()->get_index_primary_key_string($this->_fields);
1919
+		}
1920
+	}
1921
+
1922
+
1923
+
1924
+	/**
1925
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1926
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1927
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1928
+	 *
1929
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1930
+	 * @param string $relationName                     eg 'Events','Question',etc.
1931
+	 *                                                 an attendee to a group, you also want to specify which role they
1932
+	 *                                                 will have in that group. So you would use this parameter to
1933
+	 *                                                 specify array('role-column-name'=>'role-id')
1934
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1935
+	 *                                                 allow you to further constrict the relation to being added.
1936
+	 *                                                 However, keep in mind that the columns (keys) given must match a
1937
+	 *                                                 column on the JOIN table and currently only the HABTM models
1938
+	 *                                                 accept these additional conditions.  Also remember that if an
1939
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
1940
+	 *                                                 NEW row is created in the join table.
1941
+	 * @param null   $cache_id
1942
+	 * @throws EE_Error
1943
+	 * @return EE_Base_Class the object the relation was added to
1944
+	 */
1945
+	public function _add_relation_to(
1946
+		$otherObjectModelObjectOrID,
1947
+		$relationName,
1948
+		$extra_join_model_fields_n_values = array(),
1949
+		$cache_id = null
1950
+	) {
1951
+		//if this thing exists in the DB, save the relation to the DB
1952
+		if ($this->ID()) {
1953
+			$otherObject = $this->get_model()
1954
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1955
+									$extra_join_model_fields_n_values);
1956
+			//clear cache so future get_many_related and get_first_related() return new results.
1957
+			$this->clear_cache($relationName, $otherObject, true);
1958
+			if ($otherObject instanceof EE_Base_Class) {
1959
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1960
+			}
1961
+		} else {
1962
+			//this thing doesn't exist in the DB,  so just cache it
1963
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1964
+				throw new EE_Error(sprintf(
1965
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1966
+						'event_espresso'),
1967
+					$otherObjectModelObjectOrID,
1968
+					get_class($this)
1969
+				));
1970
+			} else {
1971
+				$otherObject = $otherObjectModelObjectOrID;
1972
+			}
1973
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1974
+		}
1975
+		if ($otherObject instanceof EE_Base_Class) {
1976
+			//fix the reciprocal relation too
1977
+			if ($otherObject->ID()) {
1978
+				//its saved so assumed relations exist in the DB, so we can just
1979
+				//clear the cache so future queries use the updated info in the DB
1980
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1981
+			} else {
1982
+				//it's not saved, so it caches relations like this
1983
+				$otherObject->cache($this->get_model()->get_this_model_name(), $this);
1984
+			}
1985
+		}
1986
+		return $otherObject;
1987
+	}
1988
+
1989
+
1990
+
1991
+	/**
1992
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
1993
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
1994
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
1995
+	 * from the cache
1996
+	 *
1997
+	 * @param mixed  $otherObjectModelObjectOrID
1998
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
1999
+	 *                to the DB yet
2000
+	 * @param string $relationName
2001
+	 * @param array  $where_query
2002
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2003
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2004
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2005
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2006
+	 *                created in the join table.
2007
+	 * @return EE_Base_Class the relation was removed from
2008
+	 * @throws \EE_Error
2009
+	 */
2010
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2011
+	{
2012
+		if ($this->ID()) {
2013
+			//if this exists in the DB, save the relation change to the DB too
2014
+			$otherObject = $this->get_model()
2015
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2016
+									$where_query);
2017
+			$this->clear_cache($relationName, $otherObject);
2018
+		} else {
2019
+			//this doesn't exist in the DB, just remove it from the cache
2020
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2021
+		}
2022
+		if ($otherObject instanceof EE_Base_Class) {
2023
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2024
+		}
2025
+		return $otherObject;
2026
+	}
2027
+
2028
+
2029
+
2030
+	/**
2031
+	 * Removes ALL the related things for the $relationName.
2032
+	 *
2033
+	 * @param string $relationName
2034
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2035
+	 * @return EE_Base_Class
2036
+	 * @throws \EE_Error
2037
+	 */
2038
+	public function _remove_relations($relationName, $where_query_params = array())
2039
+	{
2040
+		if ($this->ID()) {
2041
+			//if this exists in the DB, save the relation change to the DB too
2042
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2043
+			$this->clear_cache($relationName, null, true);
2044
+		} else {
2045
+			//this doesn't exist in the DB, just remove it from the cache
2046
+			$otherObjects = $this->clear_cache($relationName, null, true);
2047
+		}
2048
+		if (is_array($otherObjects)) {
2049
+			foreach ($otherObjects as $otherObject) {
2050
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2051
+			}
2052
+		}
2053
+		return $otherObjects;
2054
+	}
2055
+
2056
+
2057
+
2058
+	/**
2059
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2060
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2061
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2062
+	 * because we want to get even deleted items etc.
2063
+	 *
2064
+	 * @param string $relationName key in the model's _model_relations array
2065
+	 * @param array  $query_params like EEM_Base::get_all
2066
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2067
+	 * @throws \EE_Error
2068
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2069
+	 *                             you want IDs
2070
+	 */
2071
+	public function get_many_related($relationName, $query_params = array())
2072
+	{
2073
+		if ($this->ID()) {
2074
+			//this exists in the DB, so get the related things from either the cache or the DB
2075
+			//if there are query parameters, forget about caching the related model objects.
2076
+			if ($query_params) {
2077
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2078
+			} else {
2079
+				//did we already cache the result of this query?
2080
+				$cached_results = $this->get_all_from_cache($relationName);
2081
+				if ( ! $cached_results) {
2082
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2083
+					//if no query parameters were passed, then we got all the related model objects
2084
+					//for that relation. We can cache them then.
2085
+					foreach ($related_model_objects as $related_model_object) {
2086
+						$this->cache($relationName, $related_model_object);
2087
+					}
2088
+				} else {
2089
+					$related_model_objects = $cached_results;
2090
+				}
2091
+			}
2092
+		} else {
2093
+			//this doesn't exist in the DB, so just get the related things from the cache
2094
+			$related_model_objects = $this->get_all_from_cache($relationName);
2095
+		}
2096
+		return $related_model_objects;
2097
+	}
2098
+
2099
+
2100
+
2101
+	/**
2102
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2103
+	 * unless otherwise specified in the $query_params
2104
+	 *
2105
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2106
+	 * @param array  $query_params   like EEM_Base::get_all's
2107
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2108
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2109
+	 *                               that by the setting $distinct to TRUE;
2110
+	 * @return int
2111
+	 */
2112
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2113
+	{
2114
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2115
+	}
2116
+
2117
+
2118
+
2119
+	/**
2120
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2121
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2122
+	 *
2123
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2124
+	 * @param array  $query_params  like EEM_Base::get_all's
2125
+	 * @param string $field_to_sum  name of field to count by.
2126
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2127
+	 *                              change it)
2128
+	 * @return int
2129
+	 */
2130
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2131
+	{
2132
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2133
+	}
2134
+
2135
+
2136
+
2137
+	/**
2138
+	 * Gets the first (ie, one) related model object of the specified type.
2139
+	 *
2140
+	 * @param string $relationName key in the model's _model_relations array
2141
+	 * @param array  $query_params like EEM_Base::get_all
2142
+	 * @return EE_Base_Class (not an array, a single object)
2143
+	 * @throws \EE_Error
2144
+	 */
2145
+	public function get_first_related($relationName, $query_params = array())
2146
+	{
2147
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2148
+			//if they've provided some query parameters, don't bother trying to cache the result
2149
+			//also make sure we're not caching the result of get_first_related
2150
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2151
+			if ($query_params
2152
+				|| ! $this->get_model()->related_settings_for($relationName)
2153
+					 instanceof
2154
+					 EE_Belongs_To_Relation
2155
+			) {
2156
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2157
+			} else {
2158
+				//first, check if we've already cached the result of this query
2159
+				$cached_result = $this->get_one_from_cache($relationName);
2160
+				if ( ! $cached_result) {
2161
+					$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2162
+					$this->cache($relationName, $related_model_object);
2163
+				} else {
2164
+					$related_model_object = $cached_result;
2165
+				}
2166
+			}
2167
+		} else {
2168
+			$related_model_object = null;
2169
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2170
+			if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2171
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
+			}
2173
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2174
+			if ( ! $related_model_object) {
2175
+				$related_model_object = $this->get_one_from_cache($relationName);
2176
+			}
2177
+		}
2178
+		return $related_model_object;
2179
+	}
2180
+
2181
+
2182
+
2183
+	/**
2184
+	 * Does a delete on all related objects of type $relationName and removes
2185
+	 * the current model object's relation to them. If they can't be deleted (because
2186
+	 * of blocking related model objects) does nothing. If the related model objects are
2187
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2188
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2189
+	 *
2190
+	 * @param string $relationName
2191
+	 * @param array  $query_params like EEM_Base::get_all's
2192
+	 * @return int how many deleted
2193
+	 * @throws \EE_Error
2194
+	 */
2195
+	public function delete_related($relationName, $query_params = array())
2196
+	{
2197
+		if ($this->ID()) {
2198
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2199
+		} else {
2200
+			$count = count($this->get_all_from_cache($relationName));
2201
+			$this->clear_cache($relationName, null, true);
2202
+		}
2203
+		return $count;
2204
+	}
2205
+
2206
+
2207
+
2208
+	/**
2209
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2210
+	 * the current model object's relation to them. If they can't be deleted (because
2211
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2212
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2213
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2214
+	 *
2215
+	 * @param string $relationName
2216
+	 * @param array  $query_params like EEM_Base::get_all's
2217
+	 * @return int how many deleted (including those soft deleted)
2218
+	 * @throws \EE_Error
2219
+	 */
2220
+	public function delete_related_permanently($relationName, $query_params = array())
2221
+	{
2222
+		if ($this->ID()) {
2223
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2224
+		} else {
2225
+			$count = count($this->get_all_from_cache($relationName));
2226
+		}
2227
+		$this->clear_cache($relationName, null, true);
2228
+		return $count;
2229
+	}
2230
+
2231
+
2232
+
2233
+	/**
2234
+	 * is_set
2235
+	 * Just a simple utility function children can use for checking if property exists
2236
+	 *
2237
+	 * @access  public
2238
+	 * @param  string $field_name property to check
2239
+	 * @return bool                              TRUE if existing,FALSE if not.
2240
+	 */
2241
+	public function is_set($field_name)
2242
+	{
2243
+		return isset($this->_fields[$field_name]);
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2250
+	 * EE_Error exception if they don't
2251
+	 *
2252
+	 * @param  mixed (string|array) $properties properties to check
2253
+	 * @throws EE_Error
2254
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2255
+	 */
2256
+	protected function _property_exists($properties)
2257
+	{
2258
+		foreach ((array)$properties as $property_name) {
2259
+			//first make sure this property exists
2260
+			if ( ! $this->_fields[$property_name]) {
2261
+				throw new EE_Error(
2262
+					sprintf(
2263
+						__(
2264
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2265
+							'event_espresso'
2266
+						),
2267
+						$property_name
2268
+					)
2269
+				);
2270
+			}
2271
+		}
2272
+		return true;
2273
+	}
2274
+
2275
+
2276
+
2277
+	/**
2278
+	 * This simply returns an array of model fields for this object
2279
+	 *
2280
+	 * @return array
2281
+	 * @throws \EE_Error
2282
+	 */
2283
+	public function model_field_array()
2284
+	{
2285
+		$fields = $this->get_model()->field_settings(false);
2286
+		$properties = array();
2287
+		//remove prepended underscore
2288
+		foreach ($fields as $field_name => $settings) {
2289
+			$properties[$field_name] = $this->get($field_name);
2290
+		}
2291
+		return $properties;
2292
+	}
2293
+
2294
+
2295
+
2296
+	/**
2297
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2298
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2299
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2300
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2301
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2302
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2303
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2304
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2305
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2306
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2307
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2308
+	 *        return $previousReturnValue.$returnString;
2309
+	 * }
2310
+	 * require('EE_Answer.class.php');
2311
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2312
+	 * echo $answer->my_callback('monkeys',100);
2313
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2314
+	 *
2315
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2316
+	 * @param array  $args       array of original arguments passed to the function
2317
+	 * @throws EE_Error
2318
+	 * @return mixed whatever the plugin which calls add_filter decides
2319
+	 */
2320
+	public function __call($methodName, $args)
2321
+	{
2322
+		$className = get_class($this);
2323
+		$tagName = "FHEE__{$className}__{$methodName}";
2324
+		if ( ! has_filter($tagName)) {
2325
+			throw new EE_Error(
2326
+				sprintf(
2327
+					__(
2328
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2329
+						"event_espresso"
2330
+					),
2331
+					$methodName,
2332
+					$className,
2333
+					$tagName
2334
+				)
2335
+			);
2336
+		}
2337
+		return apply_filters($tagName, null, $this, $args);
2338
+	}
2339
+
2340
+
2341
+
2342
+	/**
2343
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2344
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2345
+	 *
2346
+	 * @param string $meta_key
2347
+	 * @param string $meta_value
2348
+	 * @param string $previous_value
2349
+	 * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2350
+	 * @throws \EE_Error
2351
+	 * NOTE: if the values haven't changed, returns 0
2352
+	 */
2353
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2354
+	{
2355
+		$query_params = array(
2356
+			array(
2357
+				'EXM_key'  => $meta_key,
2358
+				'OBJ_ID'   => $this->ID(),
2359
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2360
+			),
2361
+		);
2362
+		if ($previous_value !== null) {
2363
+			$query_params[0]['EXM_value'] = $meta_value;
2364
+		}
2365
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2366
+		if ( ! $existing_rows_like_that) {
2367
+			return $this->add_extra_meta($meta_key, $meta_value);
2368
+		} else {
2369
+			foreach ($existing_rows_like_that as $existing_row) {
2370
+				$existing_row->save(array('EXM_value' => $meta_value));
2371
+			}
2372
+			return count($existing_rows_like_that);
2373
+		}
2374
+	}
2375
+
2376
+
2377
+
2378
+	/**
2379
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2380
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2381
+	 * extra meta row was entered, false if not
2382
+	 *
2383
+	 * @param string  $meta_key
2384
+	 * @param string  $meta_value
2385
+	 * @param boolean $unique
2386
+	 * @return boolean
2387
+	 * @throws \EE_Error
2388
+	 */
2389
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2390
+	{
2391
+		if ($unique) {
2392
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2393
+				array(
2394
+					array(
2395
+						'EXM_key'  => $meta_key,
2396
+						'OBJ_ID'   => $this->ID(),
2397
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2398
+					),
2399
+				)
2400
+			);
2401
+			if ($existing_extra_meta) {
2402
+				return false;
2403
+			}
2404
+		}
2405
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2406
+			array(
2407
+				'EXM_key'   => $meta_key,
2408
+				'EXM_value' => $meta_value,
2409
+				'OBJ_ID'    => $this->ID(),
2410
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2411
+			)
2412
+		);
2413
+		$new_extra_meta->save();
2414
+		return true;
2415
+	}
2416
+
2417
+
2418
+
2419
+	/**
2420
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2421
+	 * is specified, only deletes extra meta records with that value.
2422
+	 *
2423
+	 * @param string $meta_key
2424
+	 * @param string $meta_value
2425
+	 * @return int number of extra meta rows deleted
2426
+	 * @throws \EE_Error
2427
+	 */
2428
+	public function delete_extra_meta($meta_key, $meta_value = null)
2429
+	{
2430
+		$query_params = array(
2431
+			array(
2432
+				'EXM_key'  => $meta_key,
2433
+				'OBJ_ID'   => $this->ID(),
2434
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2435
+			),
2436
+		);
2437
+		if ($meta_value !== null) {
2438
+			$query_params[0]['EXM_value'] = $meta_value;
2439
+		}
2440
+		return EEM_Extra_Meta::instance()->delete($query_params);
2441
+	}
2442
+
2443
+
2444
+
2445
+	/**
2446
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2447
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2448
+	 * You can specify $default is case you haven't found the extra meta
2449
+	 *
2450
+	 * @param string  $meta_key
2451
+	 * @param boolean $single
2452
+	 * @param mixed   $default if we don't find anything, what should we return?
2453
+	 * @return mixed single value if $single; array if ! $single
2454
+	 * @throws \EE_Error
2455
+	 */
2456
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2457
+	{
2458
+		if ($single) {
2459
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2460
+			if ($result instanceof EE_Extra_Meta) {
2461
+				return $result->value();
2462
+			} else {
2463
+				return $default;
2464
+			}
2465
+		} else {
2466
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2467
+			if ($results) {
2468
+				$values = array();
2469
+				foreach ($results as $result) {
2470
+					if ($result instanceof EE_Extra_Meta) {
2471
+						$values[$result->ID()] = $result->value();
2472
+					}
2473
+				}
2474
+				return $values;
2475
+			} else {
2476
+				return $default;
2477
+			}
2478
+		}
2479
+	}
2480
+
2481
+
2482
+
2483
+	/**
2484
+	 * Returns a simple array of all the extra meta associated with this model object.
2485
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2486
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2487
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2488
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2489
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2490
+	 * finally the extra meta's value as each sub-value. (eg
2491
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2492
+	 *
2493
+	 * @param boolean $one_of_each_key
2494
+	 * @return array
2495
+	 * @throws \EE_Error
2496
+	 */
2497
+	public function all_extra_meta_array($one_of_each_key = true)
2498
+	{
2499
+		$return_array = array();
2500
+		if ($one_of_each_key) {
2501
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2502
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2503
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2504
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2505
+				}
2506
+			}
2507
+		} else {
2508
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2509
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2510
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2511
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2512
+						$return_array[$extra_meta_obj->key()] = array();
2513
+					}
2514
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2515
+				}
2516
+			}
2517
+		}
2518
+		return $return_array;
2519
+	}
2520
+
2521
+
2522
+
2523
+	/**
2524
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2525
+	 *
2526
+	 * @return string
2527
+	 * @throws \EE_Error
2528
+	 */
2529
+	public function name()
2530
+	{
2531
+		//find a field that's not a text field
2532
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2533
+		if ($field_we_can_use) {
2534
+			return $this->get($field_we_can_use->get_name());
2535
+		} else {
2536
+			$first_few_properties = $this->model_field_array();
2537
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2538
+			$name_parts = array();
2539
+			foreach ($first_few_properties as $name => $value) {
2540
+				$name_parts[] = "$name:$value";
2541
+			}
2542
+			return implode(",", $name_parts);
2543
+		}
2544
+	}
2545
+
2546
+
2547
+
2548
+	/**
2549
+	 * in_entity_map
2550
+	 * Checks if this model object has been proven to already be in the entity map
2551
+	 *
2552
+	 * @return boolean
2553
+	 * @throws \EE_Error
2554
+	 */
2555
+	public function in_entity_map()
2556
+	{
2557
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2558
+			//well, if we looked, did we find it in the entity map?
2559
+			return true;
2560
+		} else {
2561
+			return false;
2562
+		}
2563
+	}
2564
+
2565
+
2566
+
2567
+	/**
2568
+	 * refresh_from_db
2569
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2570
+	 *
2571
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2572
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2573
+	 */
2574
+	public function refresh_from_db()
2575
+	{
2576
+		if ($this->ID() && $this->in_entity_map()) {
2577
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2578
+		} else {
2579
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2580
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2581
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2582
+			//absolutely nothing in it for this ID
2583
+			if (WP_DEBUG) {
2584
+				throw new EE_Error(
2585
+					sprintf(
2586
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587
+							'event_espresso'),
2588
+						$this->ID(),
2589
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2591
+					)
2592
+				);
2593
+			}
2594
+		}
2595
+	}
2596
+
2597
+
2598
+
2599
+	/**
2600
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2601
+	 * (probably a bad assumption they have made, oh well)
2602
+	 *
2603
+	 * @return string
2604
+	 */
2605
+	public function __toString()
2606
+	{
2607
+		try {
2608
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2609
+		} catch (Exception $e) {
2610
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2611
+			return '';
2612
+		}
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2619
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2620
+	 * This means if we have made changes to those related model objects, and want to unserialize
2621
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2622
+	 * Instead, those related model objects should be directly serialized and stored.
2623
+	 * Eg, the following won't work:
2624
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2625
+	 * $att = $reg->attendee();
2626
+	 * $att->set( 'ATT_fname', 'Dirk' );
2627
+	 * update_option( 'my_option', serialize( $reg ) );
2628
+	 * //END REQUEST
2629
+	 * //START NEXT REQUEST
2630
+	 * $reg = get_option( 'my_option' );
2631
+	 * $reg->attendee()->save();
2632
+	 * And would need to be replace with:
2633
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2634
+	 * $att = $reg->attendee();
2635
+	 * $att->set( 'ATT_fname', 'Dirk' );
2636
+	 * update_option( 'my_option', serialize( $reg ) );
2637
+	 * //END REQUEST
2638
+	 * //START NEXT REQUEST
2639
+	 * $att = get_option( 'my_option' );
2640
+	 * $att->save();
2641
+	 *
2642
+	 * @return array
2643
+	 * @throws \EE_Error
2644
+	 */
2645
+	public function __sleep()
2646
+	{
2647
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
+				$classname = 'EE_' . $this->get_model()->get_this_model_name();
2650
+				if (
2651
+					$this->get_one_from_cache($relation_name) instanceof $classname
2652
+					&& $this->get_one_from_cache($relation_name)->ID()
2653
+				) {
2654
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2655
+				}
2656
+			}
2657
+		}
2658
+		$this->_props_n_values_provided_in_constructor = array();
2659
+		return array_keys(get_object_vars($this));
2660
+	}
2661
+
2662
+
2663
+
2664
+	/**
2665
+	 * restore _props_n_values_provided_in_constructor
2666
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2667
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2668
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2669
+	 */
2670
+	public function __wakeup()
2671
+	{
2672
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2673
+	}
2674 2674
 
2675 2675
 
2676 2676
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -145,8 +145,8 @@  discard block
 block discarded – undo
145 145
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146 146
         } else {
147 147
             //set default formats for date and time
148
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
148
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
149
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
150 150
         }
151 151
         //if db model is instantiating
152 152
         if ($bydb) {
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
      */
458 458
     public function get_format($full = true)
459 459
     {
460
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
460
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461 461
     }
462 462
 
463 463
 
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
         //verify the field exists
566 566
         $this->get_model()->field_settings_for($fieldname);
567 567
         $cache_type = $pretty ? 'pretty' : 'standard';
568
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
568
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
569 569
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570 570
             return $this->_cached_properties[$fieldname][$cache_type];
571 571
         }
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
         $current_cache_id = ''
781 781
     ) {
782 782
         // verify that incoming object is of the correct type
783
-        $obj_class = 'EE_' . $relationName;
783
+        $obj_class = 'EE_'.$relationName;
784 784
         if ($newly_saved_object instanceof $obj_class) {
785 785
             /* @type EE_Base_Class $newly_saved_object */
786 786
             // now get the type of relation
@@ -1259,7 +1259,7 @@  discard block
 block discarded – undo
1259 1259
      */
1260 1260
     public function get_i18n_datetime($field_name, $format = '')
1261 1261
     {
1262
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1262
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1263 1263
         return date_i18n(
1264 1264
             $format,
1265 1265
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1397,8 +1397,8 @@  discard block
 block discarded – undo
1397 1397
         }
1398 1398
         $original_timezone = $this->_timezone;
1399 1399
         $this->set_timezone($timezone);
1400
-        $fn = (array)$field_name;
1401
-        $args = array_merge($fn, (array)$args);
1400
+        $fn = (array) $field_name;
1401
+        $args = array_merge($fn, (array) $args);
1402 1402
         if ( ! method_exists($this, $callback)) {
1403 1403
             throw new EE_Error(
1404 1404
                 sprintf(
@@ -1410,8 +1410,8 @@  discard block
 block discarded – undo
1410 1410
                 )
1411 1411
             );
1412 1412
         }
1413
-        $args = (array)$args;
1414
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1413
+        $args = (array) $args;
1414
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1415 1415
         $this->set_timezone($original_timezone);
1416 1416
         return $return;
1417 1417
     }
@@ -1548,7 +1548,7 @@  discard block
 block discarded – undo
1548 1548
          * @param array         $set_cols_n_values
1549 1549
          * @param EE_Base_Class $model_object
1550 1550
          */
1551
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1551
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552 1552
             $this);
1553 1553
         //set attributes as provided in $set_cols_n_values
1554 1554
         foreach ($set_cols_n_values as $column => $value) {
@@ -1603,8 +1603,8 @@  discard block
 block discarded – undo
1603 1603
                                 __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604 1604
                                     'event_espresso'),
1605 1605
                                 get_class($this),
1606
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1606
+                                get_class($this->get_model()).'::instance()->add_to_entity_map()',
1607
+                                get_class($this->get_model()).'::instance()->get_one_by_ID()',
1608 1608
                                 '<br />'
1609 1609
                             )
1610 1610
                         );
@@ -1871,7 +1871,7 @@  discard block
 block discarded – undo
1871 1871
         if (strpos($model_name, "EE_") === 0) {
1872 1872
             $model_classname = str_replace("EE_", "EEM_", $model_name);
1873 1873
         } else {
1874
-            $model_classname = "EEM_" . $model_name;
1874
+            $model_classname = "EEM_".$model_name;
1875 1875
         }
1876 1876
         return $model_classname;
1877 1877
     }
@@ -2255,7 +2255,7 @@  discard block
 block discarded – undo
2255 2255
      */
2256 2256
     protected function _property_exists($properties)
2257 2257
     {
2258
-        foreach ((array)$properties as $property_name) {
2258
+        foreach ((array) $properties as $property_name) {
2259 2259
             //first make sure this property exists
2260 2260
             if ( ! $this->_fields[$property_name]) {
2261 2261
                 throw new EE_Error(
@@ -2586,8 +2586,8 @@  discard block
 block discarded – undo
2586 2586
                         __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587 2587
                             'event_espresso'),
2588 2588
                         $this->ID(),
2589
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2589
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2590
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2591 2591
                     )
2592 2592
                 );
2593 2593
             }
@@ -2646,7 +2646,7 @@  discard block
 block discarded – undo
2646 2646
     {
2647 2647
         foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648 2648
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2649
+                $classname = 'EE_'.$this->get_model()->get_this_model_name();
2650 2650
                 if (
2651 2651
                     $this->get_one_from_cache($relation_name) instanceof $classname
2652 2652
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.