Completed
Branch BUG/reg-status-change-recursio... (a8e61c)
by
unknown
21:06 queued 11:18
created
core/EE_Config.core.php 2 patches
Spacing   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
     public static function instance()
146 146
     {
147 147
         // check if class object is instantiated, and instantiated properly
148
-        if (! self::$_instance instanceof EE_Config) {
148
+        if ( ! self::$_instance instanceof EE_Config) {
149 149
             self::$_instance = new self();
150 150
         }
151 151
         return self::$_instance;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
                 $this
284 284
             );
285 285
             if (is_object($settings) && property_exists($this, $config)) {
286
-                $this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__' . $config, $settings);
286
+                $this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__'.$config, $settings);
287 287
                 // call configs populate method to ensure any defaults are set for empty values.
288 288
                 if (method_exists($settings, 'populate')) {
289 289
                     $this->{$config}->populate();
@@ -556,7 +556,7 @@  discard block
 block discarded – undo
556 556
                         break;
557 557
                     // TEST #2 : check that settings section exists
558 558
                     case 2:
559
-                        if (! isset($this->{$section})) {
559
+                        if ( ! isset($this->{$section})) {
560 560
                             if ($display_errors) {
561 561
                                 throw new EE_Error(
562 562
                                     sprintf(
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
                         break;
571 571
                     // TEST #3 : check that section is the proper format
572 572
                     case 3:
573
-                        if (! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
573
+                        if ( ! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
574 574
                         ) {
575 575
                             if ($display_errors) {
576 576
                                 throw new EE_Error(
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
                         break;
617 617
                     // TEST #6 : verify config class is accessible
618 618
                     case 6:
619
-                        if (! class_exists($config_class)) {
619
+                        if ( ! class_exists($config_class)) {
620 620
                             if ($display_errors) {
621 621
                                 throw new EE_Error(
622 622
                                     sprintf(
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
                         break;
634 634
                     // TEST #7 : check that config has even been set
635 635
                     case 7:
636
-                        if (! isset($this->{$section}->{$name})) {
636
+                        if ( ! isset($this->{$section}->{$name})) {
637 637
                             if ($display_errors) {
638 638
                                 throw new EE_Error(
639 639
                                     sprintf(
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
                         break;
652 652
                     // TEST #8 : check that config is the requested type
653 653
                     case 8:
654
-                        if (! $this->{$section}->{$name} instanceof $config_class) {
654
+                        if ( ! $this->{$section}->{$name} instanceof $config_class) {
655 655
                             if ($display_errors) {
656 656
                                 throw new EE_Error(
657 657
                                     sprintf(
@@ -670,7 +670,7 @@  discard block
 block discarded – undo
670 670
                         break;
671 671
                     // TEST #9 : verify config object
672 672
                     case 9:
673
-                        if (! $config_obj instanceof EE_Config_Base) {
673
+                        if ( ! $config_obj instanceof EE_Config_Base) {
674 674
                             if ($display_errors) {
675 675
                                 throw new EE_Error(
676 676
                                     sprintf(
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
      */
703 703
     private function _generate_config_option_name($section = '', $name = '')
704 704
     {
705
-        return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
705
+        return 'ee_config-'.strtolower($section.'-'.str_replace(array('EE_', 'EED_'), '', $name));
706 706
     }
707 707
 
708 708
 
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
     {
720 720
         return ! empty($config_class)
721 721
             ? $config_class
722
-            : str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
722
+            : str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))).'_Config';
723 723
     }
724 724
 
725 725
 
@@ -738,17 +738,17 @@  discard block
 block discarded – undo
738 738
         // ensure config class is set to something
739 739
         $config_class = $this->_set_config_class($config_class, $name);
740 740
         // run tests 1-4, 6, and 7 to verify all config params are set and valid
741
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
741
+        if ( ! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
742 742
             return null;
743 743
         }
744 744
         $config_option_name = $this->_generate_config_option_name($section, $name);
745 745
         // if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
746
-        if (! isset($this->_addon_option_names[ $config_option_name ])) {
747
-            $this->_addon_option_names[ $config_option_name ] = $config_class;
746
+        if ( ! isset($this->_addon_option_names[$config_option_name])) {
747
+            $this->_addon_option_names[$config_option_name] = $config_class;
748 748
             $this->update_addon_option_names();
749 749
         }
750 750
         // verify the incoming config object but suppress errors
751
-        if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
751
+        if ( ! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
752 752
             $config_obj = new $config_class();
753 753
         }
754 754
         if (get_option($config_option_name)) {
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
         // get class name of the incoming object
796 796
         $config_class = get_class($config_obj);
797 797
         // run tests 1-5 and 9 to verify config
798
-        if (! $this->_verify_config_params(
798
+        if ( ! $this->_verify_config_params(
799 799
             $section,
800 800
             $name,
801 801
             $config_class,
@@ -807,7 +807,7 @@  discard block
 block discarded – undo
807 807
         }
808 808
         $config_option_name = $this->_generate_config_option_name($section, $name);
809 809
         // check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
810
-        if (! isset($this->_addon_option_names[ $config_option_name ])) {
810
+        if ( ! isset($this->_addon_option_names[$config_option_name])) {
811 811
             // save new config to db
812 812
             if ($this->set_config($section, $name, $config_class, $config_obj)) {
813 813
                 return true;
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
                             'event_espresso'
834 834
                         ),
835 835
                         $config_class,
836
-                        'EE_Config->' . $section . '->' . $name
836
+                        'EE_Config->'.$section.'->'.$name
837 837
                     ),
838 838
                     __FILE__,
839 839
                     __FUNCTION__,
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
         // ensure config class is set to something
860 860
         $config_class = $this->_set_config_class($config_class, $name);
861 861
         // run tests 1-4, 6 and 7 to verify that all params have been set
862
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
862
+        if ( ! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
863 863
             return null;
864 864
         }
865 865
         // now test if the requested config object exists, but suppress errors
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
         // retrieve the wp-option for this config class.
905 905
         $config_option = maybe_unserialize(get_option($config_option_name, array()));
906 906
         if (empty($config_option)) {
907
-            EE_Config::log($config_option_name . '-NOT-FOUND');
907
+            EE_Config::log($config_option_name.'-NOT-FOUND');
908 908
         }
909 909
         return $config_option;
910 910
     }
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
             // copy incoming $_REQUEST and sanitize it so we can save it
923 923
             $_request = $_REQUEST;
924 924
             array_walk_recursive($_request, 'sanitize_text_field');
925
-            $config_log[ (string) microtime(true) ] = array(
925
+            $config_log[(string) microtime(true)] = array(
926 926
                 'config_name' => $config_option_name,
927 927
                 'request'     => $_request,
928 928
             );
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
      */
938 938
     public static function trim_log()
939 939
     {
940
-        if (! EE_Config::logging_enabled()) {
940
+        if ( ! EE_Config::logging_enabled()) {
941 941
             return;
942 942
         }
943 943
         $config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
     public static function get_page_for_posts()
962 962
     {
963 963
         $page_for_posts = get_option('page_for_posts');
964
-        if (! $page_for_posts) {
964
+        if ( ! $page_for_posts) {
965 965
             return 'posts';
966 966
         }
967 967
         /** @type WPDB $wpdb */
@@ -1011,20 +1011,20 @@  discard block
 block discarded – undo
1011 1011
     {
1012 1012
         // only init widgets on admin pages when not in complete maintenance, and
1013 1013
         // on frontend when not in any maintenance mode
1014
-        if (! EE_Maintenance_Mode::instance()->level()
1014
+        if ( ! EE_Maintenance_Mode::instance()->level()
1015 1015
             || (
1016 1016
                 is_admin()
1017 1017
                 && EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1018 1018
             )
1019 1019
         ) {
1020 1020
             // grab list of installed widgets
1021
-            $widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1021
+            $widgets_to_register = glob(EE_WIDGETS.'*', GLOB_ONLYDIR);
1022 1022
             // filter list of modules to register
1023 1023
             $widgets_to_register = apply_filters(
1024 1024
                 'FHEE__EE_Config__register_widgets__widgets_to_register',
1025 1025
                 $widgets_to_register
1026 1026
             );
1027
-            if (! empty($widgets_to_register)) {
1027
+            if ( ! empty($widgets_to_register)) {
1028 1028
                 // cycle thru widget folders
1029 1029
                 foreach ($widgets_to_register as $widget_path) {
1030 1030
                     // add to list of installed widget modules
@@ -1074,31 +1074,31 @@  discard block
 block discarded – undo
1074 1074
         // create classname from widget directory name
1075 1075
         $widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1076 1076
         // add class prefix
1077
-        $widget_class = 'EEW_' . $widget;
1077
+        $widget_class = 'EEW_'.$widget;
1078 1078
         // does the widget exist ?
1079
-        if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1079
+        if ( ! is_readable($widget_path.DS.$widget_class.$widget_ext)) {
1080 1080
             $msg = sprintf(
1081 1081
                 __(
1082 1082
                     'The requested %s widget file could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s',
1083 1083
                     'event_espresso'
1084 1084
                 ),
1085 1085
                 $widget_class,
1086
-                $widget_path . DS . $widget_class . $widget_ext
1086
+                $widget_path.DS.$widget_class.$widget_ext
1087 1087
             );
1088
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1088
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1089 1089
             return;
1090 1090
         }
1091 1091
         // load the widget class file
1092
-        require_once($widget_path . DS . $widget_class . $widget_ext);
1092
+        require_once($widget_path.DS.$widget_class.$widget_ext);
1093 1093
         // verify that class exists
1094
-        if (! class_exists($widget_class)) {
1094
+        if ( ! class_exists($widget_class)) {
1095 1095
             $msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1096
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1096
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1097 1097
             return;
1098 1098
         }
1099 1099
         register_widget($widget_class);
1100 1100
         // add to array of registered widgets
1101
-        EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1101
+        EE_Registry::instance()->widgets->{$widget_class} = $widget_path.DS.$widget_class.$widget_ext;
1102 1102
     }
1103 1103
 
1104 1104
 
@@ -1111,18 +1111,18 @@  discard block
 block discarded – undo
1111 1111
     private function _register_modules()
1112 1112
     {
1113 1113
         // grab list of installed modules
1114
-        $modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1114
+        $modules_to_register = glob(EE_MODULES.'*', GLOB_ONLYDIR);
1115 1115
         // filter list of modules to register
1116 1116
         $modules_to_register = apply_filters(
1117 1117
             'FHEE__EE_Config__register_modules__modules_to_register',
1118 1118
             $modules_to_register
1119 1119
         );
1120
-        if (! empty($modules_to_register)) {
1120
+        if ( ! empty($modules_to_register)) {
1121 1121
             // loop through folders
1122 1122
             foreach ($modules_to_register as $module_path) {
1123 1123
                 /**TEMPORARILY EXCLUDE gateways from modules for time being**/
1124
-                if ($module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1125
-                    && $module_path !== EE_MODULES . 'gateways'
1124
+                if ($module_path !== EE_MODULES.'zzz-copy-this-module-template'
1125
+                    && $module_path !== EE_MODULES.'gateways'
1126 1126
                 ) {
1127 1127
                     // add to list of installed modules
1128 1128
                     EE_Config::register_module($module_path);
@@ -1159,25 +1159,25 @@  discard block
 block discarded – undo
1159 1159
             // remove last segment
1160 1160
             array_pop($module_path);
1161 1161
             // glue it back together
1162
-            $module_path = implode(DS, $module_path) . DS;
1162
+            $module_path = implode(DS, $module_path).DS;
1163 1163
             // take first segment from file name pieces and sanitize it
1164 1164
             $module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1165 1165
             // ensure class prefix is added
1166
-            $module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1166
+            $module_class = strpos($module, 'EED_') !== 0 ? 'EED_'.$module : $module;
1167 1167
         } else {
1168 1168
             // we need to generate the filename based off of the folder name
1169 1169
             // grab and sanitize module name
1170 1170
             $module = strtolower(basename($module_path));
1171 1171
             $module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1172 1172
             // like trailingslashit()
1173
-            $module_path = rtrim($module_path, DS) . DS;
1173
+            $module_path = rtrim($module_path, DS).DS;
1174 1174
             // create classname from module directory name
1175 1175
             $module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1176 1176
             // add class prefix
1177
-            $module_class = 'EED_' . $module;
1177
+            $module_class = 'EED_'.$module;
1178 1178
         }
1179 1179
         // does the module exist ?
1180
-        if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1180
+        if ( ! is_readable($module_path.DS.$module_class.$module_ext)) {
1181 1181
             $msg = sprintf(
1182 1182
                 __(
1183 1183
                     'The requested %s module file could not be found or is not readable due to file permissions.',
@@ -1185,19 +1185,19 @@  discard block
 block discarded – undo
1185 1185
                 ),
1186 1186
                 $module
1187 1187
             );
1188
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1188
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1189 1189
             return false;
1190 1190
         }
1191 1191
         // load the module class file
1192
-        require_once($module_path . $module_class . $module_ext);
1192
+        require_once($module_path.$module_class.$module_ext);
1193 1193
         // verify that class exists
1194
-        if (! class_exists($module_class)) {
1194
+        if ( ! class_exists($module_class)) {
1195 1195
             $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1196
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1196
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1197 1197
             return false;
1198 1198
         }
1199 1199
         // add to array of registered modules
1200
-        EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1200
+        EE_Registry::instance()->modules->{$module_class} = $module_path.$module_class.$module_ext;
1201 1201
         do_action(
1202 1202
             'AHEE__EE_Config__register_module__complete',
1203 1203
             $module_class,
@@ -1248,26 +1248,26 @@  discard block
 block discarded – undo
1248 1248
     {
1249 1249
         do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1250 1250
         $module = str_replace('EED_', '', $module);
1251
-        $module_class = 'EED_' . $module;
1252
-        if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1251
+        $module_class = 'EED_'.$module;
1252
+        if ( ! isset(EE_Registry::instance()->modules->{$module_class})) {
1253 1253
             $msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1254
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1254
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1255 1255
             return false;
1256 1256
         }
1257 1257
         if (empty($route)) {
1258 1258
             $msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1259
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1259
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1260 1260
             return false;
1261 1261
         }
1262
-        if (! method_exists('EED_' . $module, $method_name)) {
1262
+        if ( ! method_exists('EED_'.$module, $method_name)) {
1263 1263
             $msg = sprintf(
1264 1264
                 __('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1265 1265
                 $route
1266 1266
             );
1267
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1267
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1268 1268
             return false;
1269 1269
         }
1270
-        EE_Config::$_module_route_map[ (string) $key ][ (string) $route ] = array('EED_' . $module, $method_name);
1270
+        EE_Config::$_module_route_map[(string) $key][(string) $route] = array('EED_'.$module, $method_name);
1271 1271
         return true;
1272 1272
     }
1273 1273
 
@@ -1284,8 +1284,8 @@  discard block
 block discarded – undo
1284 1284
     {
1285 1285
         do_action('AHEE__EE_Config__get_route__begin', $route);
1286 1286
         $route = (string) apply_filters('FHEE__EE_Config__get_route', $route);
1287
-        if (isset(EE_Config::$_module_route_map[ $key ][ $route ])) {
1288
-            return EE_Config::$_module_route_map[ $key ][ $route ];
1287
+        if (isset(EE_Config::$_module_route_map[$key][$route])) {
1288
+            return EE_Config::$_module_route_map[$key][$route];
1289 1289
         }
1290 1290
         return null;
1291 1291
     }
@@ -1317,47 +1317,47 @@  discard block
 block discarded – undo
1317 1317
     public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1318 1318
     {
1319 1319
         do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1320
-        if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1320
+        if ( ! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1321 1321
             $msg = sprintf(
1322 1322
                 __('The module route %s for this forward has not been registered.', 'event_espresso'),
1323 1323
                 $route
1324 1324
             );
1325
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1325
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1326 1326
             return false;
1327 1327
         }
1328 1328
         if (empty($forward)) {
1329 1329
             $msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1330
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1330
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1331 1331
             return false;
1332 1332
         }
1333 1333
         if (is_array($forward)) {
1334
-            if (! isset($forward[1])) {
1334
+            if ( ! isset($forward[1])) {
1335 1335
                 $msg = sprintf(
1336 1336
                     __('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1337 1337
                     $route
1338 1338
                 );
1339
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1339
+                EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1340 1340
                 return false;
1341 1341
             }
1342
-            if (! method_exists($forward[0], $forward[1])) {
1342
+            if ( ! method_exists($forward[0], $forward[1])) {
1343 1343
                 $msg = sprintf(
1344 1344
                     __('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1345 1345
                     $forward[1],
1346 1346
                     $route
1347 1347
                 );
1348
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1348
+                EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1349 1349
                 return false;
1350 1350
             }
1351
-        } elseif (! function_exists($forward)) {
1351
+        } elseif ( ! function_exists($forward)) {
1352 1352
             $msg = sprintf(
1353 1353
                 __('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1354 1354
                 $forward,
1355 1355
                 $route
1356 1356
             );
1357
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1357
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1358 1358
             return false;
1359 1359
         }
1360
-        EE_Config::$_module_forward_map[ $key ][ $route ][ absint($status) ] = $forward;
1360
+        EE_Config::$_module_forward_map[$key][$route][absint($status)] = $forward;
1361 1361
         return true;
1362 1362
     }
1363 1363
 
@@ -1375,10 +1375,10 @@  discard block
 block discarded – undo
1375 1375
     public static function get_forward($route = null, $status = 0, $key = 'ee')
1376 1376
     {
1377 1377
         do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1378
-        if (isset(EE_Config::$_module_forward_map[ $key ][ $route ][ $status ])) {
1378
+        if (isset(EE_Config::$_module_forward_map[$key][$route][$status])) {
1379 1379
             return apply_filters(
1380 1380
                 'FHEE__EE_Config__get_forward',
1381
-                EE_Config::$_module_forward_map[ $key ][ $route ][ $status ],
1381
+                EE_Config::$_module_forward_map[$key][$route][$status],
1382 1382
                 $route,
1383 1383
                 $status
1384 1384
             );
@@ -1402,15 +1402,15 @@  discard block
 block discarded – undo
1402 1402
     public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1403 1403
     {
1404 1404
         do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1405
-        if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1405
+        if ( ! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1406 1406
             $msg = sprintf(
1407 1407
                 __('The module route %s for this view has not been registered.', 'event_espresso'),
1408 1408
                 $route
1409 1409
             );
1410
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1410
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1411 1411
             return false;
1412 1412
         }
1413
-        if (! is_readable($view)) {
1413
+        if ( ! is_readable($view)) {
1414 1414
             $msg = sprintf(
1415 1415
                 __(
1416 1416
                     'The %s view file could not be found or is not readable due to file permissions.',
@@ -1418,10 +1418,10 @@  discard block
 block discarded – undo
1418 1418
                 ),
1419 1419
                 $view
1420 1420
             );
1421
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1421
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
1422 1422
             return false;
1423 1423
         }
1424
-        EE_Config::$_module_view_map[ $key ][ $route ][ absint($status) ] = $view;
1424
+        EE_Config::$_module_view_map[$key][$route][absint($status)] = $view;
1425 1425
         return true;
1426 1426
     }
1427 1427
 
@@ -1439,10 +1439,10 @@  discard block
 block discarded – undo
1439 1439
     public static function get_view($route = null, $status = 0, $key = 'ee')
1440 1440
     {
1441 1441
         do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1442
-        if (isset(EE_Config::$_module_view_map[ $key ][ $route ][ $status ])) {
1442
+        if (isset(EE_Config::$_module_view_map[$key][$route][$status])) {
1443 1443
             return apply_filters(
1444 1444
                 'FHEE__EE_Config__get_view',
1445
-                EE_Config::$_module_view_map[ $key ][ $route ][ $status ],
1445
+                EE_Config::$_module_view_map[$key][$route][$status],
1446 1446
                 $route,
1447 1447
                 $status
1448 1448
             );
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
     public static function getLegacyShortcodesManager()
1470 1470
     {
1471 1471
 
1472
-        if (! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1472
+        if ( ! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1473 1473
             EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1474 1474
                 EE_Registry::instance()
1475 1475
             );
@@ -1516,7 +1516,7 @@  discard block
 block discarded – undo
1516 1516
      */
1517 1517
     public function get_pretty($property)
1518 1518
     {
1519
-        if (! property_exists($this, $property)) {
1519
+        if ( ! property_exists($this, $property)) {
1520 1520
             throw new EE_Error(
1521 1521
                 sprintf(
1522 1522
                     __(
@@ -1745,11 +1745,11 @@  discard block
 block discarded – undo
1745 1745
      */
1746 1746
     public function reg_page_url()
1747 1747
     {
1748
-        if (! $this->reg_page_url) {
1748
+        if ( ! $this->reg_page_url) {
1749 1749
             $this->reg_page_url = add_query_arg(
1750 1750
                 array('uts' => time()),
1751 1751
                 get_permalink($this->reg_page_id)
1752
-            ) . '#checkout';
1752
+            ).'#checkout';
1753 1753
         }
1754 1754
         return $this->reg_page_url;
1755 1755
     }
@@ -1765,7 +1765,7 @@  discard block
 block discarded – undo
1765 1765
      */
1766 1766
     public function txn_page_url($query_args = array())
1767 1767
     {
1768
-        if (! $this->txn_page_url) {
1768
+        if ( ! $this->txn_page_url) {
1769 1769
             $this->txn_page_url = get_permalink($this->txn_page_id);
1770 1770
         }
1771 1771
         if ($query_args) {
@@ -1786,7 +1786,7 @@  discard block
 block discarded – undo
1786 1786
      */
1787 1787
     public function thank_you_page_url($query_args = array())
1788 1788
     {
1789
-        if (! $this->thank_you_page_url) {
1789
+        if ( ! $this->thank_you_page_url) {
1790 1790
             $this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1791 1791
         }
1792 1792
         if ($query_args) {
@@ -1805,7 +1805,7 @@  discard block
 block discarded – undo
1805 1805
      */
1806 1806
     public function cancel_page_url()
1807 1807
     {
1808
-        if (! $this->cancel_page_url) {
1808
+        if ( ! $this->cancel_page_url) {
1809 1809
             $this->cancel_page_url = get_permalink($this->cancel_page_id);
1810 1810
         }
1811 1811
         return $this->cancel_page_url;
@@ -1848,13 +1848,13 @@  discard block
 block discarded – undo
1848 1848
         $current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1849 1849
         $option = self::OPTION_NAME_UXIP;
1850 1850
         // set correct table for query
1851
-        $table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1851
+        $table_name = $wpdb->get_blog_prefix($current_main_site_id).'options';
1852 1852
         // rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1853 1853
         // get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1854 1854
         // re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1855 1855
         // this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1856 1856
         // for the purpose of caching.
1857
-        $pre = apply_filters('pre_option_' . $option, false, $option);
1857
+        $pre = apply_filters('pre_option_'.$option, false, $option);
1858 1858
         if (false !== $pre) {
1859 1859
             EE_Core_Config::$ee_ueip_option = $pre;
1860 1860
             return EE_Core_Config::$ee_ueip_option;
@@ -1868,10 +1868,10 @@  discard block
 block discarded – undo
1868 1868
         if (is_object($row)) {
1869 1869
             $value = $row->option_value;
1870 1870
         } else { // option does not exist so use default.
1871
-            EE_Core_Config::$ee_ueip_option =  apply_filters('default_option_' . $option, false, $option);
1871
+            EE_Core_Config::$ee_ueip_option = apply_filters('default_option_'.$option, false, $option);
1872 1872
             return EE_Core_Config::$ee_ueip_option;
1873 1873
         }
1874
-        EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1874
+        EE_Core_Config::$ee_ueip_option = apply_filters('option_'.$option, maybe_unserialize($value), $option);
1875 1875
         return EE_Core_Config::$ee_ueip_option;
1876 1876
     }
1877 1877
 
@@ -2140,37 +2140,37 @@  discard block
 block discarded – undo
2140 2140
         // but override if requested
2141 2141
         $CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2142 2142
         // so if that all went well, and we are not in M-Mode (cuz you can't query the db in M-Mode) and double-check the countries table exists
2143
-        if (! empty($CNT_ISO)
2143
+        if ( ! empty($CNT_ISO)
2144 2144
             && EE_Maintenance_Mode::instance()->models_can_query()
2145 2145
             && $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2146 2146
         ) {
2147 2147
             // retrieve the country settings from the db, just in case they have been customized
2148 2148
             $country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2149 2149
             if ($country instanceof EE_Country) {
2150
-                $this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2151
-                $this->name = $country->currency_name_single();    // Dollar
2152
-                $this->plural = $country->currency_name_plural();    // Dollars
2153
-                $this->sign = $country->currency_sign();            // currency sign: $
2150
+                $this->code = $country->currency_code(); // currency code: USD, CAD, EUR
2151
+                $this->name = $country->currency_name_single(); // Dollar
2152
+                $this->plural = $country->currency_name_plural(); // Dollars
2153
+                $this->sign = $country->currency_sign(); // currency sign: $
2154 2154
                 $this->sign_b4 = $country->currency_sign_before(
2155
-                );        // currency sign before or after: $TRUE  or  FALSE$
2156
-                $this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2155
+                ); // currency sign before or after: $TRUE  or  FALSE$
2156
+                $this->dec_plc = $country->currency_decimal_places(); // decimal places: 2 = 0.00  3 = 0.000
2157 2157
                 $this->dec_mrk = $country->currency_decimal_mark(
2158
-                );    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2158
+                ); // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2159 2159
                 $this->thsnds = $country->currency_thousands_separator(
2160
-                );    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2160
+                ); // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2161 2161
             }
2162 2162
         }
2163 2163
         // fallback to hardcoded defaults, in case the above failed
2164 2164
         if (empty($this->code)) {
2165 2165
             // set default currency settings
2166
-            $this->code = 'USD';    // currency code: USD, CAD, EUR
2167
-            $this->name = __('Dollar', 'event_espresso');    // Dollar
2168
-            $this->plural = __('Dollars', 'event_espresso');    // Dollars
2169
-            $this->sign = '$';    // currency sign: $
2170
-            $this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2171
-            $this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2172
-            $this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2173
-            $this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2166
+            $this->code = 'USD'; // currency code: USD, CAD, EUR
2167
+            $this->name = __('Dollar', 'event_espresso'); // Dollar
2168
+            $this->plural = __('Dollars', 'event_espresso'); // Dollars
2169
+            $this->sign = '$'; // currency sign: $
2170
+            $this->sign_b4 = true; // currency sign before or after: $TRUE  or  FALSE$
2171
+            $this->dec_plc = 2; // decimal places: 2 = 0.00  3 = 0.000
2172
+            $this->dec_mrk = '.'; // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2173
+            $this->thsnds = ','; // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2174 2174
         }
2175 2175
     }
2176 2176
 }
@@ -2429,8 +2429,8 @@  discard block
 block discarded – undo
2429 2429
             $closing_a_tag = '';
2430 2430
             if (function_exists('get_privacy_policy_url')) {
2431 2431
                 $privacy_page_url = get_privacy_policy_url();
2432
-                if (! empty($privacy_page_url)) {
2433
-                    $opening_a_tag = '<a href="' . $privacy_page_url . '" target="_blank">';
2432
+                if ( ! empty($privacy_page_url)) {
2433
+                    $opening_a_tag = '<a href="'.$privacy_page_url.'" target="_blank">';
2434 2434
                     $closing_a_tag = '</a>';
2435 2435
                 }
2436 2436
             }
@@ -2642,7 +2642,7 @@  discard block
 block discarded – undo
2642 2642
     public function log_file_name($reset = false)
2643 2643
     {
2644 2644
         if (empty($this->log_file_name) || $reset) {
2645
-            $this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2645
+            $this->log_file_name = sanitize_key('espresso_log_'.md5(uniqid('', true))).'.txt';
2646 2646
             EE_Config::instance()->update_espresso_config(false, false);
2647 2647
         }
2648 2648
         return $this->log_file_name;
@@ -2656,7 +2656,7 @@  discard block
 block discarded – undo
2656 2656
     public function debug_file_name($reset = false)
2657 2657
     {
2658 2658
         if (empty($this->debug_file_name) || $reset) {
2659
-            $this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2659
+            $this->debug_file_name = sanitize_key('espresso_debug_'.md5(uniqid('', true))).'.txt';
2660 2660
             EE_Config::instance()->update_espresso_config(false, false);
2661 2661
         }
2662 2662
         return $this->debug_file_name;
@@ -2860,21 +2860,21 @@  discard block
 block discarded – undo
2860 2860
         $this->use_google_maps = true;
2861 2861
         $this->google_map_api_key = '';
2862 2862
         // for event details pages (reg page)
2863
-        $this->event_details_map_width = 585;            // ee_map_width_single
2864
-        $this->event_details_map_height = 362;            // ee_map_height_single
2865
-        $this->event_details_map_zoom = 14;            // ee_map_zoom_single
2866
-        $this->event_details_display_nav = true;            // ee_map_nav_display_single
2867
-        $this->event_details_nav_size = false;            // ee_map_nav_size_single
2868
-        $this->event_details_control_type = 'default';        // ee_map_type_control_single
2869
-        $this->event_details_map_align = 'center';            // ee_map_align_single
2863
+        $this->event_details_map_width = 585; // ee_map_width_single
2864
+        $this->event_details_map_height = 362; // ee_map_height_single
2865
+        $this->event_details_map_zoom = 14; // ee_map_zoom_single
2866
+        $this->event_details_display_nav = true; // ee_map_nav_display_single
2867
+        $this->event_details_nav_size = false; // ee_map_nav_size_single
2868
+        $this->event_details_control_type = 'default'; // ee_map_type_control_single
2869
+        $this->event_details_map_align = 'center'; // ee_map_align_single
2870 2870
         // for event list pages
2871
-        $this->event_list_map_width = 300;            // ee_map_width
2872
-        $this->event_list_map_height = 185;        // ee_map_height
2873
-        $this->event_list_map_zoom = 12;            // ee_map_zoom
2874
-        $this->event_list_display_nav = false;        // ee_map_nav_display
2875
-        $this->event_list_nav_size = true;            // ee_map_nav_size
2876
-        $this->event_list_control_type = 'dropdown';        // ee_map_type_control
2877
-        $this->event_list_map_align = 'center';            // ee_map_align
2871
+        $this->event_list_map_width = 300; // ee_map_width
2872
+        $this->event_list_map_height = 185; // ee_map_height
2873
+        $this->event_list_map_zoom = 12; // ee_map_zoom
2874
+        $this->event_list_display_nav = false; // ee_map_nav_display
2875
+        $this->event_list_nav_size = true; // ee_map_nav_size
2876
+        $this->event_list_control_type = 'dropdown'; // ee_map_type_control
2877
+        $this->event_list_map_align = 'center'; // ee_map_align
2878 2878
     }
2879 2879
 }
2880 2880
 
@@ -3166,7 +3166,7 @@  discard block
 block discarded – undo
3166 3166
      */
3167 3167
     public function max_input_vars_limit_check($input_count = 0)
3168 3168
     {
3169
-        if (! empty($this->php->max_input_vars)
3169
+        if ( ! empty($this->php->max_input_vars)
3170 3170
             && ($input_count >= $this->php->max_input_vars)
3171 3171
             && (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3172 3172
         ) {
Please login to merge, or discard this patch.
Indentation   +3146 added lines, -3146 removed lines patch added patch discarded remove patch
@@ -14,2509 +14,2509 @@  discard block
 block discarded – undo
14 14
 final class EE_Config implements ResettableInterface
15 15
 {
16 16
 
17
-    const OPTION_NAME = 'ee_config';
18
-
19
-    const LOG_NAME = 'ee_config_log';
20
-
21
-    const LOG_LENGTH = 100;
22
-
23
-    const ADDON_OPTION_NAMES = 'ee_config_option_names';
24
-
25
-    /**
26
-     *    instance of the EE_Config object
27
-     *
28
-     * @var    EE_Config $_instance
29
-     * @access    private
30
-     */
31
-    private static $_instance;
32
-
33
-    /**
34
-     * @var boolean $_logging_enabled
35
-     */
36
-    private static $_logging_enabled = false;
37
-
38
-    /**
39
-     * @var LegacyShortcodesManager $legacy_shortcodes_manager
40
-     */
41
-    private $legacy_shortcodes_manager;
42
-
43
-    /**
44
-     * An StdClass whose property names are addon slugs,
45
-     * and values are their config classes
46
-     *
47
-     * @var StdClass
48
-     */
49
-    public $addons;
50
-
51
-    /**
52
-     * @var EE_Admin_Config
53
-     */
54
-    public $admin;
55
-
56
-    /**
57
-     * @var EE_Core_Config
58
-     */
59
-    public $core;
60
-
61
-    /**
62
-     * @var EE_Currency_Config
63
-     */
64
-    public $currency;
65
-
66
-    /**
67
-     * @var EE_Organization_Config
68
-     */
69
-    public $organization;
70
-
71
-    /**
72
-     * @var EE_Registration_Config
73
-     */
74
-    public $registration;
75
-
76
-    /**
77
-     * @var EE_Template_Config
78
-     */
79
-    public $template_settings;
80
-
81
-    /**
82
-     * Holds EE environment values.
83
-     *
84
-     * @var EE_Environment_Config
85
-     */
86
-    public $environment;
87
-
88
-    /**
89
-     * settings pertaining to Google maps
90
-     *
91
-     * @var EE_Map_Config
92
-     */
93
-    public $map_settings;
94
-
95
-    /**
96
-     * settings pertaining to Taxes
97
-     *
98
-     * @var EE_Tax_Config
99
-     */
100
-    public $tax_settings;
101
-
102
-    /**
103
-     * Settings pertaining to global messages settings.
104
-     *
105
-     * @var EE_Messages_Config
106
-     */
107
-    public $messages;
108
-
109
-    /**
110
-     * @deprecated
111
-     * @var EE_Gateway_Config
112
-     */
113
-    public $gateway;
114
-
115
-    /**
116
-     * @var    array $_addon_option_names
117
-     * @access    private
118
-     */
119
-    private $_addon_option_names = array();
120
-
121
-    /**
122
-     * @var    array $_module_route_map
123
-     * @access    private
124
-     */
125
-    private static $_module_route_map = array();
126
-
127
-    /**
128
-     * @var    array $_module_forward_map
129
-     * @access    private
130
-     */
131
-    private static $_module_forward_map = array();
132
-
133
-    /**
134
-     * @var    array $_module_view_map
135
-     * @access    private
136
-     */
137
-    private static $_module_view_map = array();
138
-
139
-
140
-    /**
141
-     * @singleton method used to instantiate class object
142
-     * @access    public
143
-     * @return EE_Config instance
144
-     */
145
-    public static function instance()
146
-    {
147
-        // check if class object is instantiated, and instantiated properly
148
-        if (! self::$_instance instanceof EE_Config) {
149
-            self::$_instance = new self();
150
-        }
151
-        return self::$_instance;
152
-    }
153
-
154
-
155
-    /**
156
-     * Resets the config
157
-     *
158
-     * @param bool    $hard_reset    if TRUE, sets EE_CONFig back to its original settings in the database. If FALSE
159
-     *                               (default) leaves the database alone, and merely resets the EE_Config object to
160
-     *                               reflect its state in the database
161
-     * @param boolean $reinstantiate if TRUE (default) call instance() and return it. Otherwise, just leave
162
-     *                               $_instance as NULL. Useful in case you want to forget about the old instance on
163
-     *                               EE_Config, but might not be ready to instantiate EE_Config currently (eg if the
164
-     *                               site was put into maintenance mode)
165
-     * @return EE_Config
166
-     */
167
-    public static function reset($hard_reset = false, $reinstantiate = true)
168
-    {
169
-        if (self::$_instance instanceof EE_Config) {
170
-            if ($hard_reset) {
171
-                self::$_instance->legacy_shortcodes_manager = null;
172
-                self::$_instance->_addon_option_names = array();
173
-                self::$_instance->_initialize_config();
174
-                self::$_instance->update_espresso_config();
175
-            }
176
-            self::$_instance->update_addon_option_names();
177
-        }
178
-        self::$_instance = null;
179
-        // we don't need to reset the static properties imo because those should
180
-        // only change when a module is added or removed. Currently we don't
181
-        // support removing a module during a request when it previously existed
182
-        if ($reinstantiate) {
183
-            return self::instance();
184
-        } else {
185
-            return null;
186
-        }
187
-    }
188
-
189
-
190
-    /**
191
-     *    class constructor
192
-     *
193
-     * @access    private
194
-     */
195
-    private function __construct()
196
-    {
197
-        do_action('AHEE__EE_Config__construct__begin', $this);
198
-        EE_Config::$_logging_enabled = apply_filters('FHEE__EE_Config___construct__logging_enabled', false);
199
-        // setup empty config classes
200
-        $this->_initialize_config();
201
-        // load existing EE site settings
202
-        $this->_load_core_config();
203
-        // confirm everything loaded correctly and set filtered defaults if not
204
-        $this->_verify_config();
205
-        //  register shortcodes and modules
206
-        add_action(
207
-            'AHEE__EE_System__register_shortcodes_modules_and_widgets',
208
-            array($this, 'register_shortcodes_and_modules'),
209
-            999
210
-        );
211
-        //  initialize shortcodes and modules
212
-        add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'initialize_shortcodes_and_modules'));
213
-        // register widgets
214
-        add_action('widgets_init', array($this, 'widgets_init'), 10);
215
-        // shutdown
216
-        add_action('shutdown', array($this, 'shutdown'), 10);
217
-        // construct__end hook
218
-        do_action('AHEE__EE_Config__construct__end', $this);
219
-        // hardcoded hack
220
-        $this->template_settings->current_espresso_theme = 'Espresso_Arabica_2014';
221
-    }
222
-
223
-
224
-    /**
225
-     * @return boolean
226
-     */
227
-    public static function logging_enabled()
228
-    {
229
-        return self::$_logging_enabled;
230
-    }
231
-
232
-
233
-    /**
234
-     * use to get the current theme if needed from static context
235
-     *
236
-     * @return string current theme set.
237
-     */
238
-    public static function get_current_theme()
239
-    {
240
-        return isset(self::$_instance->template_settings->current_espresso_theme)
241
-            ? self::$_instance->template_settings->current_espresso_theme : 'Espresso_Arabica_2014';
242
-    }
243
-
244
-
245
-    /**
246
-     *        _initialize_config
247
-     *
248
-     * @access private
249
-     * @return void
250
-     */
251
-    private function _initialize_config()
252
-    {
253
-        EE_Config::trim_log();
254
-        // set defaults
255
-        $this->_addon_option_names = get_option(EE_Config::ADDON_OPTION_NAMES, array());
256
-        $this->addons = new stdClass();
257
-        // set _module_route_map
258
-        EE_Config::$_module_route_map = array();
259
-        // set _module_forward_map
260
-        EE_Config::$_module_forward_map = array();
261
-        // set _module_view_map
262
-        EE_Config::$_module_view_map = array();
263
-    }
264
-
265
-
266
-    /**
267
-     *        load core plugin configuration
268
-     *
269
-     * @access private
270
-     * @return void
271
-     */
272
-    private function _load_core_config()
273
-    {
274
-        // load_core_config__start hook
275
-        do_action('AHEE__EE_Config___load_core_config__start', $this);
276
-        $espresso_config = $this->get_espresso_config();
277
-        foreach ($espresso_config as $config => $settings) {
278
-            // load_core_config__start hook
279
-            $settings = apply_filters(
280
-                'FHEE__EE_Config___load_core_config__config_settings',
281
-                $settings,
282
-                $config,
283
-                $this
284
-            );
285
-            if (is_object($settings) && property_exists($this, $config)) {
286
-                $this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__' . $config, $settings);
287
-                // call configs populate method to ensure any defaults are set for empty values.
288
-                if (method_exists($settings, 'populate')) {
289
-                    $this->{$config}->populate();
290
-                }
291
-                if (method_exists($settings, 'do_hooks')) {
292
-                    $this->{$config}->do_hooks();
293
-                }
294
-            }
295
-        }
296
-        if (apply_filters('FHEE__EE_Config___load_core_config__update_espresso_config', false)) {
297
-            $this->update_espresso_config();
298
-        }
299
-        // load_core_config__end hook
300
-        do_action('AHEE__EE_Config___load_core_config__end', $this);
301
-    }
302
-
303
-
304
-    /**
305
-     *    _verify_config
306
-     *
307
-     * @access    protected
308
-     * @return    void
309
-     */
310
-    protected function _verify_config()
311
-    {
312
-        $this->core = $this->core instanceof EE_Core_Config
313
-            ? $this->core
314
-            : new EE_Core_Config();
315
-        $this->core = apply_filters('FHEE__EE_Config___initialize_config__core', $this->core);
316
-        $this->organization = $this->organization instanceof EE_Organization_Config
317
-            ? $this->organization
318
-            : new EE_Organization_Config();
319
-        $this->organization = apply_filters(
320
-            'FHEE__EE_Config___initialize_config__organization',
321
-            $this->organization
322
-        );
323
-        $this->currency = $this->currency instanceof EE_Currency_Config
324
-            ? $this->currency
325
-            : new EE_Currency_Config();
326
-        $this->currency = apply_filters('FHEE__EE_Config___initialize_config__currency', $this->currency);
327
-        $this->registration = $this->registration instanceof EE_Registration_Config
328
-            ? $this->registration
329
-            : new EE_Registration_Config();
330
-        $this->registration = apply_filters(
331
-            'FHEE__EE_Config___initialize_config__registration',
332
-            $this->registration
333
-        );
334
-        $this->admin = $this->admin instanceof EE_Admin_Config
335
-            ? $this->admin
336
-            : new EE_Admin_Config();
337
-        $this->admin = apply_filters('FHEE__EE_Config___initialize_config__admin', $this->admin);
338
-        $this->template_settings = $this->template_settings instanceof EE_Template_Config
339
-            ? $this->template_settings
340
-            : new EE_Template_Config();
341
-        $this->template_settings = apply_filters(
342
-            'FHEE__EE_Config___initialize_config__template_settings',
343
-            $this->template_settings
344
-        );
345
-        $this->map_settings = $this->map_settings instanceof EE_Map_Config
346
-            ? $this->map_settings
347
-            : new EE_Map_Config();
348
-        $this->map_settings = apply_filters(
349
-            'FHEE__EE_Config___initialize_config__map_settings',
350
-            $this->map_settings
351
-        );
352
-        $this->environment = $this->environment instanceof EE_Environment_Config
353
-            ? $this->environment
354
-            : new EE_Environment_Config();
355
-        $this->environment = apply_filters(
356
-            'FHEE__EE_Config___initialize_config__environment',
357
-            $this->environment
358
-        );
359
-        $this->tax_settings = $this->tax_settings instanceof EE_Tax_Config
360
-            ? $this->tax_settings
361
-            : new EE_Tax_Config();
362
-        $this->tax_settings = apply_filters(
363
-            'FHEE__EE_Config___initialize_config__tax_settings',
364
-            $this->tax_settings
365
-        );
366
-        $this->messages = apply_filters('FHEE__EE_Config__initialize_config__messages', $this->messages);
367
-        $this->messages = $this->messages instanceof EE_Messages_Config
368
-            ? $this->messages
369
-            : new EE_Messages_Config();
370
-        $this->gateway = $this->gateway instanceof EE_Gateway_Config
371
-            ? $this->gateway
372
-            : new EE_Gateway_Config();
373
-        $this->gateway = apply_filters('FHEE__EE_Config___initialize_config__gateway', $this->gateway);
374
-        $this->legacy_shortcodes_manager = null;
375
-    }
376
-
377
-
378
-    /**
379
-     *    get_espresso_config
380
-     *
381
-     * @access    public
382
-     * @return    array of espresso config stuff
383
-     */
384
-    public function get_espresso_config()
385
-    {
386
-        // grab espresso configuration
387
-        return apply_filters(
388
-            'FHEE__EE_Config__get_espresso_config__CFG',
389
-            get_option(EE_Config::OPTION_NAME, array())
390
-        );
391
-    }
392
-
393
-
394
-    /**
395
-     *    double_check_config_comparison
396
-     *
397
-     * @access    public
398
-     * @param string $option
399
-     * @param        $old_value
400
-     * @param        $value
401
-     */
402
-    public function double_check_config_comparison($option = '', $old_value, $value)
403
-    {
404
-        // make sure we're checking the ee config
405
-        if ($option === EE_Config::OPTION_NAME) {
406
-            // run a loose comparison of the old value against the new value for type and properties,
407
-            // but NOT exact instance like WP update_option does (ie: NOT type safe comparison)
408
-            if ($value != $old_value) {
409
-                // if they are NOT the same, then remove the hook,
410
-                // which means the subsequent update results will be based solely on the update query results
411
-                // the reason we do this is because, as stated above,
412
-                // WP update_option performs an exact instance comparison (===) on any update values passed to it
413
-                // this happens PRIOR to serialization and any subsequent update.
414
-                // If values are found to match their previous old value,
415
-                // then WP bails before performing any update.
416
-                // Since we are passing the EE_Config object, it is comparing the EXACT instance of the saved version
417
-                // it just pulled from the db, with the one being passed to it (which will not match).
418
-                // HOWEVER, once the object is serialized and passed off to MySQL to update,
419
-                // MySQL MAY ALSO NOT perform the update because
420
-                // the string it sees in the db looks the same as the new one it has been passed!!!
421
-                // This results in the query returning an "affected rows" value of ZERO,
422
-                // which gets returned immediately by WP update_option and looks like an error.
423
-                remove_action('update_option', array($this, 'check_config_updated'));
424
-            }
425
-        }
426
-    }
427
-
428
-
429
-    /**
430
-     *    update_espresso_config
431
-     *
432
-     * @access   public
433
-     */
434
-    protected function _reset_espresso_addon_config()
435
-    {
436
-        $this->_addon_option_names = array();
437
-        foreach ($this->addons as $addon_name => $addon_config_obj) {
438
-            $addon_config_obj = maybe_unserialize($addon_config_obj);
439
-            if ($addon_config_obj instanceof EE_Config_Base) {
440
-                $this->update_config('addons', $addon_name, $addon_config_obj, false);
441
-            }
442
-            $this->addons->{$addon_name} = null;
443
-        }
444
-    }
445
-
446
-
447
-    /**
448
-     *    update_espresso_config
449
-     *
450
-     * @access   public
451
-     * @param   bool $add_success
452
-     * @param   bool $add_error
453
-     * @return   bool
454
-     */
455
-    public function update_espresso_config($add_success = false, $add_error = true)
456
-    {
457
-        // don't allow config updates during WP heartbeats
458
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
459
-            return false;
460
-        }
461
-        // commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
462
-        // $clone = clone( self::$_instance );
463
-        // self::$_instance = NULL;
464
-        do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
465
-        $this->_reset_espresso_addon_config();
466
-        // hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
467
-        // but BEFORE the actual update occurs
468
-        add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
469
-        // don't want to persist legacy_shortcodes_manager, but don't want to lose it either
470
-        $legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
471
-        $this->legacy_shortcodes_manager = null;
472
-        // now update "ee_config"
473
-        $saved = update_option(EE_Config::OPTION_NAME, $this);
474
-        $this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
475
-        EE_Config::log(EE_Config::OPTION_NAME);
476
-        // if not saved... check if the hook we just added still exists;
477
-        // if it does, it means one of two things:
478
-        // that update_option bailed at the($value === $old_value) conditional,
479
-        // or...
480
-        // the db update query returned 0 rows affected
481
-        // (probably because the data  value was the same from it's perspective)
482
-        // so the existence of the hook means that a negative result from update_option is NOT an error,
483
-        // but just means no update occurred, so don't display an error to the user.
484
-        // BUT... if update_option returns FALSE, AND the hook is missing,
485
-        // then it means that something truly went wrong
486
-        $saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
487
-        // remove our action since we don't want it in the system anymore
488
-        remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
489
-        do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
490
-        // self::$_instance = $clone;
491
-        // unset( $clone );
492
-        // if config remains the same or was updated successfully
493
-        if ($saved) {
494
-            if ($add_success) {
495
-                EE_Error::add_success(
496
-                    __('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
497
-                    __FILE__,
498
-                    __FUNCTION__,
499
-                    __LINE__
500
-                );
501
-            }
502
-            return true;
503
-        } else {
504
-            if ($add_error) {
505
-                EE_Error::add_error(
506
-                    __('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
507
-                    __FILE__,
508
-                    __FUNCTION__,
509
-                    __LINE__
510
-                );
511
-            }
512
-            return false;
513
-        }
514
-    }
515
-
516
-
517
-    /**
518
-     *    _verify_config_params
519
-     *
520
-     * @access    private
521
-     * @param    string         $section
522
-     * @param    string         $name
523
-     * @param    string         $config_class
524
-     * @param    EE_Config_Base $config_obj
525
-     * @param    array          $tests_to_run
526
-     * @param    bool           $display_errors
527
-     * @return    bool    TRUE on success, FALSE on fail
528
-     */
529
-    private function _verify_config_params(
530
-        $section = '',
531
-        $name = '',
532
-        $config_class = '',
533
-        $config_obj = null,
534
-        $tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
535
-        $display_errors = true
536
-    ) {
537
-        try {
538
-            foreach ($tests_to_run as $test) {
539
-                switch ($test) {
540
-                    // TEST #1 : check that section was set
541
-                    case 1:
542
-                        if (empty($section)) {
543
-                            if ($display_errors) {
544
-                                throw new EE_Error(
545
-                                    sprintf(
546
-                                        __(
547
-                                            'No configuration section has been provided while attempting to save "%s".',
548
-                                            'event_espresso'
549
-                                        ),
550
-                                        $config_class
551
-                                    )
552
-                                );
553
-                            }
554
-                            return false;
555
-                        }
556
-                        break;
557
-                    // TEST #2 : check that settings section exists
558
-                    case 2:
559
-                        if (! isset($this->{$section})) {
560
-                            if ($display_errors) {
561
-                                throw new EE_Error(
562
-                                    sprintf(
563
-                                        __('The "%s" configuration section does not exist.', 'event_espresso'),
564
-                                        $section
565
-                                    )
566
-                                );
567
-                            }
568
-                            return false;
569
-                        }
570
-                        break;
571
-                    // TEST #3 : check that section is the proper format
572
-                    case 3:
573
-                        if (! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
574
-                        ) {
575
-                            if ($display_errors) {
576
-                                throw new EE_Error(
577
-                                    sprintf(
578
-                                        __(
579
-                                            'The "%s" configuration settings have not been formatted correctly.',
580
-                                            'event_espresso'
581
-                                        ),
582
-                                        $section
583
-                                    )
584
-                                );
585
-                            }
586
-                            return false;
587
-                        }
588
-                        break;
589
-                    // TEST #4 : check that config section name has been set
590
-                    case 4:
591
-                        if (empty($name)) {
592
-                            if ($display_errors) {
593
-                                throw new EE_Error(
594
-                                    __(
595
-                                        'No name has been provided for the specific configuration section.',
596
-                                        'event_espresso'
597
-                                    )
598
-                                );
599
-                            }
600
-                            return false;
601
-                        }
602
-                        break;
603
-                    // TEST #5 : check that a config class name has been set
604
-                    case 5:
605
-                        if (empty($config_class)) {
606
-                            if ($display_errors) {
607
-                                throw new EE_Error(
608
-                                    __(
609
-                                        'No class name has been provided for the specific configuration section.',
610
-                                        'event_espresso'
611
-                                    )
612
-                                );
613
-                            }
614
-                            return false;
615
-                        }
616
-                        break;
617
-                    // TEST #6 : verify config class is accessible
618
-                    case 6:
619
-                        if (! class_exists($config_class)) {
620
-                            if ($display_errors) {
621
-                                throw new EE_Error(
622
-                                    sprintf(
623
-                                        __(
624
-                                            'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
625
-                                            'event_espresso'
626
-                                        ),
627
-                                        $config_class
628
-                                    )
629
-                                );
630
-                            }
631
-                            return false;
632
-                        }
633
-                        break;
634
-                    // TEST #7 : check that config has even been set
635
-                    case 7:
636
-                        if (! isset($this->{$section}->{$name})) {
637
-                            if ($display_errors) {
638
-                                throw new EE_Error(
639
-                                    sprintf(
640
-                                        __('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
641
-                                        $section,
642
-                                        $name
643
-                                    )
644
-                                );
645
-                            }
646
-                            return false;
647
-                        } else {
648
-                            // and make sure it's not serialized
649
-                            $this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
650
-                        }
651
-                        break;
652
-                    // TEST #8 : check that config is the requested type
653
-                    case 8:
654
-                        if (! $this->{$section}->{$name} instanceof $config_class) {
655
-                            if ($display_errors) {
656
-                                throw new EE_Error(
657
-                                    sprintf(
658
-                                        __(
659
-                                            'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
660
-                                            'event_espresso'
661
-                                        ),
662
-                                        $section,
663
-                                        $name,
664
-                                        $config_class
665
-                                    )
666
-                                );
667
-                            }
668
-                            return false;
669
-                        }
670
-                        break;
671
-                    // TEST #9 : verify config object
672
-                    case 9:
673
-                        if (! $config_obj instanceof EE_Config_Base) {
674
-                            if ($display_errors) {
675
-                                throw new EE_Error(
676
-                                    sprintf(
677
-                                        __('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
678
-                                        print_r($config_obj, true)
679
-                                    )
680
-                                );
681
-                            }
682
-                            return false;
683
-                        }
684
-                        break;
685
-                }
686
-            }
687
-        } catch (EE_Error $e) {
688
-            $e->get_error();
689
-        }
690
-        // you have successfully run the gauntlet
691
-        return true;
692
-    }
693
-
694
-
695
-    /**
696
-     *    _generate_config_option_name
697
-     *
698
-     * @access        protected
699
-     * @param        string $section
700
-     * @param        string $name
701
-     * @return        string
702
-     */
703
-    private function _generate_config_option_name($section = '', $name = '')
704
-    {
705
-        return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
706
-    }
707
-
708
-
709
-    /**
710
-     *    _set_config_class
711
-     * ensures that a config class is set, either from a passed config class or one generated from the config name
712
-     *
713
-     * @access    private
714
-     * @param    string $config_class
715
-     * @param    string $name
716
-     * @return    string
717
-     */
718
-    private function _set_config_class($config_class = '', $name = '')
719
-    {
720
-        return ! empty($config_class)
721
-            ? $config_class
722
-            : str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
723
-    }
724
-
725
-
726
-    /**
727
-     *    set_config
728
-     *
729
-     * @access    protected
730
-     * @param    string         $section
731
-     * @param    string         $name
732
-     * @param    string         $config_class
733
-     * @param    EE_Config_Base $config_obj
734
-     * @return    EE_Config_Base
735
-     */
736
-    public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
737
-    {
738
-        // ensure config class is set to something
739
-        $config_class = $this->_set_config_class($config_class, $name);
740
-        // run tests 1-4, 6, and 7 to verify all config params are set and valid
741
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
742
-            return null;
743
-        }
744
-        $config_option_name = $this->_generate_config_option_name($section, $name);
745
-        // if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
746
-        if (! isset($this->_addon_option_names[ $config_option_name ])) {
747
-            $this->_addon_option_names[ $config_option_name ] = $config_class;
748
-            $this->update_addon_option_names();
749
-        }
750
-        // verify the incoming config object but suppress errors
751
-        if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
752
-            $config_obj = new $config_class();
753
-        }
754
-        if (get_option($config_option_name)) {
755
-            EE_Config::log($config_option_name);
756
-            update_option($config_option_name, $config_obj);
757
-            $this->{$section}->{$name} = $config_obj;
758
-            return $this->{$section}->{$name};
759
-        } else {
760
-            // create a wp-option for this config
761
-            if (add_option($config_option_name, $config_obj, '', 'no')) {
762
-                $this->{$section}->{$name} = maybe_unserialize($config_obj);
763
-                return $this->{$section}->{$name};
764
-            } else {
765
-                EE_Error::add_error(
766
-                    sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
767
-                    __FILE__,
768
-                    __FUNCTION__,
769
-                    __LINE__
770
-                );
771
-                return null;
772
-            }
773
-        }
774
-    }
775
-
776
-
777
-    /**
778
-     *    update_config
779
-     * Important: the config object must ALREADY be set, otherwise this will produce an error.
780
-     *
781
-     * @access    public
782
-     * @param    string                $section
783
-     * @param    string                $name
784
-     * @param    EE_Config_Base|string $config_obj
785
-     * @param    bool                  $throw_errors
786
-     * @return    bool
787
-     */
788
-    public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
789
-    {
790
-        // don't allow config updates during WP heartbeats
791
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
792
-            return false;
793
-        }
794
-        $config_obj = maybe_unserialize($config_obj);
795
-        // get class name of the incoming object
796
-        $config_class = get_class($config_obj);
797
-        // run tests 1-5 and 9 to verify config
798
-        if (! $this->_verify_config_params(
799
-            $section,
800
-            $name,
801
-            $config_class,
802
-            $config_obj,
803
-            array(1, 2, 3, 4, 7, 9)
804
-        )
805
-        ) {
806
-            return false;
807
-        }
808
-        $config_option_name = $this->_generate_config_option_name($section, $name);
809
-        // check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
810
-        if (! isset($this->_addon_option_names[ $config_option_name ])) {
811
-            // save new config to db
812
-            if ($this->set_config($section, $name, $config_class, $config_obj)) {
813
-                return true;
814
-            }
815
-        } else {
816
-            // first check if the record already exists
817
-            $existing_config = get_option($config_option_name);
818
-            $config_obj = serialize($config_obj);
819
-            // just return if db record is already up to date (NOT type safe comparison)
820
-            if ($existing_config == $config_obj) {
821
-                $this->{$section}->{$name} = $config_obj;
822
-                return true;
823
-            } elseif (update_option($config_option_name, $config_obj)) {
824
-                EE_Config::log($config_option_name);
825
-                // update wp-option for this config class
826
-                $this->{$section}->{$name} = $config_obj;
827
-                return true;
828
-            } elseif ($throw_errors) {
829
-                EE_Error::add_error(
830
-                    sprintf(
831
-                        __(
832
-                            'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
833
-                            'event_espresso'
834
-                        ),
835
-                        $config_class,
836
-                        'EE_Config->' . $section . '->' . $name
837
-                    ),
838
-                    __FILE__,
839
-                    __FUNCTION__,
840
-                    __LINE__
841
-                );
842
-            }
843
-        }
844
-        return false;
845
-    }
846
-
847
-
848
-    /**
849
-     *    get_config
850
-     *
851
-     * @access    public
852
-     * @param    string $section
853
-     * @param    string $name
854
-     * @param    string $config_class
855
-     * @return    mixed EE_Config_Base | NULL
856
-     */
857
-    public function get_config($section = '', $name = '', $config_class = '')
858
-    {
859
-        // ensure config class is set to something
860
-        $config_class = $this->_set_config_class($config_class, $name);
861
-        // run tests 1-4, 6 and 7 to verify that all params have been set
862
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
863
-            return null;
864
-        }
865
-        // now test if the requested config object exists, but suppress errors
866
-        if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
867
-            // config already exists, so pass it back
868
-            return $this->{$section}->{$name};
869
-        }
870
-        // load config option from db if it exists
871
-        $config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
872
-        // verify the newly retrieved config object, but suppress errors
873
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
874
-            // config is good, so set it and pass it back
875
-            $this->{$section}->{$name} = $config_obj;
876
-            return $this->{$section}->{$name};
877
-        }
878
-        // oops! $config_obj is not already set and does not exist in the db, so create a new one
879
-        $config_obj = $this->set_config($section, $name, $config_class);
880
-        // verify the newly created config object
881
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
882
-            return $this->{$section}->{$name};
883
-        } else {
884
-            EE_Error::add_error(
885
-                sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
886
-                __FILE__,
887
-                __FUNCTION__,
888
-                __LINE__
889
-            );
890
-        }
891
-        return null;
892
-    }
893
-
894
-
895
-    /**
896
-     *    get_config_option
897
-     *
898
-     * @access    public
899
-     * @param    string $config_option_name
900
-     * @return    mixed EE_Config_Base | FALSE
901
-     */
902
-    public function get_config_option($config_option_name = '')
903
-    {
904
-        // retrieve the wp-option for this config class.
905
-        $config_option = maybe_unserialize(get_option($config_option_name, array()));
906
-        if (empty($config_option)) {
907
-            EE_Config::log($config_option_name . '-NOT-FOUND');
908
-        }
909
-        return $config_option;
910
-    }
911
-
912
-
913
-    /**
914
-     * log
915
-     *
916
-     * @param string $config_option_name
917
-     */
918
-    public static function log($config_option_name = '')
919
-    {
920
-        if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
921
-            $config_log = get_option(EE_Config::LOG_NAME, array());
922
-            // copy incoming $_REQUEST and sanitize it so we can save it
923
-            $_request = $_REQUEST;
924
-            array_walk_recursive($_request, 'sanitize_text_field');
925
-            $config_log[ (string) microtime(true) ] = array(
926
-                'config_name' => $config_option_name,
927
-                'request'     => $_request,
928
-            );
929
-            update_option(EE_Config::LOG_NAME, $config_log);
930
-        }
931
-    }
932
-
933
-
934
-    /**
935
-     * trim_log
936
-     * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
937
-     */
938
-    public static function trim_log()
939
-    {
940
-        if (! EE_Config::logging_enabled()) {
941
-            return;
942
-        }
943
-        $config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
944
-        $log_length = count($config_log);
945
-        if ($log_length > EE_Config::LOG_LENGTH) {
946
-            ksort($config_log);
947
-            $config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
948
-            update_option(EE_Config::LOG_NAME, $config_log);
949
-        }
950
-    }
951
-
952
-
953
-    /**
954
-     *    get_page_for_posts
955
-     *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
956
-     *    wp-option "page_for_posts", or "posts" if no page is selected
957
-     *
958
-     * @access    public
959
-     * @return    string
960
-     */
961
-    public static function get_page_for_posts()
962
-    {
963
-        $page_for_posts = get_option('page_for_posts');
964
-        if (! $page_for_posts) {
965
-            return 'posts';
966
-        }
967
-        /** @type WPDB $wpdb */
968
-        global $wpdb;
969
-        $SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
970
-        return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
971
-    }
972
-
973
-
974
-    /**
975
-     *    register_shortcodes_and_modules.
976
-     *    At this point, it's too early to tell if we're maintenance mode or not.
977
-     *    In fact, this is where we give modules a chance to let core know they exist
978
-     *    so they can help trigger maintenance mode if it's needed
979
-     *
980
-     * @access    public
981
-     * @return    void
982
-     */
983
-    public function register_shortcodes_and_modules()
984
-    {
985
-        // allow modules to set hooks for the rest of the system
986
-        EE_Registry::instance()->modules = $this->_register_modules();
987
-    }
988
-
989
-
990
-    /**
991
-     *    initialize_shortcodes_and_modules
992
-     *    meaning they can start adding their hooks to get stuff done
993
-     *
994
-     * @access    public
995
-     * @return    void
996
-     */
997
-    public function initialize_shortcodes_and_modules()
998
-    {
999
-        // allow modules to set hooks for the rest of the system
1000
-        $this->_initialize_modules();
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     *    widgets_init
1006
-     *
1007
-     * @access private
1008
-     * @return void
1009
-     */
1010
-    public function widgets_init()
1011
-    {
1012
-        // only init widgets on admin pages when not in complete maintenance, and
1013
-        // on frontend when not in any maintenance mode
1014
-        if (! EE_Maintenance_Mode::instance()->level()
1015
-            || (
1016
-                is_admin()
1017
-                && EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1018
-            )
1019
-        ) {
1020
-            // grab list of installed widgets
1021
-            $widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1022
-            // filter list of modules to register
1023
-            $widgets_to_register = apply_filters(
1024
-                'FHEE__EE_Config__register_widgets__widgets_to_register',
1025
-                $widgets_to_register
1026
-            );
1027
-            if (! empty($widgets_to_register)) {
1028
-                // cycle thru widget folders
1029
-                foreach ($widgets_to_register as $widget_path) {
1030
-                    // add to list of installed widget modules
1031
-                    EE_Config::register_ee_widget($widget_path);
1032
-                }
1033
-            }
1034
-            // filter list of installed modules
1035
-            EE_Registry::instance()->widgets = apply_filters(
1036
-                'FHEE__EE_Config__register_widgets__installed_widgets',
1037
-                EE_Registry::instance()->widgets
1038
-            );
1039
-        }
1040
-    }
1041
-
1042
-
1043
-    /**
1044
-     *    register_ee_widget - makes core aware of this widget
1045
-     *
1046
-     * @access    public
1047
-     * @param    string $widget_path - full path up to and including widget folder
1048
-     * @return    void
1049
-     */
1050
-    public static function register_ee_widget($widget_path = null)
1051
-    {
1052
-        do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1053
-        $widget_ext = '.widget.php';
1054
-        // make all separators match
1055
-        $widget_path = rtrim(str_replace('\\', DS, $widget_path), DS);
1056
-        // does the file path INCLUDE the actual file name as part of the path ?
1057
-        if (strpos($widget_path, $widget_ext) !== false) {
1058
-            // grab and shortcode file name from directory name and break apart at dots
1059
-            $file_name = explode('.', basename($widget_path));
1060
-            // take first segment from file name pieces and remove class prefix if it exists
1061
-            $widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1062
-            // sanitize shortcode directory name
1063
-            $widget = sanitize_key($widget);
1064
-            // now we need to rebuild the shortcode path
1065
-            $widget_path = explode(DS, $widget_path);
1066
-            // remove last segment
1067
-            array_pop($widget_path);
1068
-            // glue it back together
1069
-            $widget_path = implode(DS, $widget_path);
1070
-        } else {
1071
-            // grab and sanitize widget directory name
1072
-            $widget = sanitize_key(basename($widget_path));
1073
-        }
1074
-        // create classname from widget directory name
1075
-        $widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1076
-        // add class prefix
1077
-        $widget_class = 'EEW_' . $widget;
1078
-        // does the widget exist ?
1079
-        if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1080
-            $msg = sprintf(
1081
-                __(
1082
-                    'The requested %s widget file could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s',
1083
-                    'event_espresso'
1084
-                ),
1085
-                $widget_class,
1086
-                $widget_path . DS . $widget_class . $widget_ext
1087
-            );
1088
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1089
-            return;
1090
-        }
1091
-        // load the widget class file
1092
-        require_once($widget_path . DS . $widget_class . $widget_ext);
1093
-        // verify that class exists
1094
-        if (! class_exists($widget_class)) {
1095
-            $msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1096
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1097
-            return;
1098
-        }
1099
-        register_widget($widget_class);
1100
-        // add to array of registered widgets
1101
-        EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     *        _register_modules
1107
-     *
1108
-     * @access private
1109
-     * @return array
1110
-     */
1111
-    private function _register_modules()
1112
-    {
1113
-        // grab list of installed modules
1114
-        $modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1115
-        // filter list of modules to register
1116
-        $modules_to_register = apply_filters(
1117
-            'FHEE__EE_Config__register_modules__modules_to_register',
1118
-            $modules_to_register
1119
-        );
1120
-        if (! empty($modules_to_register)) {
1121
-            // loop through folders
1122
-            foreach ($modules_to_register as $module_path) {
1123
-                /**TEMPORARILY EXCLUDE gateways from modules for time being**/
1124
-                if ($module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1125
-                    && $module_path !== EE_MODULES . 'gateways'
1126
-                ) {
1127
-                    // add to list of installed modules
1128
-                    EE_Config::register_module($module_path);
1129
-                }
1130
-            }
1131
-        }
1132
-        // filter list of installed modules
1133
-        return apply_filters(
1134
-            'FHEE__EE_Config___register_modules__installed_modules',
1135
-            EE_Registry::instance()->modules
1136
-        );
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     *    register_module - makes core aware of this module
1142
-     *
1143
-     * @access    public
1144
-     * @param    string $module_path - full path up to and including module folder
1145
-     * @return    bool
1146
-     */
1147
-    public static function register_module($module_path = null)
1148
-    {
1149
-        do_action('AHEE__EE_Config__register_module__begin', $module_path);
1150
-        $module_ext = '.module.php';
1151
-        // make all separators match
1152
-        $module_path = str_replace(array('\\', '/'), DS, $module_path);
1153
-        // does the file path INCLUDE the actual file name as part of the path ?
1154
-        if (strpos($module_path, $module_ext) !== false) {
1155
-            // grab and shortcode file name from directory name and break apart at dots
1156
-            $module_file = explode('.', basename($module_path));
1157
-            // now we need to rebuild the shortcode path
1158
-            $module_path = explode(DS, $module_path);
1159
-            // remove last segment
1160
-            array_pop($module_path);
1161
-            // glue it back together
1162
-            $module_path = implode(DS, $module_path) . DS;
1163
-            // take first segment from file name pieces and sanitize it
1164
-            $module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1165
-            // ensure class prefix is added
1166
-            $module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1167
-        } else {
1168
-            // we need to generate the filename based off of the folder name
1169
-            // grab and sanitize module name
1170
-            $module = strtolower(basename($module_path));
1171
-            $module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1172
-            // like trailingslashit()
1173
-            $module_path = rtrim($module_path, DS) . DS;
1174
-            // create classname from module directory name
1175
-            $module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1176
-            // add class prefix
1177
-            $module_class = 'EED_' . $module;
1178
-        }
1179
-        // does the module exist ?
1180
-        if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1181
-            $msg = sprintf(
1182
-                __(
1183
-                    'The requested %s module file could not be found or is not readable due to file permissions.',
1184
-                    'event_espresso'
1185
-                ),
1186
-                $module
1187
-            );
1188
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1189
-            return false;
1190
-        }
1191
-        // load the module class file
1192
-        require_once($module_path . $module_class . $module_ext);
1193
-        // verify that class exists
1194
-        if (! class_exists($module_class)) {
1195
-            $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1196
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1197
-            return false;
1198
-        }
1199
-        // add to array of registered modules
1200
-        EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1201
-        do_action(
1202
-            'AHEE__EE_Config__register_module__complete',
1203
-            $module_class,
1204
-            EE_Registry::instance()->modules->{$module_class}
1205
-        );
1206
-        return true;
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     *    _initialize_modules
1212
-     *    allow modules to set hooks for the rest of the system
1213
-     *
1214
-     * @access private
1215
-     * @return void
1216
-     */
1217
-    private function _initialize_modules()
1218
-    {
1219
-        // cycle thru shortcode folders
1220
-        foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1221
-            // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1222
-            // which set hooks ?
1223
-            if (is_admin()) {
1224
-                // fire immediately
1225
-                call_user_func(array($module_class, 'set_hooks_admin'));
1226
-            } else {
1227
-                // delay until other systems are online
1228
-                add_action(
1229
-                    'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1230
-                    array($module_class, 'set_hooks')
1231
-                );
1232
-            }
1233
-        }
1234
-    }
1235
-
1236
-
1237
-    /**
1238
-     *    register_route - adds module method routes to route_map
1239
-     *
1240
-     * @access    public
1241
-     * @param    string $route       - "pretty" public alias for module method
1242
-     * @param    string $module      - module name (classname without EED_ prefix)
1243
-     * @param    string $method_name - the actual module method to be routed to
1244
-     * @param    string $key         - url param key indicating a route is being called
1245
-     * @return    bool
1246
-     */
1247
-    public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1248
-    {
1249
-        do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1250
-        $module = str_replace('EED_', '', $module);
1251
-        $module_class = 'EED_' . $module;
1252
-        if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1253
-            $msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1254
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1255
-            return false;
1256
-        }
1257
-        if (empty($route)) {
1258
-            $msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1259
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1260
-            return false;
1261
-        }
1262
-        if (! method_exists('EED_' . $module, $method_name)) {
1263
-            $msg = sprintf(
1264
-                __('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1265
-                $route
1266
-            );
1267
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1268
-            return false;
1269
-        }
1270
-        EE_Config::$_module_route_map[ (string) $key ][ (string) $route ] = array('EED_' . $module, $method_name);
1271
-        return true;
1272
-    }
1273
-
1274
-
1275
-    /**
1276
-     *    get_route - get module method route
1277
-     *
1278
-     * @access    public
1279
-     * @param    string $route - "pretty" public alias for module method
1280
-     * @param    string $key   - url param key indicating a route is being called
1281
-     * @return    string
1282
-     */
1283
-    public static function get_route($route = null, $key = 'ee')
1284
-    {
1285
-        do_action('AHEE__EE_Config__get_route__begin', $route);
1286
-        $route = (string) apply_filters('FHEE__EE_Config__get_route', $route);
1287
-        if (isset(EE_Config::$_module_route_map[ $key ][ $route ])) {
1288
-            return EE_Config::$_module_route_map[ $key ][ $route ];
1289
-        }
1290
-        return null;
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     *    get_routes - get ALL module method routes
1296
-     *
1297
-     * @access    public
1298
-     * @return    array
1299
-     */
1300
-    public static function get_routes()
1301
-    {
1302
-        return EE_Config::$_module_route_map;
1303
-    }
1304
-
1305
-
1306
-    /**
1307
-     *    register_forward - allows modules to forward request to another module for further processing
1308
-     *
1309
-     * @access    public
1310
-     * @param    string       $route   - "pretty" public alias for module method
1311
-     * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1312
-     *                                 class, allows different forwards to be served based on status
1313
-     * @param    array|string $forward - function name or array( class, method )
1314
-     * @param    string       $key     - url param key indicating a route is being called
1315
-     * @return    bool
1316
-     */
1317
-    public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1318
-    {
1319
-        do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1320
-        if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1321
-            $msg = sprintf(
1322
-                __('The module route %s for this forward has not been registered.', 'event_espresso'),
1323
-                $route
1324
-            );
1325
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1326
-            return false;
1327
-        }
1328
-        if (empty($forward)) {
1329
-            $msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1330
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1331
-            return false;
1332
-        }
1333
-        if (is_array($forward)) {
1334
-            if (! isset($forward[1])) {
1335
-                $msg = sprintf(
1336
-                    __('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1337
-                    $route
1338
-                );
1339
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1340
-                return false;
1341
-            }
1342
-            if (! method_exists($forward[0], $forward[1])) {
1343
-                $msg = sprintf(
1344
-                    __('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1345
-                    $forward[1],
1346
-                    $route
1347
-                );
1348
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1349
-                return false;
1350
-            }
1351
-        } elseif (! function_exists($forward)) {
1352
-            $msg = sprintf(
1353
-                __('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1354
-                $forward,
1355
-                $route
1356
-            );
1357
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1358
-            return false;
1359
-        }
1360
-        EE_Config::$_module_forward_map[ $key ][ $route ][ absint($status) ] = $forward;
1361
-        return true;
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     *    get_forward - get forwarding route
1367
-     *
1368
-     * @access    public
1369
-     * @param    string  $route  - "pretty" public alias for module method
1370
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1371
-     *                           allows different forwards to be served based on status
1372
-     * @param    string  $key    - url param key indicating a route is being called
1373
-     * @return    string
1374
-     */
1375
-    public static function get_forward($route = null, $status = 0, $key = 'ee')
1376
-    {
1377
-        do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1378
-        if (isset(EE_Config::$_module_forward_map[ $key ][ $route ][ $status ])) {
1379
-            return apply_filters(
1380
-                'FHEE__EE_Config__get_forward',
1381
-                EE_Config::$_module_forward_map[ $key ][ $route ][ $status ],
1382
-                $route,
1383
-                $status
1384
-            );
1385
-        }
1386
-        return null;
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     *    register_forward - allows modules to specify different view templates for different method routes and status
1392
-     *    results
1393
-     *
1394
-     * @access    public
1395
-     * @param    string  $route  - "pretty" public alias for module method
1396
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1397
-     *                           allows different views to be served based on status
1398
-     * @param    string  $view
1399
-     * @param    string  $key    - url param key indicating a route is being called
1400
-     * @return    bool
1401
-     */
1402
-    public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1403
-    {
1404
-        do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1405
-        if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1406
-            $msg = sprintf(
1407
-                __('The module route %s for this view has not been registered.', 'event_espresso'),
1408
-                $route
1409
-            );
1410
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1411
-            return false;
1412
-        }
1413
-        if (! is_readable($view)) {
1414
-            $msg = sprintf(
1415
-                __(
1416
-                    'The %s view file could not be found or is not readable due to file permissions.',
1417
-                    'event_espresso'
1418
-                ),
1419
-                $view
1420
-            );
1421
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1422
-            return false;
1423
-        }
1424
-        EE_Config::$_module_view_map[ $key ][ $route ][ absint($status) ] = $view;
1425
-        return true;
1426
-    }
1427
-
1428
-
1429
-    /**
1430
-     *    get_view - get view for route and status
1431
-     *
1432
-     * @access    public
1433
-     * @param    string  $route  - "pretty" public alias for module method
1434
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1435
-     *                           allows different views to be served based on status
1436
-     * @param    string  $key    - url param key indicating a route is being called
1437
-     * @return    string
1438
-     */
1439
-    public static function get_view($route = null, $status = 0, $key = 'ee')
1440
-    {
1441
-        do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1442
-        if (isset(EE_Config::$_module_view_map[ $key ][ $route ][ $status ])) {
1443
-            return apply_filters(
1444
-                'FHEE__EE_Config__get_view',
1445
-                EE_Config::$_module_view_map[ $key ][ $route ][ $status ],
1446
-                $route,
1447
-                $status
1448
-            );
1449
-        }
1450
-        return null;
1451
-    }
1452
-
1453
-
1454
-    public function update_addon_option_names()
1455
-    {
1456
-        update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1457
-    }
1458
-
1459
-
1460
-    public function shutdown()
1461
-    {
1462
-        $this->update_addon_option_names();
1463
-    }
1464
-
1465
-
1466
-    /**
1467
-     * @return LegacyShortcodesManager
1468
-     */
1469
-    public static function getLegacyShortcodesManager()
1470
-    {
1471
-
1472
-        if (! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1473
-            EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1474
-                EE_Registry::instance()
1475
-            );
1476
-        }
1477
-        return EE_Config::instance()->legacy_shortcodes_manager;
1478
-    }
1479
-
1480
-
1481
-    /**
1482
-     * register_shortcode - makes core aware of this shortcode
1483
-     *
1484
-     * @deprecated 4.9.26
1485
-     * @param    string $shortcode_path - full path up to and including shortcode folder
1486
-     * @return    bool
1487
-     */
1488
-    public static function register_shortcode($shortcode_path = null)
1489
-    {
1490
-        EE_Error::doing_it_wrong(
1491
-            __METHOD__,
1492
-            __(
1493
-                'Usage is deprecated. Use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::registerShortcode() as direct replacement, or better yet, please see the new \EventEspresso\core\services\shortcodes\ShortcodesManager class.',
1494
-                'event_espresso'
1495
-            ),
1496
-            '4.9.26'
1497
-        );
1498
-        return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1499
-    }
1500
-}
1501
-
1502
-/**
1503
- * Base class used for config classes. These classes should generally not have
1504
- * magic functions in use, except we'll allow them to magically set and get stuff...
1505
- * basically, they should just be well-defined stdClasses
1506
- */
1507
-class EE_Config_Base
1508
-{
1509
-
1510
-    /**
1511
-     * Utility function for escaping the value of a property and returning.
1512
-     *
1513
-     * @param string $property property name (checks to see if exists).
1514
-     * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1515
-     * @throws \EE_Error
1516
-     */
1517
-    public function get_pretty($property)
1518
-    {
1519
-        if (! property_exists($this, $property)) {
1520
-            throw new EE_Error(
1521
-                sprintf(
1522
-                    __(
1523
-                        '%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1524
-                        'event_espresso'
1525
-                    ),
1526
-                    get_class($this),
1527
-                    $property
1528
-                )
1529
-            );
1530
-        }
1531
-        // just handling escaping of strings for now.
1532
-        if (is_string($this->{$property})) {
1533
-            return stripslashes($this->{$property});
1534
-        }
1535
-        return $this->{$property};
1536
-    }
1537
-
1538
-
1539
-    public function populate()
1540
-    {
1541
-        // grab defaults via a new instance of this class.
1542
-        $class_name = get_class($this);
1543
-        $defaults = new $class_name;
1544
-        // loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1545
-        // default from our $defaults object.
1546
-        foreach (get_object_vars($defaults) as $property => $value) {
1547
-            if ($this->{$property} === null) {
1548
-                $this->{$property} = $value;
1549
-            }
1550
-        }
1551
-        // cleanup
1552
-        unset($defaults);
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     *        __isset
1558
-     *
1559
-     * @param $a
1560
-     * @return bool
1561
-     */
1562
-    public function __isset($a)
1563
-    {
1564
-        return false;
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     *        __unset
1570
-     *
1571
-     * @param $a
1572
-     * @return bool
1573
-     */
1574
-    public function __unset($a)
1575
-    {
1576
-        return false;
1577
-    }
1578
-
1579
-
1580
-    /**
1581
-     *        __clone
1582
-     */
1583
-    public function __clone()
1584
-    {
1585
-    }
1586
-
1587
-
1588
-    /**
1589
-     *        __wakeup
1590
-     */
1591
-    public function __wakeup()
1592
-    {
1593
-    }
1594
-
1595
-
1596
-    /**
1597
-     *        __destruct
1598
-     */
1599
-    public function __destruct()
1600
-    {
1601
-    }
1602
-}
1603
-
1604
-/**
1605
- * Class for defining what's in the EE_Config relating to registration settings
1606
- */
1607
-class EE_Core_Config extends EE_Config_Base
1608
-{
1609
-
1610
-    const OPTION_NAME_UXIP = 'ee_ueip_optin';
1611
-
1612
-
1613
-    public $current_blog_id;
1614
-
1615
-    public $ee_ueip_optin;
1616
-
1617
-    public $ee_ueip_has_notified;
1618
-
1619
-    /**
1620
-     * Not to be confused with the 4 critical page variables (See
1621
-     * get_critical_pages_array()), this is just an array of wp posts that have EE
1622
-     * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1623
-     * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1624
-     *
1625
-     * @var array
1626
-     */
1627
-    public $post_shortcodes;
1628
-
1629
-    public $module_route_map;
1630
-
1631
-    public $module_forward_map;
1632
-
1633
-    public $module_view_map;
1634
-
1635
-    /**
1636
-     * The next 4 vars are the IDs of critical EE pages.
1637
-     *
1638
-     * @var int
1639
-     */
1640
-    public $reg_page_id;
1641
-
1642
-    public $txn_page_id;
1643
-
1644
-    public $thank_you_page_id;
1645
-
1646
-    public $cancel_page_id;
1647
-
1648
-    /**
1649
-     * The next 4 vars are the URLs of critical EE pages.
1650
-     *
1651
-     * @var int
1652
-     */
1653
-    public $reg_page_url;
1654
-
1655
-    public $txn_page_url;
1656
-
1657
-    public $thank_you_page_url;
1658
-
1659
-    public $cancel_page_url;
1660
-
1661
-    /**
1662
-     * The next vars relate to the custom slugs for EE CPT routes
1663
-     */
1664
-    public $event_cpt_slug;
1665
-
1666
-    /**
1667
-     * This caches the _ee_ueip_option in case this config is reset in the same
1668
-     * request across blog switches in a multisite context.
1669
-     * Avoids extra queries to the db for this option.
1670
-     *
1671
-     * @var bool
1672
-     */
1673
-    public static $ee_ueip_option;
1674
-
1675
-
1676
-    /**
1677
-     *    class constructor
1678
-     *
1679
-     * @access    public
1680
-     */
1681
-    public function __construct()
1682
-    {
1683
-        // set default organization settings
1684
-        $this->current_blog_id = get_current_blog_id();
1685
-        $this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1686
-        $this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1687
-        $this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1688
-        $this->post_shortcodes = array();
1689
-        $this->module_route_map = array();
1690
-        $this->module_forward_map = array();
1691
-        $this->module_view_map = array();
1692
-        // critical EE page IDs
1693
-        $this->reg_page_id = 0;
1694
-        $this->txn_page_id = 0;
1695
-        $this->thank_you_page_id = 0;
1696
-        $this->cancel_page_id = 0;
1697
-        // critical EE page URLs
1698
-        $this->reg_page_url = '';
1699
-        $this->txn_page_url = '';
1700
-        $this->thank_you_page_url = '';
1701
-        $this->cancel_page_url = '';
1702
-        // cpt slugs
1703
-        $this->event_cpt_slug = __('events', 'event_espresso');
1704
-        // ueip constant check
1705
-        if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1706
-            $this->ee_ueip_optin = false;
1707
-            $this->ee_ueip_has_notified = true;
1708
-        }
1709
-    }
1710
-
1711
-
1712
-    /**
1713
-     * @return array
1714
-     */
1715
-    public function get_critical_pages_array()
1716
-    {
1717
-        return array(
1718
-            $this->reg_page_id,
1719
-            $this->txn_page_id,
1720
-            $this->thank_you_page_id,
1721
-            $this->cancel_page_id,
1722
-        );
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * @return array
1728
-     */
1729
-    public function get_critical_pages_shortcodes_array()
1730
-    {
1731
-        return array(
1732
-            $this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1733
-            $this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1734
-            $this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1735
-            $this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1736
-        );
1737
-    }
1738
-
1739
-
1740
-    /**
1741
-     *  gets/returns URL for EE reg_page
1742
-     *
1743
-     * @access    public
1744
-     * @return    string
1745
-     */
1746
-    public function reg_page_url()
1747
-    {
1748
-        if (! $this->reg_page_url) {
1749
-            $this->reg_page_url = add_query_arg(
1750
-                array('uts' => time()),
1751
-                get_permalink($this->reg_page_id)
1752
-            ) . '#checkout';
1753
-        }
1754
-        return $this->reg_page_url;
1755
-    }
1756
-
1757
-
1758
-    /**
1759
-     *  gets/returns URL for EE txn_page
1760
-     *
1761
-     * @param array $query_args like what gets passed to
1762
-     *                          add_query_arg() as the first argument
1763
-     * @access    public
1764
-     * @return    string
1765
-     */
1766
-    public function txn_page_url($query_args = array())
1767
-    {
1768
-        if (! $this->txn_page_url) {
1769
-            $this->txn_page_url = get_permalink($this->txn_page_id);
1770
-        }
1771
-        if ($query_args) {
1772
-            return add_query_arg($query_args, $this->txn_page_url);
1773
-        } else {
1774
-            return $this->txn_page_url;
1775
-        }
1776
-    }
1777
-
1778
-
1779
-    /**
1780
-     *  gets/returns URL for EE thank_you_page
1781
-     *
1782
-     * @param array $query_args like what gets passed to
1783
-     *                          add_query_arg() as the first argument
1784
-     * @access    public
1785
-     * @return    string
1786
-     */
1787
-    public function thank_you_page_url($query_args = array())
1788
-    {
1789
-        if (! $this->thank_you_page_url) {
1790
-            $this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1791
-        }
1792
-        if ($query_args) {
1793
-            return add_query_arg($query_args, $this->thank_you_page_url);
1794
-        } else {
1795
-            return $this->thank_you_page_url;
1796
-        }
1797
-    }
1798
-
1799
-
1800
-    /**
1801
-     *  gets/returns URL for EE cancel_page
1802
-     *
1803
-     * @access    public
1804
-     * @return    string
1805
-     */
1806
-    public function cancel_page_url()
1807
-    {
1808
-        if (! $this->cancel_page_url) {
1809
-            $this->cancel_page_url = get_permalink($this->cancel_page_id);
1810
-        }
1811
-        return $this->cancel_page_url;
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1817
-     *
1818
-     * @since 4.7.5
1819
-     */
1820
-    protected function _reset_urls()
1821
-    {
1822
-        $this->reg_page_url = '';
1823
-        $this->txn_page_url = '';
1824
-        $this->cancel_page_url = '';
1825
-        $this->thank_you_page_url = '';
1826
-    }
1827
-
1828
-
1829
-    /**
1830
-     * Used to return what the optin value is set for the EE User Experience Program.
1831
-     * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1832
-     * on the main site only.
1833
-     *
1834
-     * @return bool
1835
-     */
1836
-    protected function _get_main_ee_ueip_optin()
1837
-    {
1838
-        // if this is the main site then we can just bypass our direct query.
1839
-        if (is_main_site()) {
1840
-            return get_option(self::OPTION_NAME_UXIP, false);
1841
-        }
1842
-        // is this already cached for this request?  If so use it.
1843
-        if (EE_Core_Config::$ee_ueip_option !== null) {
1844
-            return EE_Core_Config::$ee_ueip_option;
1845
-        }
1846
-        global $wpdb;
1847
-        $current_network_main_site = is_multisite() ? get_current_site() : null;
1848
-        $current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1849
-        $option = self::OPTION_NAME_UXIP;
1850
-        // set correct table for query
1851
-        $table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1852
-        // rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1853
-        // get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1854
-        // re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1855
-        // this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1856
-        // for the purpose of caching.
1857
-        $pre = apply_filters('pre_option_' . $option, false, $option);
1858
-        if (false !== $pre) {
1859
-            EE_Core_Config::$ee_ueip_option = $pre;
1860
-            return EE_Core_Config::$ee_ueip_option;
1861
-        }
1862
-        $row = $wpdb->get_row(
1863
-            $wpdb->prepare(
1864
-                "SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1865
-                $option
1866
-            )
1867
-        );
1868
-        if (is_object($row)) {
1869
-            $value = $row->option_value;
1870
-        } else { // option does not exist so use default.
1871
-            EE_Core_Config::$ee_ueip_option =  apply_filters('default_option_' . $option, false, $option);
1872
-            return EE_Core_Config::$ee_ueip_option;
1873
-        }
1874
-        EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1875
-        return EE_Core_Config::$ee_ueip_option;
1876
-    }
1877
-
1878
-
1879
-    /**
1880
-     * Utility function for escaping the value of a property and returning.
1881
-     *
1882
-     * @param string $property property name (checks to see if exists).
1883
-     * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1884
-     * @throws \EE_Error
1885
-     */
1886
-    public function get_pretty($property)
1887
-    {
1888
-        if ($property === self::OPTION_NAME_UXIP) {
1889
-            return $this->ee_ueip_optin ? 'yes' : 'no';
1890
-        }
1891
-        return parent::get_pretty($property);
1892
-    }
1893
-
1894
-
1895
-    /**
1896
-     * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1897
-     * on the object.
1898
-     *
1899
-     * @return array
1900
-     */
1901
-    public function __sleep()
1902
-    {
1903
-        // reset all url properties
1904
-        $this->_reset_urls();
1905
-        // return what to save to db
1906
-        return array_keys(get_object_vars($this));
1907
-    }
1908
-}
1909
-
1910
-/**
1911
- * Config class for storing info on the Organization
1912
- */
1913
-class EE_Organization_Config extends EE_Config_Base
1914
-{
1915
-
1916
-    /**
1917
-     * @var string $name
1918
-     * eg EE4.1
1919
-     */
1920
-    public $name;
1921
-
1922
-    /**
1923
-     * @var string $address_1
1924
-     * eg 123 Onna Road
1925
-     */
1926
-    public $address_1 = '';
1927
-
1928
-    /**
1929
-     * @var string $address_2
1930
-     * eg PO Box 123
1931
-     */
1932
-    public $address_2 = '';
1933
-
1934
-    /**
1935
-     * @var string $city
1936
-     * eg Inna City
1937
-     */
1938
-    public $city = '';
1939
-
1940
-    /**
1941
-     * @var int $STA_ID
1942
-     * eg 4
1943
-     */
1944
-    public $STA_ID = 0;
1945
-
1946
-    /**
1947
-     * @var string $CNT_ISO
1948
-     * eg US
1949
-     */
1950
-    public $CNT_ISO = '';
1951
-
1952
-    /**
1953
-     * @var string $zip
1954
-     * eg 12345  or V1A 2B3
1955
-     */
1956
-    public $zip = '';
1957
-
1958
-    /**
1959
-     * @var string $email
1960
-     * eg [email protected]
1961
-     */
1962
-    public $email;
1963
-
1964
-    /**
1965
-     * @var string $phone
1966
-     * eg. 111-111-1111
1967
-     */
1968
-    public $phone = '';
1969
-
1970
-    /**
1971
-     * @var string $vat
1972
-     * VAT/Tax Number
1973
-     */
1974
-    public $vat = '';
1975
-
1976
-    /**
1977
-     * @var string $logo_url
1978
-     * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
1979
-     */
1980
-    public $logo_url = '';
1981
-
1982
-    /**
1983
-     * The below are all various properties for holding links to organization social network profiles
1984
-     *
1985
-     * @var string
1986
-     */
1987
-    /**
1988
-     * facebook (facebook.com/profile.name)
1989
-     *
1990
-     * @var string
1991
-     */
1992
-    public $facebook = '';
1993
-
1994
-    /**
1995
-     * twitter (twitter.com/twitter_handle)
1996
-     *
1997
-     * @var string
1998
-     */
1999
-    public $twitter = '';
2000
-
2001
-    /**
2002
-     * linkedin (linkedin.com/in/profile_name)
2003
-     *
2004
-     * @var string
2005
-     */
2006
-    public $linkedin = '';
2007
-
2008
-    /**
2009
-     * pinterest (www.pinterest.com/profile_name)
2010
-     *
2011
-     * @var string
2012
-     */
2013
-    public $pinterest = '';
2014
-
2015
-    /**
2016
-     * google+ (google.com/+profileName)
2017
-     *
2018
-     * @var string
2019
-     */
2020
-    public $google = '';
2021
-
2022
-    /**
2023
-     * instagram (instagram.com/handle)
2024
-     *
2025
-     * @var string
2026
-     */
2027
-    public $instagram = '';
2028
-
2029
-
2030
-    /**
2031
-     *    class constructor
2032
-     *
2033
-     * @access    public
2034
-     */
2035
-    public function __construct()
2036
-    {
2037
-        // set default organization settings
2038
-        // decode HTML entities from the WP blogname, because it's stored in the DB with HTML entities encoded
2039
-        $this->name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
2040
-        $this->email = get_bloginfo('admin_email');
2041
-    }
2042
-}
2043
-
2044
-/**
2045
- * Class for defining what's in the EE_Config relating to currency
2046
- */
2047
-class EE_Currency_Config extends EE_Config_Base
2048
-{
2049
-
2050
-    /**
2051
-     * @var string $code
2052
-     * eg 'US'
2053
-     */
2054
-    public $code;
2055
-
2056
-    /**
2057
-     * @var string $name
2058
-     * eg 'Dollar'
2059
-     */
2060
-    public $name;
2061
-
2062
-    /**
2063
-     * plural name
2064
-     *
2065
-     * @var string $plural
2066
-     * eg 'Dollars'
2067
-     */
2068
-    public $plural;
2069
-
2070
-    /**
2071
-     * currency sign
2072
-     *
2073
-     * @var string $sign
2074
-     * eg '$'
2075
-     */
2076
-    public $sign;
2077
-
2078
-    /**
2079
-     * Whether the currency sign should come before the number or not
2080
-     *
2081
-     * @var boolean $sign_b4
2082
-     */
2083
-    public $sign_b4;
2084
-
2085
-    /**
2086
-     * How many digits should come after the decimal place
2087
-     *
2088
-     * @var int $dec_plc
2089
-     */
2090
-    public $dec_plc;
2091
-
2092
-    /**
2093
-     * Symbol to use for decimal mark
2094
-     *
2095
-     * @var string $dec_mrk
2096
-     * eg '.'
2097
-     */
2098
-    public $dec_mrk;
2099
-
2100
-    /**
2101
-     * Symbol to use for thousands
2102
-     *
2103
-     * @var string $thsnds
2104
-     * eg ','
2105
-     */
2106
-    public $thsnds;
2107
-
2108
-
2109
-    /**
2110
-     *    class constructor
2111
-     *
2112
-     * @access    public
2113
-     * @param string $CNT_ISO
2114
-     * @throws \EE_Error
2115
-     */
2116
-    public function __construct($CNT_ISO = '')
2117
-    {
2118
-        /** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2119
-        $table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2120
-        // get country code from organization settings or use default
2121
-        $ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2122
-                   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2123
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
2124
-            : '';
2125
-        // but override if requested
2126
-        $CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2127
-        // so if that all went well, and we are not in M-Mode (cuz you can't query the db in M-Mode) and double-check the countries table exists
2128
-        if (! empty($CNT_ISO)
2129
-            && EE_Maintenance_Mode::instance()->models_can_query()
2130
-            && $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2131
-        ) {
2132
-            // retrieve the country settings from the db, just in case they have been customized
2133
-            $country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2134
-            if ($country instanceof EE_Country) {
2135
-                $this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2136
-                $this->name = $country->currency_name_single();    // Dollar
2137
-                $this->plural = $country->currency_name_plural();    // Dollars
2138
-                $this->sign = $country->currency_sign();            // currency sign: $
2139
-                $this->sign_b4 = $country->currency_sign_before(
2140
-                );        // currency sign before or after: $TRUE  or  FALSE$
2141
-                $this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2142
-                $this->dec_mrk = $country->currency_decimal_mark(
2143
-                );    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2144
-                $this->thsnds = $country->currency_thousands_separator(
2145
-                );    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2146
-            }
2147
-        }
2148
-        // fallback to hardcoded defaults, in case the above failed
2149
-        if (empty($this->code)) {
2150
-            // set default currency settings
2151
-            $this->code = 'USD';    // currency code: USD, CAD, EUR
2152
-            $this->name = __('Dollar', 'event_espresso');    // Dollar
2153
-            $this->plural = __('Dollars', 'event_espresso');    // Dollars
2154
-            $this->sign = '$';    // currency sign: $
2155
-            $this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2156
-            $this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2157
-            $this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2158
-            $this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2159
-        }
2160
-    }
2161
-}
2162
-
2163
-/**
2164
- * Class for defining what's in the EE_Config relating to registration settings
2165
- */
2166
-class EE_Registration_Config extends EE_Config_Base
2167
-{
2168
-
2169
-    /**
2170
-     * Default registration status
2171
-     *
2172
-     * @var string $default_STS_ID
2173
-     * eg 'RPP'
2174
-     */
2175
-    public $default_STS_ID;
2176
-
2177
-    /**
2178
-     * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2179
-     * registrations)
2180
-     *
2181
-     * @var int
2182
-     */
2183
-    public $default_maximum_number_of_tickets;
2184
-
2185
-    /**
2186
-     * level of validation to apply to email addresses
2187
-     *
2188
-     * @var string $email_validation_level
2189
-     * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2190
-     */
2191
-    public $email_validation_level;
2192
-
2193
-    /**
2194
-     *    whether or not to show alternate payment options during the reg process if payment status is pending
2195
-     *
2196
-     * @var boolean $show_pending_payment_options
2197
-     */
2198
-    public $show_pending_payment_options;
2199
-
2200
-    /**
2201
-     * Whether to skip the registration confirmation page
2202
-     *
2203
-     * @var boolean $skip_reg_confirmation
2204
-     */
2205
-    public $skip_reg_confirmation;
2206
-
2207
-    /**
2208
-     * an array of SPCO reg steps where:
2209
-     *        the keys denotes the reg step order
2210
-     *        each element consists of an array with the following elements:
2211
-     *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2212
-     *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2213
-     *            "slug" => the URL param used to trigger the reg step
2214
-     *
2215
-     * @var array $reg_steps
2216
-     */
2217
-    public $reg_steps;
2218
-
2219
-    /**
2220
-     * Whether registration confirmation should be the last page of SPCO
2221
-     *
2222
-     * @var boolean $reg_confirmation_last
2223
-     */
2224
-    public $reg_confirmation_last;
2225
-
2226
-    /**
2227
-     * Whether or not to enable the EE Bot Trap
2228
-     *
2229
-     * @var boolean $use_bot_trap
2230
-     */
2231
-    public $use_bot_trap;
2232
-
2233
-    /**
2234
-     * Whether or not to encrypt some data sent by the EE Bot Trap
2235
-     *
2236
-     * @var boolean $use_encryption
2237
-     */
2238
-    public $use_encryption;
2239
-
2240
-    /**
2241
-     * Whether or not to use ReCaptcha
2242
-     *
2243
-     * @var boolean $use_captcha
2244
-     */
2245
-    public $use_captcha;
2246
-
2247
-    /**
2248
-     * ReCaptcha Theme
2249
-     *
2250
-     * @var string $recaptcha_theme
2251
-     *    options: 'dark', 'light', 'invisible'
2252
-     */
2253
-    public $recaptcha_theme;
2254
-
2255
-    /**
2256
-     * ReCaptcha Badge - determines the position of the reCAPTCHA badge if using Invisible ReCaptcha.
2257
-     *
2258
-     * @var string $recaptcha_badge
2259
-     *    options: 'bottomright', 'bottomleft', 'inline'
2260
-     */
2261
-    public $recaptcha_badge;
17
+	const OPTION_NAME = 'ee_config';
18
+
19
+	const LOG_NAME = 'ee_config_log';
20
+
21
+	const LOG_LENGTH = 100;
22
+
23
+	const ADDON_OPTION_NAMES = 'ee_config_option_names';
24
+
25
+	/**
26
+	 *    instance of the EE_Config object
27
+	 *
28
+	 * @var    EE_Config $_instance
29
+	 * @access    private
30
+	 */
31
+	private static $_instance;
32
+
33
+	/**
34
+	 * @var boolean $_logging_enabled
35
+	 */
36
+	private static $_logging_enabled = false;
37
+
38
+	/**
39
+	 * @var LegacyShortcodesManager $legacy_shortcodes_manager
40
+	 */
41
+	private $legacy_shortcodes_manager;
42
+
43
+	/**
44
+	 * An StdClass whose property names are addon slugs,
45
+	 * and values are their config classes
46
+	 *
47
+	 * @var StdClass
48
+	 */
49
+	public $addons;
50
+
51
+	/**
52
+	 * @var EE_Admin_Config
53
+	 */
54
+	public $admin;
55
+
56
+	/**
57
+	 * @var EE_Core_Config
58
+	 */
59
+	public $core;
60
+
61
+	/**
62
+	 * @var EE_Currency_Config
63
+	 */
64
+	public $currency;
65
+
66
+	/**
67
+	 * @var EE_Organization_Config
68
+	 */
69
+	public $organization;
70
+
71
+	/**
72
+	 * @var EE_Registration_Config
73
+	 */
74
+	public $registration;
75
+
76
+	/**
77
+	 * @var EE_Template_Config
78
+	 */
79
+	public $template_settings;
80
+
81
+	/**
82
+	 * Holds EE environment values.
83
+	 *
84
+	 * @var EE_Environment_Config
85
+	 */
86
+	public $environment;
87
+
88
+	/**
89
+	 * settings pertaining to Google maps
90
+	 *
91
+	 * @var EE_Map_Config
92
+	 */
93
+	public $map_settings;
94
+
95
+	/**
96
+	 * settings pertaining to Taxes
97
+	 *
98
+	 * @var EE_Tax_Config
99
+	 */
100
+	public $tax_settings;
101
+
102
+	/**
103
+	 * Settings pertaining to global messages settings.
104
+	 *
105
+	 * @var EE_Messages_Config
106
+	 */
107
+	public $messages;
108
+
109
+	/**
110
+	 * @deprecated
111
+	 * @var EE_Gateway_Config
112
+	 */
113
+	public $gateway;
114
+
115
+	/**
116
+	 * @var    array $_addon_option_names
117
+	 * @access    private
118
+	 */
119
+	private $_addon_option_names = array();
120
+
121
+	/**
122
+	 * @var    array $_module_route_map
123
+	 * @access    private
124
+	 */
125
+	private static $_module_route_map = array();
126
+
127
+	/**
128
+	 * @var    array $_module_forward_map
129
+	 * @access    private
130
+	 */
131
+	private static $_module_forward_map = array();
132
+
133
+	/**
134
+	 * @var    array $_module_view_map
135
+	 * @access    private
136
+	 */
137
+	private static $_module_view_map = array();
138
+
139
+
140
+	/**
141
+	 * @singleton method used to instantiate class object
142
+	 * @access    public
143
+	 * @return EE_Config instance
144
+	 */
145
+	public static function instance()
146
+	{
147
+		// check if class object is instantiated, and instantiated properly
148
+		if (! self::$_instance instanceof EE_Config) {
149
+			self::$_instance = new self();
150
+		}
151
+		return self::$_instance;
152
+	}
153
+
154
+
155
+	/**
156
+	 * Resets the config
157
+	 *
158
+	 * @param bool    $hard_reset    if TRUE, sets EE_CONFig back to its original settings in the database. If FALSE
159
+	 *                               (default) leaves the database alone, and merely resets the EE_Config object to
160
+	 *                               reflect its state in the database
161
+	 * @param boolean $reinstantiate if TRUE (default) call instance() and return it. Otherwise, just leave
162
+	 *                               $_instance as NULL. Useful in case you want to forget about the old instance on
163
+	 *                               EE_Config, but might not be ready to instantiate EE_Config currently (eg if the
164
+	 *                               site was put into maintenance mode)
165
+	 * @return EE_Config
166
+	 */
167
+	public static function reset($hard_reset = false, $reinstantiate = true)
168
+	{
169
+		if (self::$_instance instanceof EE_Config) {
170
+			if ($hard_reset) {
171
+				self::$_instance->legacy_shortcodes_manager = null;
172
+				self::$_instance->_addon_option_names = array();
173
+				self::$_instance->_initialize_config();
174
+				self::$_instance->update_espresso_config();
175
+			}
176
+			self::$_instance->update_addon_option_names();
177
+		}
178
+		self::$_instance = null;
179
+		// we don't need to reset the static properties imo because those should
180
+		// only change when a module is added or removed. Currently we don't
181
+		// support removing a module during a request when it previously existed
182
+		if ($reinstantiate) {
183
+			return self::instance();
184
+		} else {
185
+			return null;
186
+		}
187
+	}
188
+
189
+
190
+	/**
191
+	 *    class constructor
192
+	 *
193
+	 * @access    private
194
+	 */
195
+	private function __construct()
196
+	{
197
+		do_action('AHEE__EE_Config__construct__begin', $this);
198
+		EE_Config::$_logging_enabled = apply_filters('FHEE__EE_Config___construct__logging_enabled', false);
199
+		// setup empty config classes
200
+		$this->_initialize_config();
201
+		// load existing EE site settings
202
+		$this->_load_core_config();
203
+		// confirm everything loaded correctly and set filtered defaults if not
204
+		$this->_verify_config();
205
+		//  register shortcodes and modules
206
+		add_action(
207
+			'AHEE__EE_System__register_shortcodes_modules_and_widgets',
208
+			array($this, 'register_shortcodes_and_modules'),
209
+			999
210
+		);
211
+		//  initialize shortcodes and modules
212
+		add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'initialize_shortcodes_and_modules'));
213
+		// register widgets
214
+		add_action('widgets_init', array($this, 'widgets_init'), 10);
215
+		// shutdown
216
+		add_action('shutdown', array($this, 'shutdown'), 10);
217
+		// construct__end hook
218
+		do_action('AHEE__EE_Config__construct__end', $this);
219
+		// hardcoded hack
220
+		$this->template_settings->current_espresso_theme = 'Espresso_Arabica_2014';
221
+	}
222
+
223
+
224
+	/**
225
+	 * @return boolean
226
+	 */
227
+	public static function logging_enabled()
228
+	{
229
+		return self::$_logging_enabled;
230
+	}
231
+
232
+
233
+	/**
234
+	 * use to get the current theme if needed from static context
235
+	 *
236
+	 * @return string current theme set.
237
+	 */
238
+	public static function get_current_theme()
239
+	{
240
+		return isset(self::$_instance->template_settings->current_espresso_theme)
241
+			? self::$_instance->template_settings->current_espresso_theme : 'Espresso_Arabica_2014';
242
+	}
243
+
244
+
245
+	/**
246
+	 *        _initialize_config
247
+	 *
248
+	 * @access private
249
+	 * @return void
250
+	 */
251
+	private function _initialize_config()
252
+	{
253
+		EE_Config::trim_log();
254
+		// set defaults
255
+		$this->_addon_option_names = get_option(EE_Config::ADDON_OPTION_NAMES, array());
256
+		$this->addons = new stdClass();
257
+		// set _module_route_map
258
+		EE_Config::$_module_route_map = array();
259
+		// set _module_forward_map
260
+		EE_Config::$_module_forward_map = array();
261
+		// set _module_view_map
262
+		EE_Config::$_module_view_map = array();
263
+	}
264
+
265
+
266
+	/**
267
+	 *        load core plugin configuration
268
+	 *
269
+	 * @access private
270
+	 * @return void
271
+	 */
272
+	private function _load_core_config()
273
+	{
274
+		// load_core_config__start hook
275
+		do_action('AHEE__EE_Config___load_core_config__start', $this);
276
+		$espresso_config = $this->get_espresso_config();
277
+		foreach ($espresso_config as $config => $settings) {
278
+			// load_core_config__start hook
279
+			$settings = apply_filters(
280
+				'FHEE__EE_Config___load_core_config__config_settings',
281
+				$settings,
282
+				$config,
283
+				$this
284
+			);
285
+			if (is_object($settings) && property_exists($this, $config)) {
286
+				$this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__' . $config, $settings);
287
+				// call configs populate method to ensure any defaults are set for empty values.
288
+				if (method_exists($settings, 'populate')) {
289
+					$this->{$config}->populate();
290
+				}
291
+				if (method_exists($settings, 'do_hooks')) {
292
+					$this->{$config}->do_hooks();
293
+				}
294
+			}
295
+		}
296
+		if (apply_filters('FHEE__EE_Config___load_core_config__update_espresso_config', false)) {
297
+			$this->update_espresso_config();
298
+		}
299
+		// load_core_config__end hook
300
+		do_action('AHEE__EE_Config___load_core_config__end', $this);
301
+	}
302
+
303
+
304
+	/**
305
+	 *    _verify_config
306
+	 *
307
+	 * @access    protected
308
+	 * @return    void
309
+	 */
310
+	protected function _verify_config()
311
+	{
312
+		$this->core = $this->core instanceof EE_Core_Config
313
+			? $this->core
314
+			: new EE_Core_Config();
315
+		$this->core = apply_filters('FHEE__EE_Config___initialize_config__core', $this->core);
316
+		$this->organization = $this->organization instanceof EE_Organization_Config
317
+			? $this->organization
318
+			: new EE_Organization_Config();
319
+		$this->organization = apply_filters(
320
+			'FHEE__EE_Config___initialize_config__organization',
321
+			$this->organization
322
+		);
323
+		$this->currency = $this->currency instanceof EE_Currency_Config
324
+			? $this->currency
325
+			: new EE_Currency_Config();
326
+		$this->currency = apply_filters('FHEE__EE_Config___initialize_config__currency', $this->currency);
327
+		$this->registration = $this->registration instanceof EE_Registration_Config
328
+			? $this->registration
329
+			: new EE_Registration_Config();
330
+		$this->registration = apply_filters(
331
+			'FHEE__EE_Config___initialize_config__registration',
332
+			$this->registration
333
+		);
334
+		$this->admin = $this->admin instanceof EE_Admin_Config
335
+			? $this->admin
336
+			: new EE_Admin_Config();
337
+		$this->admin = apply_filters('FHEE__EE_Config___initialize_config__admin', $this->admin);
338
+		$this->template_settings = $this->template_settings instanceof EE_Template_Config
339
+			? $this->template_settings
340
+			: new EE_Template_Config();
341
+		$this->template_settings = apply_filters(
342
+			'FHEE__EE_Config___initialize_config__template_settings',
343
+			$this->template_settings
344
+		);
345
+		$this->map_settings = $this->map_settings instanceof EE_Map_Config
346
+			? $this->map_settings
347
+			: new EE_Map_Config();
348
+		$this->map_settings = apply_filters(
349
+			'FHEE__EE_Config___initialize_config__map_settings',
350
+			$this->map_settings
351
+		);
352
+		$this->environment = $this->environment instanceof EE_Environment_Config
353
+			? $this->environment
354
+			: new EE_Environment_Config();
355
+		$this->environment = apply_filters(
356
+			'FHEE__EE_Config___initialize_config__environment',
357
+			$this->environment
358
+		);
359
+		$this->tax_settings = $this->tax_settings instanceof EE_Tax_Config
360
+			? $this->tax_settings
361
+			: new EE_Tax_Config();
362
+		$this->tax_settings = apply_filters(
363
+			'FHEE__EE_Config___initialize_config__tax_settings',
364
+			$this->tax_settings
365
+		);
366
+		$this->messages = apply_filters('FHEE__EE_Config__initialize_config__messages', $this->messages);
367
+		$this->messages = $this->messages instanceof EE_Messages_Config
368
+			? $this->messages
369
+			: new EE_Messages_Config();
370
+		$this->gateway = $this->gateway instanceof EE_Gateway_Config
371
+			? $this->gateway
372
+			: new EE_Gateway_Config();
373
+		$this->gateway = apply_filters('FHEE__EE_Config___initialize_config__gateway', $this->gateway);
374
+		$this->legacy_shortcodes_manager = null;
375
+	}
376
+
377
+
378
+	/**
379
+	 *    get_espresso_config
380
+	 *
381
+	 * @access    public
382
+	 * @return    array of espresso config stuff
383
+	 */
384
+	public function get_espresso_config()
385
+	{
386
+		// grab espresso configuration
387
+		return apply_filters(
388
+			'FHEE__EE_Config__get_espresso_config__CFG',
389
+			get_option(EE_Config::OPTION_NAME, array())
390
+		);
391
+	}
392
+
393
+
394
+	/**
395
+	 *    double_check_config_comparison
396
+	 *
397
+	 * @access    public
398
+	 * @param string $option
399
+	 * @param        $old_value
400
+	 * @param        $value
401
+	 */
402
+	public function double_check_config_comparison($option = '', $old_value, $value)
403
+	{
404
+		// make sure we're checking the ee config
405
+		if ($option === EE_Config::OPTION_NAME) {
406
+			// run a loose comparison of the old value against the new value for type and properties,
407
+			// but NOT exact instance like WP update_option does (ie: NOT type safe comparison)
408
+			if ($value != $old_value) {
409
+				// if they are NOT the same, then remove the hook,
410
+				// which means the subsequent update results will be based solely on the update query results
411
+				// the reason we do this is because, as stated above,
412
+				// WP update_option performs an exact instance comparison (===) on any update values passed to it
413
+				// this happens PRIOR to serialization and any subsequent update.
414
+				// If values are found to match their previous old value,
415
+				// then WP bails before performing any update.
416
+				// Since we are passing the EE_Config object, it is comparing the EXACT instance of the saved version
417
+				// it just pulled from the db, with the one being passed to it (which will not match).
418
+				// HOWEVER, once the object is serialized and passed off to MySQL to update,
419
+				// MySQL MAY ALSO NOT perform the update because
420
+				// the string it sees in the db looks the same as the new one it has been passed!!!
421
+				// This results in the query returning an "affected rows" value of ZERO,
422
+				// which gets returned immediately by WP update_option and looks like an error.
423
+				remove_action('update_option', array($this, 'check_config_updated'));
424
+			}
425
+		}
426
+	}
427
+
428
+
429
+	/**
430
+	 *    update_espresso_config
431
+	 *
432
+	 * @access   public
433
+	 */
434
+	protected function _reset_espresso_addon_config()
435
+	{
436
+		$this->_addon_option_names = array();
437
+		foreach ($this->addons as $addon_name => $addon_config_obj) {
438
+			$addon_config_obj = maybe_unserialize($addon_config_obj);
439
+			if ($addon_config_obj instanceof EE_Config_Base) {
440
+				$this->update_config('addons', $addon_name, $addon_config_obj, false);
441
+			}
442
+			$this->addons->{$addon_name} = null;
443
+		}
444
+	}
445
+
446
+
447
+	/**
448
+	 *    update_espresso_config
449
+	 *
450
+	 * @access   public
451
+	 * @param   bool $add_success
452
+	 * @param   bool $add_error
453
+	 * @return   bool
454
+	 */
455
+	public function update_espresso_config($add_success = false, $add_error = true)
456
+	{
457
+		// don't allow config updates during WP heartbeats
458
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
459
+			return false;
460
+		}
461
+		// commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
462
+		// $clone = clone( self::$_instance );
463
+		// self::$_instance = NULL;
464
+		do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
465
+		$this->_reset_espresso_addon_config();
466
+		// hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
467
+		// but BEFORE the actual update occurs
468
+		add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
469
+		// don't want to persist legacy_shortcodes_manager, but don't want to lose it either
470
+		$legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
471
+		$this->legacy_shortcodes_manager = null;
472
+		// now update "ee_config"
473
+		$saved = update_option(EE_Config::OPTION_NAME, $this);
474
+		$this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
475
+		EE_Config::log(EE_Config::OPTION_NAME);
476
+		// if not saved... check if the hook we just added still exists;
477
+		// if it does, it means one of two things:
478
+		// that update_option bailed at the($value === $old_value) conditional,
479
+		// or...
480
+		// the db update query returned 0 rows affected
481
+		// (probably because the data  value was the same from it's perspective)
482
+		// so the existence of the hook means that a negative result from update_option is NOT an error,
483
+		// but just means no update occurred, so don't display an error to the user.
484
+		// BUT... if update_option returns FALSE, AND the hook is missing,
485
+		// then it means that something truly went wrong
486
+		$saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
487
+		// remove our action since we don't want it in the system anymore
488
+		remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
489
+		do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
490
+		// self::$_instance = $clone;
491
+		// unset( $clone );
492
+		// if config remains the same or was updated successfully
493
+		if ($saved) {
494
+			if ($add_success) {
495
+				EE_Error::add_success(
496
+					__('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
497
+					__FILE__,
498
+					__FUNCTION__,
499
+					__LINE__
500
+				);
501
+			}
502
+			return true;
503
+		} else {
504
+			if ($add_error) {
505
+				EE_Error::add_error(
506
+					__('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
507
+					__FILE__,
508
+					__FUNCTION__,
509
+					__LINE__
510
+				);
511
+			}
512
+			return false;
513
+		}
514
+	}
515
+
516
+
517
+	/**
518
+	 *    _verify_config_params
519
+	 *
520
+	 * @access    private
521
+	 * @param    string         $section
522
+	 * @param    string         $name
523
+	 * @param    string         $config_class
524
+	 * @param    EE_Config_Base $config_obj
525
+	 * @param    array          $tests_to_run
526
+	 * @param    bool           $display_errors
527
+	 * @return    bool    TRUE on success, FALSE on fail
528
+	 */
529
+	private function _verify_config_params(
530
+		$section = '',
531
+		$name = '',
532
+		$config_class = '',
533
+		$config_obj = null,
534
+		$tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
535
+		$display_errors = true
536
+	) {
537
+		try {
538
+			foreach ($tests_to_run as $test) {
539
+				switch ($test) {
540
+					// TEST #1 : check that section was set
541
+					case 1:
542
+						if (empty($section)) {
543
+							if ($display_errors) {
544
+								throw new EE_Error(
545
+									sprintf(
546
+										__(
547
+											'No configuration section has been provided while attempting to save "%s".',
548
+											'event_espresso'
549
+										),
550
+										$config_class
551
+									)
552
+								);
553
+							}
554
+							return false;
555
+						}
556
+						break;
557
+					// TEST #2 : check that settings section exists
558
+					case 2:
559
+						if (! isset($this->{$section})) {
560
+							if ($display_errors) {
561
+								throw new EE_Error(
562
+									sprintf(
563
+										__('The "%s" configuration section does not exist.', 'event_espresso'),
564
+										$section
565
+									)
566
+								);
567
+							}
568
+							return false;
569
+						}
570
+						break;
571
+					// TEST #3 : check that section is the proper format
572
+					case 3:
573
+						if (! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
574
+						) {
575
+							if ($display_errors) {
576
+								throw new EE_Error(
577
+									sprintf(
578
+										__(
579
+											'The "%s" configuration settings have not been formatted correctly.',
580
+											'event_espresso'
581
+										),
582
+										$section
583
+									)
584
+								);
585
+							}
586
+							return false;
587
+						}
588
+						break;
589
+					// TEST #4 : check that config section name has been set
590
+					case 4:
591
+						if (empty($name)) {
592
+							if ($display_errors) {
593
+								throw new EE_Error(
594
+									__(
595
+										'No name has been provided for the specific configuration section.',
596
+										'event_espresso'
597
+									)
598
+								);
599
+							}
600
+							return false;
601
+						}
602
+						break;
603
+					// TEST #5 : check that a config class name has been set
604
+					case 5:
605
+						if (empty($config_class)) {
606
+							if ($display_errors) {
607
+								throw new EE_Error(
608
+									__(
609
+										'No class name has been provided for the specific configuration section.',
610
+										'event_espresso'
611
+									)
612
+								);
613
+							}
614
+							return false;
615
+						}
616
+						break;
617
+					// TEST #6 : verify config class is accessible
618
+					case 6:
619
+						if (! class_exists($config_class)) {
620
+							if ($display_errors) {
621
+								throw new EE_Error(
622
+									sprintf(
623
+										__(
624
+											'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
625
+											'event_espresso'
626
+										),
627
+										$config_class
628
+									)
629
+								);
630
+							}
631
+							return false;
632
+						}
633
+						break;
634
+					// TEST #7 : check that config has even been set
635
+					case 7:
636
+						if (! isset($this->{$section}->{$name})) {
637
+							if ($display_errors) {
638
+								throw new EE_Error(
639
+									sprintf(
640
+										__('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
641
+										$section,
642
+										$name
643
+									)
644
+								);
645
+							}
646
+							return false;
647
+						} else {
648
+							// and make sure it's not serialized
649
+							$this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
650
+						}
651
+						break;
652
+					// TEST #8 : check that config is the requested type
653
+					case 8:
654
+						if (! $this->{$section}->{$name} instanceof $config_class) {
655
+							if ($display_errors) {
656
+								throw new EE_Error(
657
+									sprintf(
658
+										__(
659
+											'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
660
+											'event_espresso'
661
+										),
662
+										$section,
663
+										$name,
664
+										$config_class
665
+									)
666
+								);
667
+							}
668
+							return false;
669
+						}
670
+						break;
671
+					// TEST #9 : verify config object
672
+					case 9:
673
+						if (! $config_obj instanceof EE_Config_Base) {
674
+							if ($display_errors) {
675
+								throw new EE_Error(
676
+									sprintf(
677
+										__('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
678
+										print_r($config_obj, true)
679
+									)
680
+								);
681
+							}
682
+							return false;
683
+						}
684
+						break;
685
+				}
686
+			}
687
+		} catch (EE_Error $e) {
688
+			$e->get_error();
689
+		}
690
+		// you have successfully run the gauntlet
691
+		return true;
692
+	}
693
+
694
+
695
+	/**
696
+	 *    _generate_config_option_name
697
+	 *
698
+	 * @access        protected
699
+	 * @param        string $section
700
+	 * @param        string $name
701
+	 * @return        string
702
+	 */
703
+	private function _generate_config_option_name($section = '', $name = '')
704
+	{
705
+		return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
706
+	}
707
+
708
+
709
+	/**
710
+	 *    _set_config_class
711
+	 * ensures that a config class is set, either from a passed config class or one generated from the config name
712
+	 *
713
+	 * @access    private
714
+	 * @param    string $config_class
715
+	 * @param    string $name
716
+	 * @return    string
717
+	 */
718
+	private function _set_config_class($config_class = '', $name = '')
719
+	{
720
+		return ! empty($config_class)
721
+			? $config_class
722
+			: str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
723
+	}
724
+
725
+
726
+	/**
727
+	 *    set_config
728
+	 *
729
+	 * @access    protected
730
+	 * @param    string         $section
731
+	 * @param    string         $name
732
+	 * @param    string         $config_class
733
+	 * @param    EE_Config_Base $config_obj
734
+	 * @return    EE_Config_Base
735
+	 */
736
+	public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
737
+	{
738
+		// ensure config class is set to something
739
+		$config_class = $this->_set_config_class($config_class, $name);
740
+		// run tests 1-4, 6, and 7 to verify all config params are set and valid
741
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
742
+			return null;
743
+		}
744
+		$config_option_name = $this->_generate_config_option_name($section, $name);
745
+		// if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
746
+		if (! isset($this->_addon_option_names[ $config_option_name ])) {
747
+			$this->_addon_option_names[ $config_option_name ] = $config_class;
748
+			$this->update_addon_option_names();
749
+		}
750
+		// verify the incoming config object but suppress errors
751
+		if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
752
+			$config_obj = new $config_class();
753
+		}
754
+		if (get_option($config_option_name)) {
755
+			EE_Config::log($config_option_name);
756
+			update_option($config_option_name, $config_obj);
757
+			$this->{$section}->{$name} = $config_obj;
758
+			return $this->{$section}->{$name};
759
+		} else {
760
+			// create a wp-option for this config
761
+			if (add_option($config_option_name, $config_obj, '', 'no')) {
762
+				$this->{$section}->{$name} = maybe_unserialize($config_obj);
763
+				return $this->{$section}->{$name};
764
+			} else {
765
+				EE_Error::add_error(
766
+					sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
767
+					__FILE__,
768
+					__FUNCTION__,
769
+					__LINE__
770
+				);
771
+				return null;
772
+			}
773
+		}
774
+	}
775
+
776
+
777
+	/**
778
+	 *    update_config
779
+	 * Important: the config object must ALREADY be set, otherwise this will produce an error.
780
+	 *
781
+	 * @access    public
782
+	 * @param    string                $section
783
+	 * @param    string                $name
784
+	 * @param    EE_Config_Base|string $config_obj
785
+	 * @param    bool                  $throw_errors
786
+	 * @return    bool
787
+	 */
788
+	public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
789
+	{
790
+		// don't allow config updates during WP heartbeats
791
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
792
+			return false;
793
+		}
794
+		$config_obj = maybe_unserialize($config_obj);
795
+		// get class name of the incoming object
796
+		$config_class = get_class($config_obj);
797
+		// run tests 1-5 and 9 to verify config
798
+		if (! $this->_verify_config_params(
799
+			$section,
800
+			$name,
801
+			$config_class,
802
+			$config_obj,
803
+			array(1, 2, 3, 4, 7, 9)
804
+		)
805
+		) {
806
+			return false;
807
+		}
808
+		$config_option_name = $this->_generate_config_option_name($section, $name);
809
+		// check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
810
+		if (! isset($this->_addon_option_names[ $config_option_name ])) {
811
+			// save new config to db
812
+			if ($this->set_config($section, $name, $config_class, $config_obj)) {
813
+				return true;
814
+			}
815
+		} else {
816
+			// first check if the record already exists
817
+			$existing_config = get_option($config_option_name);
818
+			$config_obj = serialize($config_obj);
819
+			// just return if db record is already up to date (NOT type safe comparison)
820
+			if ($existing_config == $config_obj) {
821
+				$this->{$section}->{$name} = $config_obj;
822
+				return true;
823
+			} elseif (update_option($config_option_name, $config_obj)) {
824
+				EE_Config::log($config_option_name);
825
+				// update wp-option for this config class
826
+				$this->{$section}->{$name} = $config_obj;
827
+				return true;
828
+			} elseif ($throw_errors) {
829
+				EE_Error::add_error(
830
+					sprintf(
831
+						__(
832
+							'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
833
+							'event_espresso'
834
+						),
835
+						$config_class,
836
+						'EE_Config->' . $section . '->' . $name
837
+					),
838
+					__FILE__,
839
+					__FUNCTION__,
840
+					__LINE__
841
+				);
842
+			}
843
+		}
844
+		return false;
845
+	}
846
+
847
+
848
+	/**
849
+	 *    get_config
850
+	 *
851
+	 * @access    public
852
+	 * @param    string $section
853
+	 * @param    string $name
854
+	 * @param    string $config_class
855
+	 * @return    mixed EE_Config_Base | NULL
856
+	 */
857
+	public function get_config($section = '', $name = '', $config_class = '')
858
+	{
859
+		// ensure config class is set to something
860
+		$config_class = $this->_set_config_class($config_class, $name);
861
+		// run tests 1-4, 6 and 7 to verify that all params have been set
862
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
863
+			return null;
864
+		}
865
+		// now test if the requested config object exists, but suppress errors
866
+		if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
867
+			// config already exists, so pass it back
868
+			return $this->{$section}->{$name};
869
+		}
870
+		// load config option from db if it exists
871
+		$config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
872
+		// verify the newly retrieved config object, but suppress errors
873
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
874
+			// config is good, so set it and pass it back
875
+			$this->{$section}->{$name} = $config_obj;
876
+			return $this->{$section}->{$name};
877
+		}
878
+		// oops! $config_obj is not already set and does not exist in the db, so create a new one
879
+		$config_obj = $this->set_config($section, $name, $config_class);
880
+		// verify the newly created config object
881
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
882
+			return $this->{$section}->{$name};
883
+		} else {
884
+			EE_Error::add_error(
885
+				sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
886
+				__FILE__,
887
+				__FUNCTION__,
888
+				__LINE__
889
+			);
890
+		}
891
+		return null;
892
+	}
893
+
894
+
895
+	/**
896
+	 *    get_config_option
897
+	 *
898
+	 * @access    public
899
+	 * @param    string $config_option_name
900
+	 * @return    mixed EE_Config_Base | FALSE
901
+	 */
902
+	public function get_config_option($config_option_name = '')
903
+	{
904
+		// retrieve the wp-option for this config class.
905
+		$config_option = maybe_unserialize(get_option($config_option_name, array()));
906
+		if (empty($config_option)) {
907
+			EE_Config::log($config_option_name . '-NOT-FOUND');
908
+		}
909
+		return $config_option;
910
+	}
911
+
912
+
913
+	/**
914
+	 * log
915
+	 *
916
+	 * @param string $config_option_name
917
+	 */
918
+	public static function log($config_option_name = '')
919
+	{
920
+		if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
921
+			$config_log = get_option(EE_Config::LOG_NAME, array());
922
+			// copy incoming $_REQUEST and sanitize it so we can save it
923
+			$_request = $_REQUEST;
924
+			array_walk_recursive($_request, 'sanitize_text_field');
925
+			$config_log[ (string) microtime(true) ] = array(
926
+				'config_name' => $config_option_name,
927
+				'request'     => $_request,
928
+			);
929
+			update_option(EE_Config::LOG_NAME, $config_log);
930
+		}
931
+	}
932
+
933
+
934
+	/**
935
+	 * trim_log
936
+	 * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
937
+	 */
938
+	public static function trim_log()
939
+	{
940
+		if (! EE_Config::logging_enabled()) {
941
+			return;
942
+		}
943
+		$config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
944
+		$log_length = count($config_log);
945
+		if ($log_length > EE_Config::LOG_LENGTH) {
946
+			ksort($config_log);
947
+			$config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
948
+			update_option(EE_Config::LOG_NAME, $config_log);
949
+		}
950
+	}
951
+
952
+
953
+	/**
954
+	 *    get_page_for_posts
955
+	 *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
956
+	 *    wp-option "page_for_posts", or "posts" if no page is selected
957
+	 *
958
+	 * @access    public
959
+	 * @return    string
960
+	 */
961
+	public static function get_page_for_posts()
962
+	{
963
+		$page_for_posts = get_option('page_for_posts');
964
+		if (! $page_for_posts) {
965
+			return 'posts';
966
+		}
967
+		/** @type WPDB $wpdb */
968
+		global $wpdb;
969
+		$SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
970
+		return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
971
+	}
972
+
973
+
974
+	/**
975
+	 *    register_shortcodes_and_modules.
976
+	 *    At this point, it's too early to tell if we're maintenance mode or not.
977
+	 *    In fact, this is where we give modules a chance to let core know they exist
978
+	 *    so they can help trigger maintenance mode if it's needed
979
+	 *
980
+	 * @access    public
981
+	 * @return    void
982
+	 */
983
+	public function register_shortcodes_and_modules()
984
+	{
985
+		// allow modules to set hooks for the rest of the system
986
+		EE_Registry::instance()->modules = $this->_register_modules();
987
+	}
988
+
989
+
990
+	/**
991
+	 *    initialize_shortcodes_and_modules
992
+	 *    meaning they can start adding their hooks to get stuff done
993
+	 *
994
+	 * @access    public
995
+	 * @return    void
996
+	 */
997
+	public function initialize_shortcodes_and_modules()
998
+	{
999
+		// allow modules to set hooks for the rest of the system
1000
+		$this->_initialize_modules();
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 *    widgets_init
1006
+	 *
1007
+	 * @access private
1008
+	 * @return void
1009
+	 */
1010
+	public function widgets_init()
1011
+	{
1012
+		// only init widgets on admin pages when not in complete maintenance, and
1013
+		// on frontend when not in any maintenance mode
1014
+		if (! EE_Maintenance_Mode::instance()->level()
1015
+			|| (
1016
+				is_admin()
1017
+				&& EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1018
+			)
1019
+		) {
1020
+			// grab list of installed widgets
1021
+			$widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1022
+			// filter list of modules to register
1023
+			$widgets_to_register = apply_filters(
1024
+				'FHEE__EE_Config__register_widgets__widgets_to_register',
1025
+				$widgets_to_register
1026
+			);
1027
+			if (! empty($widgets_to_register)) {
1028
+				// cycle thru widget folders
1029
+				foreach ($widgets_to_register as $widget_path) {
1030
+					// add to list of installed widget modules
1031
+					EE_Config::register_ee_widget($widget_path);
1032
+				}
1033
+			}
1034
+			// filter list of installed modules
1035
+			EE_Registry::instance()->widgets = apply_filters(
1036
+				'FHEE__EE_Config__register_widgets__installed_widgets',
1037
+				EE_Registry::instance()->widgets
1038
+			);
1039
+		}
1040
+	}
1041
+
1042
+
1043
+	/**
1044
+	 *    register_ee_widget - makes core aware of this widget
1045
+	 *
1046
+	 * @access    public
1047
+	 * @param    string $widget_path - full path up to and including widget folder
1048
+	 * @return    void
1049
+	 */
1050
+	public static function register_ee_widget($widget_path = null)
1051
+	{
1052
+		do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1053
+		$widget_ext = '.widget.php';
1054
+		// make all separators match
1055
+		$widget_path = rtrim(str_replace('\\', DS, $widget_path), DS);
1056
+		// does the file path INCLUDE the actual file name as part of the path ?
1057
+		if (strpos($widget_path, $widget_ext) !== false) {
1058
+			// grab and shortcode file name from directory name and break apart at dots
1059
+			$file_name = explode('.', basename($widget_path));
1060
+			// take first segment from file name pieces and remove class prefix if it exists
1061
+			$widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1062
+			// sanitize shortcode directory name
1063
+			$widget = sanitize_key($widget);
1064
+			// now we need to rebuild the shortcode path
1065
+			$widget_path = explode(DS, $widget_path);
1066
+			// remove last segment
1067
+			array_pop($widget_path);
1068
+			// glue it back together
1069
+			$widget_path = implode(DS, $widget_path);
1070
+		} else {
1071
+			// grab and sanitize widget directory name
1072
+			$widget = sanitize_key(basename($widget_path));
1073
+		}
1074
+		// create classname from widget directory name
1075
+		$widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1076
+		// add class prefix
1077
+		$widget_class = 'EEW_' . $widget;
1078
+		// does the widget exist ?
1079
+		if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1080
+			$msg = sprintf(
1081
+				__(
1082
+					'The requested %s widget file could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s',
1083
+					'event_espresso'
1084
+				),
1085
+				$widget_class,
1086
+				$widget_path . DS . $widget_class . $widget_ext
1087
+			);
1088
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1089
+			return;
1090
+		}
1091
+		// load the widget class file
1092
+		require_once($widget_path . DS . $widget_class . $widget_ext);
1093
+		// verify that class exists
1094
+		if (! class_exists($widget_class)) {
1095
+			$msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1096
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1097
+			return;
1098
+		}
1099
+		register_widget($widget_class);
1100
+		// add to array of registered widgets
1101
+		EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 *        _register_modules
1107
+	 *
1108
+	 * @access private
1109
+	 * @return array
1110
+	 */
1111
+	private function _register_modules()
1112
+	{
1113
+		// grab list of installed modules
1114
+		$modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1115
+		// filter list of modules to register
1116
+		$modules_to_register = apply_filters(
1117
+			'FHEE__EE_Config__register_modules__modules_to_register',
1118
+			$modules_to_register
1119
+		);
1120
+		if (! empty($modules_to_register)) {
1121
+			// loop through folders
1122
+			foreach ($modules_to_register as $module_path) {
1123
+				/**TEMPORARILY EXCLUDE gateways from modules for time being**/
1124
+				if ($module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1125
+					&& $module_path !== EE_MODULES . 'gateways'
1126
+				) {
1127
+					// add to list of installed modules
1128
+					EE_Config::register_module($module_path);
1129
+				}
1130
+			}
1131
+		}
1132
+		// filter list of installed modules
1133
+		return apply_filters(
1134
+			'FHEE__EE_Config___register_modules__installed_modules',
1135
+			EE_Registry::instance()->modules
1136
+		);
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 *    register_module - makes core aware of this module
1142
+	 *
1143
+	 * @access    public
1144
+	 * @param    string $module_path - full path up to and including module folder
1145
+	 * @return    bool
1146
+	 */
1147
+	public static function register_module($module_path = null)
1148
+	{
1149
+		do_action('AHEE__EE_Config__register_module__begin', $module_path);
1150
+		$module_ext = '.module.php';
1151
+		// make all separators match
1152
+		$module_path = str_replace(array('\\', '/'), DS, $module_path);
1153
+		// does the file path INCLUDE the actual file name as part of the path ?
1154
+		if (strpos($module_path, $module_ext) !== false) {
1155
+			// grab and shortcode file name from directory name and break apart at dots
1156
+			$module_file = explode('.', basename($module_path));
1157
+			// now we need to rebuild the shortcode path
1158
+			$module_path = explode(DS, $module_path);
1159
+			// remove last segment
1160
+			array_pop($module_path);
1161
+			// glue it back together
1162
+			$module_path = implode(DS, $module_path) . DS;
1163
+			// take first segment from file name pieces and sanitize it
1164
+			$module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1165
+			// ensure class prefix is added
1166
+			$module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1167
+		} else {
1168
+			// we need to generate the filename based off of the folder name
1169
+			// grab and sanitize module name
1170
+			$module = strtolower(basename($module_path));
1171
+			$module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1172
+			// like trailingslashit()
1173
+			$module_path = rtrim($module_path, DS) . DS;
1174
+			// create classname from module directory name
1175
+			$module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1176
+			// add class prefix
1177
+			$module_class = 'EED_' . $module;
1178
+		}
1179
+		// does the module exist ?
1180
+		if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1181
+			$msg = sprintf(
1182
+				__(
1183
+					'The requested %s module file could not be found or is not readable due to file permissions.',
1184
+					'event_espresso'
1185
+				),
1186
+				$module
1187
+			);
1188
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1189
+			return false;
1190
+		}
1191
+		// load the module class file
1192
+		require_once($module_path . $module_class . $module_ext);
1193
+		// verify that class exists
1194
+		if (! class_exists($module_class)) {
1195
+			$msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1196
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1197
+			return false;
1198
+		}
1199
+		// add to array of registered modules
1200
+		EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1201
+		do_action(
1202
+			'AHEE__EE_Config__register_module__complete',
1203
+			$module_class,
1204
+			EE_Registry::instance()->modules->{$module_class}
1205
+		);
1206
+		return true;
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 *    _initialize_modules
1212
+	 *    allow modules to set hooks for the rest of the system
1213
+	 *
1214
+	 * @access private
1215
+	 * @return void
1216
+	 */
1217
+	private function _initialize_modules()
1218
+	{
1219
+		// cycle thru shortcode folders
1220
+		foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1221
+			// fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1222
+			// which set hooks ?
1223
+			if (is_admin()) {
1224
+				// fire immediately
1225
+				call_user_func(array($module_class, 'set_hooks_admin'));
1226
+			} else {
1227
+				// delay until other systems are online
1228
+				add_action(
1229
+					'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1230
+					array($module_class, 'set_hooks')
1231
+				);
1232
+			}
1233
+		}
1234
+	}
1235
+
1236
+
1237
+	/**
1238
+	 *    register_route - adds module method routes to route_map
1239
+	 *
1240
+	 * @access    public
1241
+	 * @param    string $route       - "pretty" public alias for module method
1242
+	 * @param    string $module      - module name (classname without EED_ prefix)
1243
+	 * @param    string $method_name - the actual module method to be routed to
1244
+	 * @param    string $key         - url param key indicating a route is being called
1245
+	 * @return    bool
1246
+	 */
1247
+	public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1248
+	{
1249
+		do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1250
+		$module = str_replace('EED_', '', $module);
1251
+		$module_class = 'EED_' . $module;
1252
+		if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1253
+			$msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1254
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1255
+			return false;
1256
+		}
1257
+		if (empty($route)) {
1258
+			$msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1259
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1260
+			return false;
1261
+		}
1262
+		if (! method_exists('EED_' . $module, $method_name)) {
1263
+			$msg = sprintf(
1264
+				__('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1265
+				$route
1266
+			);
1267
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1268
+			return false;
1269
+		}
1270
+		EE_Config::$_module_route_map[ (string) $key ][ (string) $route ] = array('EED_' . $module, $method_name);
1271
+		return true;
1272
+	}
1273
+
1274
+
1275
+	/**
1276
+	 *    get_route - get module method route
1277
+	 *
1278
+	 * @access    public
1279
+	 * @param    string $route - "pretty" public alias for module method
1280
+	 * @param    string $key   - url param key indicating a route is being called
1281
+	 * @return    string
1282
+	 */
1283
+	public static function get_route($route = null, $key = 'ee')
1284
+	{
1285
+		do_action('AHEE__EE_Config__get_route__begin', $route);
1286
+		$route = (string) apply_filters('FHEE__EE_Config__get_route', $route);
1287
+		if (isset(EE_Config::$_module_route_map[ $key ][ $route ])) {
1288
+			return EE_Config::$_module_route_map[ $key ][ $route ];
1289
+		}
1290
+		return null;
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 *    get_routes - get ALL module method routes
1296
+	 *
1297
+	 * @access    public
1298
+	 * @return    array
1299
+	 */
1300
+	public static function get_routes()
1301
+	{
1302
+		return EE_Config::$_module_route_map;
1303
+	}
1304
+
1305
+
1306
+	/**
1307
+	 *    register_forward - allows modules to forward request to another module for further processing
1308
+	 *
1309
+	 * @access    public
1310
+	 * @param    string       $route   - "pretty" public alias for module method
1311
+	 * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1312
+	 *                                 class, allows different forwards to be served based on status
1313
+	 * @param    array|string $forward - function name or array( class, method )
1314
+	 * @param    string       $key     - url param key indicating a route is being called
1315
+	 * @return    bool
1316
+	 */
1317
+	public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1318
+	{
1319
+		do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1320
+		if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1321
+			$msg = sprintf(
1322
+				__('The module route %s for this forward has not been registered.', 'event_espresso'),
1323
+				$route
1324
+			);
1325
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1326
+			return false;
1327
+		}
1328
+		if (empty($forward)) {
1329
+			$msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1330
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1331
+			return false;
1332
+		}
1333
+		if (is_array($forward)) {
1334
+			if (! isset($forward[1])) {
1335
+				$msg = sprintf(
1336
+					__('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1337
+					$route
1338
+				);
1339
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1340
+				return false;
1341
+			}
1342
+			if (! method_exists($forward[0], $forward[1])) {
1343
+				$msg = sprintf(
1344
+					__('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1345
+					$forward[1],
1346
+					$route
1347
+				);
1348
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1349
+				return false;
1350
+			}
1351
+		} elseif (! function_exists($forward)) {
1352
+			$msg = sprintf(
1353
+				__('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1354
+				$forward,
1355
+				$route
1356
+			);
1357
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1358
+			return false;
1359
+		}
1360
+		EE_Config::$_module_forward_map[ $key ][ $route ][ absint($status) ] = $forward;
1361
+		return true;
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 *    get_forward - get forwarding route
1367
+	 *
1368
+	 * @access    public
1369
+	 * @param    string  $route  - "pretty" public alias for module method
1370
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1371
+	 *                           allows different forwards to be served based on status
1372
+	 * @param    string  $key    - url param key indicating a route is being called
1373
+	 * @return    string
1374
+	 */
1375
+	public static function get_forward($route = null, $status = 0, $key = 'ee')
1376
+	{
1377
+		do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1378
+		if (isset(EE_Config::$_module_forward_map[ $key ][ $route ][ $status ])) {
1379
+			return apply_filters(
1380
+				'FHEE__EE_Config__get_forward',
1381
+				EE_Config::$_module_forward_map[ $key ][ $route ][ $status ],
1382
+				$route,
1383
+				$status
1384
+			);
1385
+		}
1386
+		return null;
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 *    register_forward - allows modules to specify different view templates for different method routes and status
1392
+	 *    results
1393
+	 *
1394
+	 * @access    public
1395
+	 * @param    string  $route  - "pretty" public alias for module method
1396
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1397
+	 *                           allows different views to be served based on status
1398
+	 * @param    string  $view
1399
+	 * @param    string  $key    - url param key indicating a route is being called
1400
+	 * @return    bool
1401
+	 */
1402
+	public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1403
+	{
1404
+		do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1405
+		if (! isset(EE_Config::$_module_route_map[ $key ][ $route ]) || empty($route)) {
1406
+			$msg = sprintf(
1407
+				__('The module route %s for this view has not been registered.', 'event_espresso'),
1408
+				$route
1409
+			);
1410
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1411
+			return false;
1412
+		}
1413
+		if (! is_readable($view)) {
1414
+			$msg = sprintf(
1415
+				__(
1416
+					'The %s view file could not be found or is not readable due to file permissions.',
1417
+					'event_espresso'
1418
+				),
1419
+				$view
1420
+			);
1421
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1422
+			return false;
1423
+		}
1424
+		EE_Config::$_module_view_map[ $key ][ $route ][ absint($status) ] = $view;
1425
+		return true;
1426
+	}
1427
+
1428
+
1429
+	/**
1430
+	 *    get_view - get view for route and status
1431
+	 *
1432
+	 * @access    public
1433
+	 * @param    string  $route  - "pretty" public alias for module method
1434
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1435
+	 *                           allows different views to be served based on status
1436
+	 * @param    string  $key    - url param key indicating a route is being called
1437
+	 * @return    string
1438
+	 */
1439
+	public static function get_view($route = null, $status = 0, $key = 'ee')
1440
+	{
1441
+		do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1442
+		if (isset(EE_Config::$_module_view_map[ $key ][ $route ][ $status ])) {
1443
+			return apply_filters(
1444
+				'FHEE__EE_Config__get_view',
1445
+				EE_Config::$_module_view_map[ $key ][ $route ][ $status ],
1446
+				$route,
1447
+				$status
1448
+			);
1449
+		}
1450
+		return null;
1451
+	}
1452
+
1453
+
1454
+	public function update_addon_option_names()
1455
+	{
1456
+		update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1457
+	}
1458
+
1459
+
1460
+	public function shutdown()
1461
+	{
1462
+		$this->update_addon_option_names();
1463
+	}
1464
+
1465
+
1466
+	/**
1467
+	 * @return LegacyShortcodesManager
1468
+	 */
1469
+	public static function getLegacyShortcodesManager()
1470
+	{
1471
+
1472
+		if (! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1473
+			EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1474
+				EE_Registry::instance()
1475
+			);
1476
+		}
1477
+		return EE_Config::instance()->legacy_shortcodes_manager;
1478
+	}
1479
+
1480
+
1481
+	/**
1482
+	 * register_shortcode - makes core aware of this shortcode
1483
+	 *
1484
+	 * @deprecated 4.9.26
1485
+	 * @param    string $shortcode_path - full path up to and including shortcode folder
1486
+	 * @return    bool
1487
+	 */
1488
+	public static function register_shortcode($shortcode_path = null)
1489
+	{
1490
+		EE_Error::doing_it_wrong(
1491
+			__METHOD__,
1492
+			__(
1493
+				'Usage is deprecated. Use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::registerShortcode() as direct replacement, or better yet, please see the new \EventEspresso\core\services\shortcodes\ShortcodesManager class.',
1494
+				'event_espresso'
1495
+			),
1496
+			'4.9.26'
1497
+		);
1498
+		return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1499
+	}
1500
+}
2262 1501
 
2263
-    /**
2264
-     * ReCaptcha Type
2265
-     *
2266
-     * @var string $recaptcha_type
2267
-     *    options: 'audio', 'image'
2268
-     */
2269
-    public $recaptcha_type;
1502
+/**
1503
+ * Base class used for config classes. These classes should generally not have
1504
+ * magic functions in use, except we'll allow them to magically set and get stuff...
1505
+ * basically, they should just be well-defined stdClasses
1506
+ */
1507
+class EE_Config_Base
1508
+{
2270 1509
 
2271
-    /**
2272
-     * ReCaptcha language
2273
-     *
2274
-     * @var string $recaptcha_language
2275
-     * eg 'en'
2276
-     */
2277
-    public $recaptcha_language;
1510
+	/**
1511
+	 * Utility function for escaping the value of a property and returning.
1512
+	 *
1513
+	 * @param string $property property name (checks to see if exists).
1514
+	 * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1515
+	 * @throws \EE_Error
1516
+	 */
1517
+	public function get_pretty($property)
1518
+	{
1519
+		if (! property_exists($this, $property)) {
1520
+			throw new EE_Error(
1521
+				sprintf(
1522
+					__(
1523
+						'%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1524
+						'event_espresso'
1525
+					),
1526
+					get_class($this),
1527
+					$property
1528
+				)
1529
+			);
1530
+		}
1531
+		// just handling escaping of strings for now.
1532
+		if (is_string($this->{$property})) {
1533
+			return stripslashes($this->{$property});
1534
+		}
1535
+		return $this->{$property};
1536
+	}
1537
+
1538
+
1539
+	public function populate()
1540
+	{
1541
+		// grab defaults via a new instance of this class.
1542
+		$class_name = get_class($this);
1543
+		$defaults = new $class_name;
1544
+		// loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1545
+		// default from our $defaults object.
1546
+		foreach (get_object_vars($defaults) as $property => $value) {
1547
+			if ($this->{$property} === null) {
1548
+				$this->{$property} = $value;
1549
+			}
1550
+		}
1551
+		// cleanup
1552
+		unset($defaults);
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 *        __isset
1558
+	 *
1559
+	 * @param $a
1560
+	 * @return bool
1561
+	 */
1562
+	public function __isset($a)
1563
+	{
1564
+		return false;
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 *        __unset
1570
+	 *
1571
+	 * @param $a
1572
+	 * @return bool
1573
+	 */
1574
+	public function __unset($a)
1575
+	{
1576
+		return false;
1577
+	}
1578
+
1579
+
1580
+	/**
1581
+	 *        __clone
1582
+	 */
1583
+	public function __clone()
1584
+	{
1585
+	}
1586
+
1587
+
1588
+	/**
1589
+	 *        __wakeup
1590
+	 */
1591
+	public function __wakeup()
1592
+	{
1593
+	}
1594
+
1595
+
1596
+	/**
1597
+	 *        __destruct
1598
+	 */
1599
+	public function __destruct()
1600
+	{
1601
+	}
1602
+}
2278 1603
 
2279
-    /**
2280
-     * ReCaptcha public key
2281
-     *
2282
-     * @var string $recaptcha_publickey
2283
-     */
2284
-    public $recaptcha_publickey;
1604
+/**
1605
+ * Class for defining what's in the EE_Config relating to registration settings
1606
+ */
1607
+class EE_Core_Config extends EE_Config_Base
1608
+{
2285 1609
 
2286
-    /**
2287
-     * ReCaptcha private key
2288
-     *
2289
-     * @var string $recaptcha_privatekey
2290
-     */
2291
-    public $recaptcha_privatekey;
1610
+	const OPTION_NAME_UXIP = 'ee_ueip_optin';
1611
+
1612
+
1613
+	public $current_blog_id;
1614
+
1615
+	public $ee_ueip_optin;
1616
+
1617
+	public $ee_ueip_has_notified;
1618
+
1619
+	/**
1620
+	 * Not to be confused with the 4 critical page variables (See
1621
+	 * get_critical_pages_array()), this is just an array of wp posts that have EE
1622
+	 * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1623
+	 * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1624
+	 *
1625
+	 * @var array
1626
+	 */
1627
+	public $post_shortcodes;
1628
+
1629
+	public $module_route_map;
1630
+
1631
+	public $module_forward_map;
1632
+
1633
+	public $module_view_map;
1634
+
1635
+	/**
1636
+	 * The next 4 vars are the IDs of critical EE pages.
1637
+	 *
1638
+	 * @var int
1639
+	 */
1640
+	public $reg_page_id;
1641
+
1642
+	public $txn_page_id;
1643
+
1644
+	public $thank_you_page_id;
1645
+
1646
+	public $cancel_page_id;
1647
+
1648
+	/**
1649
+	 * The next 4 vars are the URLs of critical EE pages.
1650
+	 *
1651
+	 * @var int
1652
+	 */
1653
+	public $reg_page_url;
1654
+
1655
+	public $txn_page_url;
1656
+
1657
+	public $thank_you_page_url;
1658
+
1659
+	public $cancel_page_url;
1660
+
1661
+	/**
1662
+	 * The next vars relate to the custom slugs for EE CPT routes
1663
+	 */
1664
+	public $event_cpt_slug;
1665
+
1666
+	/**
1667
+	 * This caches the _ee_ueip_option in case this config is reset in the same
1668
+	 * request across blog switches in a multisite context.
1669
+	 * Avoids extra queries to the db for this option.
1670
+	 *
1671
+	 * @var bool
1672
+	 */
1673
+	public static $ee_ueip_option;
1674
+
1675
+
1676
+	/**
1677
+	 *    class constructor
1678
+	 *
1679
+	 * @access    public
1680
+	 */
1681
+	public function __construct()
1682
+	{
1683
+		// set default organization settings
1684
+		$this->current_blog_id = get_current_blog_id();
1685
+		$this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1686
+		$this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1687
+		$this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1688
+		$this->post_shortcodes = array();
1689
+		$this->module_route_map = array();
1690
+		$this->module_forward_map = array();
1691
+		$this->module_view_map = array();
1692
+		// critical EE page IDs
1693
+		$this->reg_page_id = 0;
1694
+		$this->txn_page_id = 0;
1695
+		$this->thank_you_page_id = 0;
1696
+		$this->cancel_page_id = 0;
1697
+		// critical EE page URLs
1698
+		$this->reg_page_url = '';
1699
+		$this->txn_page_url = '';
1700
+		$this->thank_you_page_url = '';
1701
+		$this->cancel_page_url = '';
1702
+		// cpt slugs
1703
+		$this->event_cpt_slug = __('events', 'event_espresso');
1704
+		// ueip constant check
1705
+		if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1706
+			$this->ee_ueip_optin = false;
1707
+			$this->ee_ueip_has_notified = true;
1708
+		}
1709
+	}
1710
+
1711
+
1712
+	/**
1713
+	 * @return array
1714
+	 */
1715
+	public function get_critical_pages_array()
1716
+	{
1717
+		return array(
1718
+			$this->reg_page_id,
1719
+			$this->txn_page_id,
1720
+			$this->thank_you_page_id,
1721
+			$this->cancel_page_id,
1722
+		);
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * @return array
1728
+	 */
1729
+	public function get_critical_pages_shortcodes_array()
1730
+	{
1731
+		return array(
1732
+			$this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1733
+			$this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1734
+			$this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1735
+			$this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1736
+		);
1737
+	}
1738
+
1739
+
1740
+	/**
1741
+	 *  gets/returns URL for EE reg_page
1742
+	 *
1743
+	 * @access    public
1744
+	 * @return    string
1745
+	 */
1746
+	public function reg_page_url()
1747
+	{
1748
+		if (! $this->reg_page_url) {
1749
+			$this->reg_page_url = add_query_arg(
1750
+				array('uts' => time()),
1751
+				get_permalink($this->reg_page_id)
1752
+			) . '#checkout';
1753
+		}
1754
+		return $this->reg_page_url;
1755
+	}
1756
+
1757
+
1758
+	/**
1759
+	 *  gets/returns URL for EE txn_page
1760
+	 *
1761
+	 * @param array $query_args like what gets passed to
1762
+	 *                          add_query_arg() as the first argument
1763
+	 * @access    public
1764
+	 * @return    string
1765
+	 */
1766
+	public function txn_page_url($query_args = array())
1767
+	{
1768
+		if (! $this->txn_page_url) {
1769
+			$this->txn_page_url = get_permalink($this->txn_page_id);
1770
+		}
1771
+		if ($query_args) {
1772
+			return add_query_arg($query_args, $this->txn_page_url);
1773
+		} else {
1774
+			return $this->txn_page_url;
1775
+		}
1776
+	}
1777
+
1778
+
1779
+	/**
1780
+	 *  gets/returns URL for EE thank_you_page
1781
+	 *
1782
+	 * @param array $query_args like what gets passed to
1783
+	 *                          add_query_arg() as the first argument
1784
+	 * @access    public
1785
+	 * @return    string
1786
+	 */
1787
+	public function thank_you_page_url($query_args = array())
1788
+	{
1789
+		if (! $this->thank_you_page_url) {
1790
+			$this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1791
+		}
1792
+		if ($query_args) {
1793
+			return add_query_arg($query_args, $this->thank_you_page_url);
1794
+		} else {
1795
+			return $this->thank_you_page_url;
1796
+		}
1797
+	}
1798
+
1799
+
1800
+	/**
1801
+	 *  gets/returns URL for EE cancel_page
1802
+	 *
1803
+	 * @access    public
1804
+	 * @return    string
1805
+	 */
1806
+	public function cancel_page_url()
1807
+	{
1808
+		if (! $this->cancel_page_url) {
1809
+			$this->cancel_page_url = get_permalink($this->cancel_page_id);
1810
+		}
1811
+		return $this->cancel_page_url;
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1817
+	 *
1818
+	 * @since 4.7.5
1819
+	 */
1820
+	protected function _reset_urls()
1821
+	{
1822
+		$this->reg_page_url = '';
1823
+		$this->txn_page_url = '';
1824
+		$this->cancel_page_url = '';
1825
+		$this->thank_you_page_url = '';
1826
+	}
1827
+
1828
+
1829
+	/**
1830
+	 * Used to return what the optin value is set for the EE User Experience Program.
1831
+	 * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1832
+	 * on the main site only.
1833
+	 *
1834
+	 * @return bool
1835
+	 */
1836
+	protected function _get_main_ee_ueip_optin()
1837
+	{
1838
+		// if this is the main site then we can just bypass our direct query.
1839
+		if (is_main_site()) {
1840
+			return get_option(self::OPTION_NAME_UXIP, false);
1841
+		}
1842
+		// is this already cached for this request?  If so use it.
1843
+		if (EE_Core_Config::$ee_ueip_option !== null) {
1844
+			return EE_Core_Config::$ee_ueip_option;
1845
+		}
1846
+		global $wpdb;
1847
+		$current_network_main_site = is_multisite() ? get_current_site() : null;
1848
+		$current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1849
+		$option = self::OPTION_NAME_UXIP;
1850
+		// set correct table for query
1851
+		$table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1852
+		// rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1853
+		// get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1854
+		// re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1855
+		// this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1856
+		// for the purpose of caching.
1857
+		$pre = apply_filters('pre_option_' . $option, false, $option);
1858
+		if (false !== $pre) {
1859
+			EE_Core_Config::$ee_ueip_option = $pre;
1860
+			return EE_Core_Config::$ee_ueip_option;
1861
+		}
1862
+		$row = $wpdb->get_row(
1863
+			$wpdb->prepare(
1864
+				"SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1865
+				$option
1866
+			)
1867
+		);
1868
+		if (is_object($row)) {
1869
+			$value = $row->option_value;
1870
+		} else { // option does not exist so use default.
1871
+			EE_Core_Config::$ee_ueip_option =  apply_filters('default_option_' . $option, false, $option);
1872
+			return EE_Core_Config::$ee_ueip_option;
1873
+		}
1874
+		EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1875
+		return EE_Core_Config::$ee_ueip_option;
1876
+	}
1877
+
1878
+
1879
+	/**
1880
+	 * Utility function for escaping the value of a property and returning.
1881
+	 *
1882
+	 * @param string $property property name (checks to see if exists).
1883
+	 * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1884
+	 * @throws \EE_Error
1885
+	 */
1886
+	public function get_pretty($property)
1887
+	{
1888
+		if ($property === self::OPTION_NAME_UXIP) {
1889
+			return $this->ee_ueip_optin ? 'yes' : 'no';
1890
+		}
1891
+		return parent::get_pretty($property);
1892
+	}
1893
+
1894
+
1895
+	/**
1896
+	 * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1897
+	 * on the object.
1898
+	 *
1899
+	 * @return array
1900
+	 */
1901
+	public function __sleep()
1902
+	{
1903
+		// reset all url properties
1904
+		$this->_reset_urls();
1905
+		// return what to save to db
1906
+		return array_keys(get_object_vars($this));
1907
+	}
1908
+}
2292 1909
 
2293
-    /**
2294
-     * array of form names protected by ReCaptcha
2295
-     *
2296
-     * @var array $recaptcha_protected_forms
2297
-     */
2298
-    public $recaptcha_protected_forms;
1910
+/**
1911
+ * Config class for storing info on the Organization
1912
+ */
1913
+class EE_Organization_Config extends EE_Config_Base
1914
+{
2299 1915
 
2300
-    /**
2301
-     * ReCaptcha width
2302
-     *
2303
-     * @var int $recaptcha_width
2304
-     * @deprecated
2305
-     */
2306
-    public $recaptcha_width;
1916
+	/**
1917
+	 * @var string $name
1918
+	 * eg EE4.1
1919
+	 */
1920
+	public $name;
1921
+
1922
+	/**
1923
+	 * @var string $address_1
1924
+	 * eg 123 Onna Road
1925
+	 */
1926
+	public $address_1 = '';
1927
+
1928
+	/**
1929
+	 * @var string $address_2
1930
+	 * eg PO Box 123
1931
+	 */
1932
+	public $address_2 = '';
1933
+
1934
+	/**
1935
+	 * @var string $city
1936
+	 * eg Inna City
1937
+	 */
1938
+	public $city = '';
1939
+
1940
+	/**
1941
+	 * @var int $STA_ID
1942
+	 * eg 4
1943
+	 */
1944
+	public $STA_ID = 0;
1945
+
1946
+	/**
1947
+	 * @var string $CNT_ISO
1948
+	 * eg US
1949
+	 */
1950
+	public $CNT_ISO = '';
1951
+
1952
+	/**
1953
+	 * @var string $zip
1954
+	 * eg 12345  or V1A 2B3
1955
+	 */
1956
+	public $zip = '';
1957
+
1958
+	/**
1959
+	 * @var string $email
1960
+	 * eg [email protected]
1961
+	 */
1962
+	public $email;
1963
+
1964
+	/**
1965
+	 * @var string $phone
1966
+	 * eg. 111-111-1111
1967
+	 */
1968
+	public $phone = '';
1969
+
1970
+	/**
1971
+	 * @var string $vat
1972
+	 * VAT/Tax Number
1973
+	 */
1974
+	public $vat = '';
1975
+
1976
+	/**
1977
+	 * @var string $logo_url
1978
+	 * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
1979
+	 */
1980
+	public $logo_url = '';
1981
+
1982
+	/**
1983
+	 * The below are all various properties for holding links to organization social network profiles
1984
+	 *
1985
+	 * @var string
1986
+	 */
1987
+	/**
1988
+	 * facebook (facebook.com/profile.name)
1989
+	 *
1990
+	 * @var string
1991
+	 */
1992
+	public $facebook = '';
1993
+
1994
+	/**
1995
+	 * twitter (twitter.com/twitter_handle)
1996
+	 *
1997
+	 * @var string
1998
+	 */
1999
+	public $twitter = '';
2000
+
2001
+	/**
2002
+	 * linkedin (linkedin.com/in/profile_name)
2003
+	 *
2004
+	 * @var string
2005
+	 */
2006
+	public $linkedin = '';
2007
+
2008
+	/**
2009
+	 * pinterest (www.pinterest.com/profile_name)
2010
+	 *
2011
+	 * @var string
2012
+	 */
2013
+	public $pinterest = '';
2014
+
2015
+	/**
2016
+	 * google+ (google.com/+profileName)
2017
+	 *
2018
+	 * @var string
2019
+	 */
2020
+	public $google = '';
2021
+
2022
+	/**
2023
+	 * instagram (instagram.com/handle)
2024
+	 *
2025
+	 * @var string
2026
+	 */
2027
+	public $instagram = '';
2028
+
2029
+
2030
+	/**
2031
+	 *    class constructor
2032
+	 *
2033
+	 * @access    public
2034
+	 */
2035
+	public function __construct()
2036
+	{
2037
+		// set default organization settings
2038
+		// decode HTML entities from the WP blogname, because it's stored in the DB with HTML entities encoded
2039
+		$this->name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
2040
+		$this->email = get_bloginfo('admin_email');
2041
+	}
2042
+}
2307 2043
 
2308
-    /**
2309
-     * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2310
-     *
2311
-     * @var boolean $track_invalid_checkout_access
2312
-     */
2313
-    protected $track_invalid_checkout_access = true;
2044
+/**
2045
+ * Class for defining what's in the EE_Config relating to currency
2046
+ */
2047
+class EE_Currency_Config extends EE_Config_Base
2048
+{
2314 2049
 
2315
-    /**
2316
-     * Whether or not to show the privacy policy consent checkbox
2317
-     *
2318
-     * @var bool
2319
-     */
2320
-    public $consent_checkbox_enabled;
2050
+	/**
2051
+	 * @var string $code
2052
+	 * eg 'US'
2053
+	 */
2054
+	public $code;
2055
+
2056
+	/**
2057
+	 * @var string $name
2058
+	 * eg 'Dollar'
2059
+	 */
2060
+	public $name;
2061
+
2062
+	/**
2063
+	 * plural name
2064
+	 *
2065
+	 * @var string $plural
2066
+	 * eg 'Dollars'
2067
+	 */
2068
+	public $plural;
2069
+
2070
+	/**
2071
+	 * currency sign
2072
+	 *
2073
+	 * @var string $sign
2074
+	 * eg '$'
2075
+	 */
2076
+	public $sign;
2077
+
2078
+	/**
2079
+	 * Whether the currency sign should come before the number or not
2080
+	 *
2081
+	 * @var boolean $sign_b4
2082
+	 */
2083
+	public $sign_b4;
2084
+
2085
+	/**
2086
+	 * How many digits should come after the decimal place
2087
+	 *
2088
+	 * @var int $dec_plc
2089
+	 */
2090
+	public $dec_plc;
2091
+
2092
+	/**
2093
+	 * Symbol to use for decimal mark
2094
+	 *
2095
+	 * @var string $dec_mrk
2096
+	 * eg '.'
2097
+	 */
2098
+	public $dec_mrk;
2099
+
2100
+	/**
2101
+	 * Symbol to use for thousands
2102
+	 *
2103
+	 * @var string $thsnds
2104
+	 * eg ','
2105
+	 */
2106
+	public $thsnds;
2107
+
2108
+
2109
+	/**
2110
+	 *    class constructor
2111
+	 *
2112
+	 * @access    public
2113
+	 * @param string $CNT_ISO
2114
+	 * @throws \EE_Error
2115
+	 */
2116
+	public function __construct($CNT_ISO = '')
2117
+	{
2118
+		/** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2119
+		$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2120
+		// get country code from organization settings or use default
2121
+		$ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2122
+				   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2123
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
2124
+			: '';
2125
+		// but override if requested
2126
+		$CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2127
+		// so if that all went well, and we are not in M-Mode (cuz you can't query the db in M-Mode) and double-check the countries table exists
2128
+		if (! empty($CNT_ISO)
2129
+			&& EE_Maintenance_Mode::instance()->models_can_query()
2130
+			&& $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2131
+		) {
2132
+			// retrieve the country settings from the db, just in case they have been customized
2133
+			$country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2134
+			if ($country instanceof EE_Country) {
2135
+				$this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2136
+				$this->name = $country->currency_name_single();    // Dollar
2137
+				$this->plural = $country->currency_name_plural();    // Dollars
2138
+				$this->sign = $country->currency_sign();            // currency sign: $
2139
+				$this->sign_b4 = $country->currency_sign_before(
2140
+				);        // currency sign before or after: $TRUE  or  FALSE$
2141
+				$this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2142
+				$this->dec_mrk = $country->currency_decimal_mark(
2143
+				);    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2144
+				$this->thsnds = $country->currency_thousands_separator(
2145
+				);    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2146
+			}
2147
+		}
2148
+		// fallback to hardcoded defaults, in case the above failed
2149
+		if (empty($this->code)) {
2150
+			// set default currency settings
2151
+			$this->code = 'USD';    // currency code: USD, CAD, EUR
2152
+			$this->name = __('Dollar', 'event_espresso');    // Dollar
2153
+			$this->plural = __('Dollars', 'event_espresso');    // Dollars
2154
+			$this->sign = '$';    // currency sign: $
2155
+			$this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2156
+			$this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2157
+			$this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2158
+			$this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2159
+		}
2160
+	}
2161
+}
2321 2162
 
2322
-    /**
2323
-     * Label text to show on the checkbox
2324
-     *
2325
-     * @var string
2326
-     */
2327
-    public $consent_checkbox_label_text;
2163
+/**
2164
+ * Class for defining what's in the EE_Config relating to registration settings
2165
+ */
2166
+class EE_Registration_Config extends EE_Config_Base
2167
+{
2328 2168
 
2329
-    /*
2169
+	/**
2170
+	 * Default registration status
2171
+	 *
2172
+	 * @var string $default_STS_ID
2173
+	 * eg 'RPP'
2174
+	 */
2175
+	public $default_STS_ID;
2176
+
2177
+	/**
2178
+	 * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2179
+	 * registrations)
2180
+	 *
2181
+	 * @var int
2182
+	 */
2183
+	public $default_maximum_number_of_tickets;
2184
+
2185
+	/**
2186
+	 * level of validation to apply to email addresses
2187
+	 *
2188
+	 * @var string $email_validation_level
2189
+	 * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2190
+	 */
2191
+	public $email_validation_level;
2192
+
2193
+	/**
2194
+	 *    whether or not to show alternate payment options during the reg process if payment status is pending
2195
+	 *
2196
+	 * @var boolean $show_pending_payment_options
2197
+	 */
2198
+	public $show_pending_payment_options;
2199
+
2200
+	/**
2201
+	 * Whether to skip the registration confirmation page
2202
+	 *
2203
+	 * @var boolean $skip_reg_confirmation
2204
+	 */
2205
+	public $skip_reg_confirmation;
2206
+
2207
+	/**
2208
+	 * an array of SPCO reg steps where:
2209
+	 *        the keys denotes the reg step order
2210
+	 *        each element consists of an array with the following elements:
2211
+	 *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2212
+	 *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2213
+	 *            "slug" => the URL param used to trigger the reg step
2214
+	 *
2215
+	 * @var array $reg_steps
2216
+	 */
2217
+	public $reg_steps;
2218
+
2219
+	/**
2220
+	 * Whether registration confirmation should be the last page of SPCO
2221
+	 *
2222
+	 * @var boolean $reg_confirmation_last
2223
+	 */
2224
+	public $reg_confirmation_last;
2225
+
2226
+	/**
2227
+	 * Whether or not to enable the EE Bot Trap
2228
+	 *
2229
+	 * @var boolean $use_bot_trap
2230
+	 */
2231
+	public $use_bot_trap;
2232
+
2233
+	/**
2234
+	 * Whether or not to encrypt some data sent by the EE Bot Trap
2235
+	 *
2236
+	 * @var boolean $use_encryption
2237
+	 */
2238
+	public $use_encryption;
2239
+
2240
+	/**
2241
+	 * Whether or not to use ReCaptcha
2242
+	 *
2243
+	 * @var boolean $use_captcha
2244
+	 */
2245
+	public $use_captcha;
2246
+
2247
+	/**
2248
+	 * ReCaptcha Theme
2249
+	 *
2250
+	 * @var string $recaptcha_theme
2251
+	 *    options: 'dark', 'light', 'invisible'
2252
+	 */
2253
+	public $recaptcha_theme;
2254
+
2255
+	/**
2256
+	 * ReCaptcha Badge - determines the position of the reCAPTCHA badge if using Invisible ReCaptcha.
2257
+	 *
2258
+	 * @var string $recaptcha_badge
2259
+	 *    options: 'bottomright', 'bottomleft', 'inline'
2260
+	 */
2261
+	public $recaptcha_badge;
2262
+
2263
+	/**
2264
+	 * ReCaptcha Type
2265
+	 *
2266
+	 * @var string $recaptcha_type
2267
+	 *    options: 'audio', 'image'
2268
+	 */
2269
+	public $recaptcha_type;
2270
+
2271
+	/**
2272
+	 * ReCaptcha language
2273
+	 *
2274
+	 * @var string $recaptcha_language
2275
+	 * eg 'en'
2276
+	 */
2277
+	public $recaptcha_language;
2278
+
2279
+	/**
2280
+	 * ReCaptcha public key
2281
+	 *
2282
+	 * @var string $recaptcha_publickey
2283
+	 */
2284
+	public $recaptcha_publickey;
2285
+
2286
+	/**
2287
+	 * ReCaptcha private key
2288
+	 *
2289
+	 * @var string $recaptcha_privatekey
2290
+	 */
2291
+	public $recaptcha_privatekey;
2292
+
2293
+	/**
2294
+	 * array of form names protected by ReCaptcha
2295
+	 *
2296
+	 * @var array $recaptcha_protected_forms
2297
+	 */
2298
+	public $recaptcha_protected_forms;
2299
+
2300
+	/**
2301
+	 * ReCaptcha width
2302
+	 *
2303
+	 * @var int $recaptcha_width
2304
+	 * @deprecated
2305
+	 */
2306
+	public $recaptcha_width;
2307
+
2308
+	/**
2309
+	 * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2310
+	 *
2311
+	 * @var boolean $track_invalid_checkout_access
2312
+	 */
2313
+	protected $track_invalid_checkout_access = true;
2314
+
2315
+	/**
2316
+	 * Whether or not to show the privacy policy consent checkbox
2317
+	 *
2318
+	 * @var bool
2319
+	 */
2320
+	public $consent_checkbox_enabled;
2321
+
2322
+	/**
2323
+	 * Label text to show on the checkbox
2324
+	 *
2325
+	 * @var string
2326
+	 */
2327
+	public $consent_checkbox_label_text;
2328
+
2329
+	/*
2330 2330
      * String describing how long to keep payment logs. Passed into DateTime constructor
2331 2331
      * @var string
2332 2332
      */
2333
-    public $gateway_log_lifespan = '1 week';
2334
-
2335
-
2336
-    /**
2337
-     *    class constructor
2338
-     *
2339
-     * @access    public
2340
-     */
2341
-    public function __construct()
2342
-    {
2343
-        // set default registration settings
2344
-        $this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2345
-        $this->email_validation_level = 'wp_default';
2346
-        $this->show_pending_payment_options = true;
2347
-        $this->skip_reg_confirmation = true;
2348
-        $this->reg_steps = array();
2349
-        $this->reg_confirmation_last = false;
2350
-        $this->use_bot_trap = true;
2351
-        $this->use_encryption = true;
2352
-        $this->use_captcha = false;
2353
-        $this->recaptcha_theme = 'light';
2354
-        $this->recaptcha_badge = 'bottomleft';
2355
-        $this->recaptcha_type = 'image';
2356
-        $this->recaptcha_language = 'en';
2357
-        $this->recaptcha_publickey = null;
2358
-        $this->recaptcha_privatekey = null;
2359
-        $this->recaptcha_protected_forms = array();
2360
-        $this->recaptcha_width = 500;
2361
-        $this->default_maximum_number_of_tickets = 10;
2362
-        $this->consent_checkbox_enabled = false;
2363
-        $this->consent_checkbox_label_text = '';
2364
-        $this->gateway_log_lifespan = '7 days';
2365
-    }
2366
-
2367
-
2368
-    /**
2369
-     * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2370
-     *
2371
-     * @since 4.8.8.rc.019
2372
-     */
2373
-    public function do_hooks()
2374
-    {
2375
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2376
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2377
-        add_action('setup_theme', array($this, 'setDefaultCheckboxLabelText'));
2378
-    }
2379
-
2380
-
2381
-    /**
2382
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the
2383
-     * EVT_default_registration_status field matches the config setting for default_STS_ID.
2384
-     */
2385
-    public function set_default_reg_status_on_EEM_Event()
2386
-    {
2387
-        EEM_Event::set_default_reg_status($this->default_STS_ID);
2388
-    }
2389
-
2390
-
2391
-    /**
2392
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2393
-     * for Events matches the config setting for default_maximum_number_of_tickets
2394
-     */
2395
-    public function set_default_max_ticket_on_EEM_Event()
2396
-    {
2397
-        EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2398
-    }
2399
-
2400
-
2401
-    /**
2402
-     * Sets the default consent checkbox text. This needs to be done a bit later than when EE_Registration_Config is
2403
-     * constructed because that happens before we can get the privacy policy page's permalink.
2404
-     *
2405
-     * @throws InvalidArgumentException
2406
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2407
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2408
-     */
2409
-    public function setDefaultCheckboxLabelText()
2410
-    {
2411
-        if ($this->getConsentCheckboxLabelText() === null
2412
-            || $this->getConsentCheckboxLabelText() === '') {
2413
-            $opening_a_tag = '';
2414
-            $closing_a_tag = '';
2415
-            if (function_exists('get_privacy_policy_url')) {
2416
-                $privacy_page_url = get_privacy_policy_url();
2417
-                if (! empty($privacy_page_url)) {
2418
-                    $opening_a_tag = '<a href="' . $privacy_page_url . '" target="_blank">';
2419
-                    $closing_a_tag = '</a>';
2420
-                }
2421
-            }
2422
-            $loader = LoaderFactory::getLoader();
2423
-            $org_config = $loader->getShared('EE_Organization_Config');
2424
-            /**
2425
-             * @var $org_config EE_Organization_Config
2426
-             */
2427
-
2428
-            $this->setConsentCheckboxLabelText(
2429
-                sprintf(
2430
-                    esc_html__(
2431
-                        'I consent to %1$s storing and using my personal information, according to their %2$sprivacy policy%3$s.',
2432
-                        'event_espresso'
2433
-                    ),
2434
-                    $org_config->name,
2435
-                    $opening_a_tag,
2436
-                    $closing_a_tag
2437
-                )
2438
-            );
2439
-        }
2440
-    }
2441
-
2442
-
2443
-    /**
2444
-     * @return boolean
2445
-     */
2446
-    public function track_invalid_checkout_access()
2447
-    {
2448
-        return $this->track_invalid_checkout_access;
2449
-    }
2450
-
2451
-
2452
-    /**
2453
-     * @param boolean $track_invalid_checkout_access
2454
-     */
2455
-    public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2456
-    {
2457
-        $this->track_invalid_checkout_access = filter_var(
2458
-            $track_invalid_checkout_access,
2459
-            FILTER_VALIDATE_BOOLEAN
2460
-        );
2461
-    }
2462
-
2463
-
2464
-    /**
2465
-     * Gets the options to make availalbe for the gateway log lifespan
2466
-     * @return array
2467
-     */
2468
-    public function gatewayLogLifespanOptions()
2469
-    {
2470
-        return (array) apply_filters(
2471
-            'FHEE_EE_Admin_Config__gatewayLogLifespanOptions',
2472
-            array(
2473
-                '1 second' => esc_html__('Don\'t Log At All', 'event_espresso'),
2474
-                '1 day' => esc_html__('1 Day', 'event_espresso'),
2475
-                '7 days' => esc_html__('7 Days', 'event_espresso'),
2476
-                '14 days' => esc_html__('14 Days', 'event_espresso'),
2477
-                '30 days' => esc_html__('30 Days', 'event_espresso')
2478
-            )
2479
-        );
2480
-    }
2481
-
2482
-
2483
-    /**
2484
-     * @return bool
2485
-     */
2486
-    public function isConsentCheckboxEnabled()
2487
-    {
2488
-        return $this->consent_checkbox_enabled;
2489
-    }
2490
-
2491
-
2492
-    /**
2493
-     * @param bool $consent_checkbox_enabled
2494
-     */
2495
-    public function setConsentCheckboxEnabled($consent_checkbox_enabled)
2496
-    {
2497
-        $this->consent_checkbox_enabled = filter_var(
2498
-            $consent_checkbox_enabled,
2499
-            FILTER_VALIDATE_BOOLEAN
2500
-        );
2501
-    }
2502
-
2503
-
2504
-    /**
2505
-     * @return string
2506
-     */
2507
-    public function getConsentCheckboxLabelText()
2508
-    {
2509
-        return $this->consent_checkbox_label_text;
2510
-    }
2511
-
2512
-
2513
-    /**
2514
-     * @param string $consent_checkbox_label_text
2515
-     */
2516
-    public function setConsentCheckboxLabelText($consent_checkbox_label_text)
2517
-    {
2518
-        $this->consent_checkbox_label_text = (string) $consent_checkbox_label_text;
2519
-    }
2333
+	public $gateway_log_lifespan = '1 week';
2334
+
2335
+
2336
+	/**
2337
+	 *    class constructor
2338
+	 *
2339
+	 * @access    public
2340
+	 */
2341
+	public function __construct()
2342
+	{
2343
+		// set default registration settings
2344
+		$this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2345
+		$this->email_validation_level = 'wp_default';
2346
+		$this->show_pending_payment_options = true;
2347
+		$this->skip_reg_confirmation = true;
2348
+		$this->reg_steps = array();
2349
+		$this->reg_confirmation_last = false;
2350
+		$this->use_bot_trap = true;
2351
+		$this->use_encryption = true;
2352
+		$this->use_captcha = false;
2353
+		$this->recaptcha_theme = 'light';
2354
+		$this->recaptcha_badge = 'bottomleft';
2355
+		$this->recaptcha_type = 'image';
2356
+		$this->recaptcha_language = 'en';
2357
+		$this->recaptcha_publickey = null;
2358
+		$this->recaptcha_privatekey = null;
2359
+		$this->recaptcha_protected_forms = array();
2360
+		$this->recaptcha_width = 500;
2361
+		$this->default_maximum_number_of_tickets = 10;
2362
+		$this->consent_checkbox_enabled = false;
2363
+		$this->consent_checkbox_label_text = '';
2364
+		$this->gateway_log_lifespan = '7 days';
2365
+	}
2366
+
2367
+
2368
+	/**
2369
+	 * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2370
+	 *
2371
+	 * @since 4.8.8.rc.019
2372
+	 */
2373
+	public function do_hooks()
2374
+	{
2375
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2376
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2377
+		add_action('setup_theme', array($this, 'setDefaultCheckboxLabelText'));
2378
+	}
2379
+
2380
+
2381
+	/**
2382
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the
2383
+	 * EVT_default_registration_status field matches the config setting for default_STS_ID.
2384
+	 */
2385
+	public function set_default_reg_status_on_EEM_Event()
2386
+	{
2387
+		EEM_Event::set_default_reg_status($this->default_STS_ID);
2388
+	}
2389
+
2390
+
2391
+	/**
2392
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2393
+	 * for Events matches the config setting for default_maximum_number_of_tickets
2394
+	 */
2395
+	public function set_default_max_ticket_on_EEM_Event()
2396
+	{
2397
+		EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2398
+	}
2399
+
2400
+
2401
+	/**
2402
+	 * Sets the default consent checkbox text. This needs to be done a bit later than when EE_Registration_Config is
2403
+	 * constructed because that happens before we can get the privacy policy page's permalink.
2404
+	 *
2405
+	 * @throws InvalidArgumentException
2406
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2407
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2408
+	 */
2409
+	public function setDefaultCheckboxLabelText()
2410
+	{
2411
+		if ($this->getConsentCheckboxLabelText() === null
2412
+			|| $this->getConsentCheckboxLabelText() === '') {
2413
+			$opening_a_tag = '';
2414
+			$closing_a_tag = '';
2415
+			if (function_exists('get_privacy_policy_url')) {
2416
+				$privacy_page_url = get_privacy_policy_url();
2417
+				if (! empty($privacy_page_url)) {
2418
+					$opening_a_tag = '<a href="' . $privacy_page_url . '" target="_blank">';
2419
+					$closing_a_tag = '</a>';
2420
+				}
2421
+			}
2422
+			$loader = LoaderFactory::getLoader();
2423
+			$org_config = $loader->getShared('EE_Organization_Config');
2424
+			/**
2425
+			 * @var $org_config EE_Organization_Config
2426
+			 */
2427
+
2428
+			$this->setConsentCheckboxLabelText(
2429
+				sprintf(
2430
+					esc_html__(
2431
+						'I consent to %1$s storing and using my personal information, according to their %2$sprivacy policy%3$s.',
2432
+						'event_espresso'
2433
+					),
2434
+					$org_config->name,
2435
+					$opening_a_tag,
2436
+					$closing_a_tag
2437
+				)
2438
+			);
2439
+		}
2440
+	}
2441
+
2442
+
2443
+	/**
2444
+	 * @return boolean
2445
+	 */
2446
+	public function track_invalid_checkout_access()
2447
+	{
2448
+		return $this->track_invalid_checkout_access;
2449
+	}
2450
+
2451
+
2452
+	/**
2453
+	 * @param boolean $track_invalid_checkout_access
2454
+	 */
2455
+	public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2456
+	{
2457
+		$this->track_invalid_checkout_access = filter_var(
2458
+			$track_invalid_checkout_access,
2459
+			FILTER_VALIDATE_BOOLEAN
2460
+		);
2461
+	}
2462
+
2463
+
2464
+	/**
2465
+	 * Gets the options to make availalbe for the gateway log lifespan
2466
+	 * @return array
2467
+	 */
2468
+	public function gatewayLogLifespanOptions()
2469
+	{
2470
+		return (array) apply_filters(
2471
+			'FHEE_EE_Admin_Config__gatewayLogLifespanOptions',
2472
+			array(
2473
+				'1 second' => esc_html__('Don\'t Log At All', 'event_espresso'),
2474
+				'1 day' => esc_html__('1 Day', 'event_espresso'),
2475
+				'7 days' => esc_html__('7 Days', 'event_espresso'),
2476
+				'14 days' => esc_html__('14 Days', 'event_espresso'),
2477
+				'30 days' => esc_html__('30 Days', 'event_espresso')
2478
+			)
2479
+		);
2480
+	}
2481
+
2482
+
2483
+	/**
2484
+	 * @return bool
2485
+	 */
2486
+	public function isConsentCheckboxEnabled()
2487
+	{
2488
+		return $this->consent_checkbox_enabled;
2489
+	}
2490
+
2491
+
2492
+	/**
2493
+	 * @param bool $consent_checkbox_enabled
2494
+	 */
2495
+	public function setConsentCheckboxEnabled($consent_checkbox_enabled)
2496
+	{
2497
+		$this->consent_checkbox_enabled = filter_var(
2498
+			$consent_checkbox_enabled,
2499
+			FILTER_VALIDATE_BOOLEAN
2500
+		);
2501
+	}
2502
+
2503
+
2504
+	/**
2505
+	 * @return string
2506
+	 */
2507
+	public function getConsentCheckboxLabelText()
2508
+	{
2509
+		return $this->consent_checkbox_label_text;
2510
+	}
2511
+
2512
+
2513
+	/**
2514
+	 * @param string $consent_checkbox_label_text
2515
+	 */
2516
+	public function setConsentCheckboxLabelText($consent_checkbox_label_text)
2517
+	{
2518
+		$this->consent_checkbox_label_text = (string) $consent_checkbox_label_text;
2519
+	}
2520 2520
 }
2521 2521
 
2522 2522
 /**
@@ -2525,154 +2525,154 @@  discard block
 block discarded – undo
2525 2525
 class EE_Admin_Config extends EE_Config_Base
2526 2526
 {
2527 2527
 
2528
-    /**
2529
-     * @var boolean $use_personnel_manager
2530
-     */
2531
-    public $use_personnel_manager;
2532
-
2533
-    /**
2534
-     * @var boolean $use_dashboard_widget
2535
-     */
2536
-    public $use_dashboard_widget;
2537
-
2538
-    /**
2539
-     * @var int $events_in_dashboard
2540
-     */
2541
-    public $events_in_dashboard;
2542
-
2543
-    /**
2544
-     * @var boolean $use_event_timezones
2545
-     */
2546
-    public $use_event_timezones;
2547
-
2548
-    /**
2549
-     * @var boolean $use_full_logging
2550
-     */
2551
-    public $use_full_logging;
2552
-
2553
-    /**
2554
-     * @var string $log_file_name
2555
-     */
2556
-    public $log_file_name;
2557
-
2558
-    /**
2559
-     * @var string $debug_file_name
2560
-     */
2561
-    public $debug_file_name;
2562
-
2563
-    /**
2564
-     * @var boolean $use_remote_logging
2565
-     */
2566
-    public $use_remote_logging;
2567
-
2568
-    /**
2569
-     * @var string $remote_logging_url
2570
-     */
2571
-    public $remote_logging_url;
2572
-
2573
-    /**
2574
-     * @var boolean $show_reg_footer
2575
-     */
2576
-    public $show_reg_footer;
2577
-
2578
-    /**
2579
-     * @var string $affiliate_id
2580
-     */
2581
-    public $affiliate_id;
2582
-
2583
-    /**
2584
-     * help tours on or off (global setting)
2585
-     *
2586
-     * @var boolean
2587
-     */
2588
-    public $help_tour_activation;
2589
-
2590
-    /**
2591
-     * adds extra layer of encoding to session data to prevent serialization errors
2592
-     * but is incompatible with some server configuration errors
2593
-     * if you get "500 internal server errors" during registration, try turning this on
2594
-     * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2595
-     *
2596
-     * @var boolean $encode_session_data
2597
-     */
2598
-    private $encode_session_data = false;
2599
-
2600
-
2601
-    /**
2602
-     *    class constructor
2603
-     *
2604
-     * @access    public
2605
-     */
2606
-    public function __construct()
2607
-    {
2608
-        // set default general admin settings
2609
-        $this->use_personnel_manager = true;
2610
-        $this->use_dashboard_widget = true;
2611
-        $this->events_in_dashboard = 30;
2612
-        $this->use_event_timezones = false;
2613
-        $this->use_full_logging = false;
2614
-        $this->use_remote_logging = false;
2615
-        $this->remote_logging_url = null;
2616
-        $this->show_reg_footer = true;
2617
-        $this->affiliate_id = 'default';
2618
-        $this->help_tour_activation = true;
2619
-        $this->encode_session_data = false;
2620
-    }
2621
-
2622
-
2623
-    /**
2624
-     * @param bool $reset
2625
-     * @return string
2626
-     */
2627
-    public function log_file_name($reset = false)
2628
-    {
2629
-        if (empty($this->log_file_name) || $reset) {
2630
-            $this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2631
-            EE_Config::instance()->update_espresso_config(false, false);
2632
-        }
2633
-        return $this->log_file_name;
2634
-    }
2635
-
2636
-
2637
-    /**
2638
-     * @param bool $reset
2639
-     * @return string
2640
-     */
2641
-    public function debug_file_name($reset = false)
2642
-    {
2643
-        if (empty($this->debug_file_name) || $reset) {
2644
-            $this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2645
-            EE_Config::instance()->update_espresso_config(false, false);
2646
-        }
2647
-        return $this->debug_file_name;
2648
-    }
2649
-
2650
-
2651
-    /**
2652
-     * @return string
2653
-     */
2654
-    public function affiliate_id()
2655
-    {
2656
-        return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2657
-    }
2658
-
2659
-
2660
-    /**
2661
-     * @return boolean
2662
-     */
2663
-    public function encode_session_data()
2664
-    {
2665
-        return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2666
-    }
2667
-
2668
-
2669
-    /**
2670
-     * @param boolean $encode_session_data
2671
-     */
2672
-    public function set_encode_session_data($encode_session_data)
2673
-    {
2674
-        $this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2675
-    }
2528
+	/**
2529
+	 * @var boolean $use_personnel_manager
2530
+	 */
2531
+	public $use_personnel_manager;
2532
+
2533
+	/**
2534
+	 * @var boolean $use_dashboard_widget
2535
+	 */
2536
+	public $use_dashboard_widget;
2537
+
2538
+	/**
2539
+	 * @var int $events_in_dashboard
2540
+	 */
2541
+	public $events_in_dashboard;
2542
+
2543
+	/**
2544
+	 * @var boolean $use_event_timezones
2545
+	 */
2546
+	public $use_event_timezones;
2547
+
2548
+	/**
2549
+	 * @var boolean $use_full_logging
2550
+	 */
2551
+	public $use_full_logging;
2552
+
2553
+	/**
2554
+	 * @var string $log_file_name
2555
+	 */
2556
+	public $log_file_name;
2557
+
2558
+	/**
2559
+	 * @var string $debug_file_name
2560
+	 */
2561
+	public $debug_file_name;
2562
+
2563
+	/**
2564
+	 * @var boolean $use_remote_logging
2565
+	 */
2566
+	public $use_remote_logging;
2567
+
2568
+	/**
2569
+	 * @var string $remote_logging_url
2570
+	 */
2571
+	public $remote_logging_url;
2572
+
2573
+	/**
2574
+	 * @var boolean $show_reg_footer
2575
+	 */
2576
+	public $show_reg_footer;
2577
+
2578
+	/**
2579
+	 * @var string $affiliate_id
2580
+	 */
2581
+	public $affiliate_id;
2582
+
2583
+	/**
2584
+	 * help tours on or off (global setting)
2585
+	 *
2586
+	 * @var boolean
2587
+	 */
2588
+	public $help_tour_activation;
2589
+
2590
+	/**
2591
+	 * adds extra layer of encoding to session data to prevent serialization errors
2592
+	 * but is incompatible with some server configuration errors
2593
+	 * if you get "500 internal server errors" during registration, try turning this on
2594
+	 * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2595
+	 *
2596
+	 * @var boolean $encode_session_data
2597
+	 */
2598
+	private $encode_session_data = false;
2599
+
2600
+
2601
+	/**
2602
+	 *    class constructor
2603
+	 *
2604
+	 * @access    public
2605
+	 */
2606
+	public function __construct()
2607
+	{
2608
+		// set default general admin settings
2609
+		$this->use_personnel_manager = true;
2610
+		$this->use_dashboard_widget = true;
2611
+		$this->events_in_dashboard = 30;
2612
+		$this->use_event_timezones = false;
2613
+		$this->use_full_logging = false;
2614
+		$this->use_remote_logging = false;
2615
+		$this->remote_logging_url = null;
2616
+		$this->show_reg_footer = true;
2617
+		$this->affiliate_id = 'default';
2618
+		$this->help_tour_activation = true;
2619
+		$this->encode_session_data = false;
2620
+	}
2621
+
2622
+
2623
+	/**
2624
+	 * @param bool $reset
2625
+	 * @return string
2626
+	 */
2627
+	public function log_file_name($reset = false)
2628
+	{
2629
+		if (empty($this->log_file_name) || $reset) {
2630
+			$this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2631
+			EE_Config::instance()->update_espresso_config(false, false);
2632
+		}
2633
+		return $this->log_file_name;
2634
+	}
2635
+
2636
+
2637
+	/**
2638
+	 * @param bool $reset
2639
+	 * @return string
2640
+	 */
2641
+	public function debug_file_name($reset = false)
2642
+	{
2643
+		if (empty($this->debug_file_name) || $reset) {
2644
+			$this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2645
+			EE_Config::instance()->update_espresso_config(false, false);
2646
+		}
2647
+		return $this->debug_file_name;
2648
+	}
2649
+
2650
+
2651
+	/**
2652
+	 * @return string
2653
+	 */
2654
+	public function affiliate_id()
2655
+	{
2656
+		return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2657
+	}
2658
+
2659
+
2660
+	/**
2661
+	 * @return boolean
2662
+	 */
2663
+	public function encode_session_data()
2664
+	{
2665
+		return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2666
+	}
2667
+
2668
+
2669
+	/**
2670
+	 * @param boolean $encode_session_data
2671
+	 */
2672
+	public function set_encode_session_data($encode_session_data)
2673
+	{
2674
+		$this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2675
+	}
2676 2676
 }
2677 2677
 
2678 2678
 /**
@@ -2681,70 +2681,70 @@  discard block
 block discarded – undo
2681 2681
 class EE_Template_Config extends EE_Config_Base
2682 2682
 {
2683 2683
 
2684
-    /**
2685
-     * @var boolean $enable_default_style
2686
-     */
2687
-    public $enable_default_style;
2688
-
2689
-    /**
2690
-     * @var string $custom_style_sheet
2691
-     */
2692
-    public $custom_style_sheet;
2693
-
2694
-    /**
2695
-     * @var boolean $display_address_in_regform
2696
-     */
2697
-    public $display_address_in_regform;
2698
-
2699
-    /**
2700
-     * @var int $display_description_on_multi_reg_page
2701
-     */
2702
-    public $display_description_on_multi_reg_page;
2703
-
2704
-    /**
2705
-     * @var boolean $use_custom_templates
2706
-     */
2707
-    public $use_custom_templates;
2708
-
2709
-    /**
2710
-     * @var string $current_espresso_theme
2711
-     */
2712
-    public $current_espresso_theme;
2713
-
2714
-    /**
2715
-     * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2716
-     */
2717
-    public $EED_Ticket_Selector;
2718
-
2719
-    /**
2720
-     * @var EE_Event_Single_Config $EED_Event_Single
2721
-     */
2722
-    public $EED_Event_Single;
2723
-
2724
-    /**
2725
-     * @var EE_Events_Archive_Config $EED_Events_Archive
2726
-     */
2727
-    public $EED_Events_Archive;
2728
-
2729
-
2730
-    /**
2731
-     *    class constructor
2732
-     *
2733
-     * @access    public
2734
-     */
2735
-    public function __construct()
2736
-    {
2737
-        // set default template settings
2738
-        $this->enable_default_style = true;
2739
-        $this->custom_style_sheet = null;
2740
-        $this->display_address_in_regform = true;
2741
-        $this->display_description_on_multi_reg_page = false;
2742
-        $this->use_custom_templates = false;
2743
-        $this->current_espresso_theme = 'Espresso_Arabica_2014';
2744
-        $this->EED_Event_Single = null;
2745
-        $this->EED_Events_Archive = null;
2746
-        $this->EED_Ticket_Selector = null;
2747
-    }
2684
+	/**
2685
+	 * @var boolean $enable_default_style
2686
+	 */
2687
+	public $enable_default_style;
2688
+
2689
+	/**
2690
+	 * @var string $custom_style_sheet
2691
+	 */
2692
+	public $custom_style_sheet;
2693
+
2694
+	/**
2695
+	 * @var boolean $display_address_in_regform
2696
+	 */
2697
+	public $display_address_in_regform;
2698
+
2699
+	/**
2700
+	 * @var int $display_description_on_multi_reg_page
2701
+	 */
2702
+	public $display_description_on_multi_reg_page;
2703
+
2704
+	/**
2705
+	 * @var boolean $use_custom_templates
2706
+	 */
2707
+	public $use_custom_templates;
2708
+
2709
+	/**
2710
+	 * @var string $current_espresso_theme
2711
+	 */
2712
+	public $current_espresso_theme;
2713
+
2714
+	/**
2715
+	 * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2716
+	 */
2717
+	public $EED_Ticket_Selector;
2718
+
2719
+	/**
2720
+	 * @var EE_Event_Single_Config $EED_Event_Single
2721
+	 */
2722
+	public $EED_Event_Single;
2723
+
2724
+	/**
2725
+	 * @var EE_Events_Archive_Config $EED_Events_Archive
2726
+	 */
2727
+	public $EED_Events_Archive;
2728
+
2729
+
2730
+	/**
2731
+	 *    class constructor
2732
+	 *
2733
+	 * @access    public
2734
+	 */
2735
+	public function __construct()
2736
+	{
2737
+		// set default template settings
2738
+		$this->enable_default_style = true;
2739
+		$this->custom_style_sheet = null;
2740
+		$this->display_address_in_regform = true;
2741
+		$this->display_description_on_multi_reg_page = false;
2742
+		$this->use_custom_templates = false;
2743
+		$this->current_espresso_theme = 'Espresso_Arabica_2014';
2744
+		$this->EED_Event_Single = null;
2745
+		$this->EED_Events_Archive = null;
2746
+		$this->EED_Ticket_Selector = null;
2747
+	}
2748 2748
 }
2749 2749
 
2750 2750
 /**
@@ -2753,114 +2753,114 @@  discard block
 block discarded – undo
2753 2753
 class EE_Map_Config extends EE_Config_Base
2754 2754
 {
2755 2755
 
2756
-    /**
2757
-     * @var boolean $use_google_maps
2758
-     */
2759
-    public $use_google_maps;
2760
-
2761
-    /**
2762
-     * @var string $api_key
2763
-     */
2764
-    public $google_map_api_key;
2765
-
2766
-    /**
2767
-     * @var int $event_details_map_width
2768
-     */
2769
-    public $event_details_map_width;
2770
-
2771
-    /**
2772
-     * @var int $event_details_map_height
2773
-     */
2774
-    public $event_details_map_height;
2775
-
2776
-    /**
2777
-     * @var int $event_details_map_zoom
2778
-     */
2779
-    public $event_details_map_zoom;
2780
-
2781
-    /**
2782
-     * @var boolean $event_details_display_nav
2783
-     */
2784
-    public $event_details_display_nav;
2785
-
2786
-    /**
2787
-     * @var boolean $event_details_nav_size
2788
-     */
2789
-    public $event_details_nav_size;
2790
-
2791
-    /**
2792
-     * @var string $event_details_control_type
2793
-     */
2794
-    public $event_details_control_type;
2795
-
2796
-    /**
2797
-     * @var string $event_details_map_align
2798
-     */
2799
-    public $event_details_map_align;
2800
-
2801
-    /**
2802
-     * @var int $event_list_map_width
2803
-     */
2804
-    public $event_list_map_width;
2805
-
2806
-    /**
2807
-     * @var int $event_list_map_height
2808
-     */
2809
-    public $event_list_map_height;
2810
-
2811
-    /**
2812
-     * @var int $event_list_map_zoom
2813
-     */
2814
-    public $event_list_map_zoom;
2815
-
2816
-    /**
2817
-     * @var boolean $event_list_display_nav
2818
-     */
2819
-    public $event_list_display_nav;
2820
-
2821
-    /**
2822
-     * @var boolean $event_list_nav_size
2823
-     */
2824
-    public $event_list_nav_size;
2825
-
2826
-    /**
2827
-     * @var string $event_list_control_type
2828
-     */
2829
-    public $event_list_control_type;
2830
-
2831
-    /**
2832
-     * @var string $event_list_map_align
2833
-     */
2834
-    public $event_list_map_align;
2835
-
2836
-
2837
-    /**
2838
-     *    class constructor
2839
-     *
2840
-     * @access    public
2841
-     */
2842
-    public function __construct()
2843
-    {
2844
-        // set default map settings
2845
-        $this->use_google_maps = true;
2846
-        $this->google_map_api_key = '';
2847
-        // for event details pages (reg page)
2848
-        $this->event_details_map_width = 585;            // ee_map_width_single
2849
-        $this->event_details_map_height = 362;            // ee_map_height_single
2850
-        $this->event_details_map_zoom = 14;            // ee_map_zoom_single
2851
-        $this->event_details_display_nav = true;            // ee_map_nav_display_single
2852
-        $this->event_details_nav_size = false;            // ee_map_nav_size_single
2853
-        $this->event_details_control_type = 'default';        // ee_map_type_control_single
2854
-        $this->event_details_map_align = 'center';            // ee_map_align_single
2855
-        // for event list pages
2856
-        $this->event_list_map_width = 300;            // ee_map_width
2857
-        $this->event_list_map_height = 185;        // ee_map_height
2858
-        $this->event_list_map_zoom = 12;            // ee_map_zoom
2859
-        $this->event_list_display_nav = false;        // ee_map_nav_display
2860
-        $this->event_list_nav_size = true;            // ee_map_nav_size
2861
-        $this->event_list_control_type = 'dropdown';        // ee_map_type_control
2862
-        $this->event_list_map_align = 'center';            // ee_map_align
2863
-    }
2756
+	/**
2757
+	 * @var boolean $use_google_maps
2758
+	 */
2759
+	public $use_google_maps;
2760
+
2761
+	/**
2762
+	 * @var string $api_key
2763
+	 */
2764
+	public $google_map_api_key;
2765
+
2766
+	/**
2767
+	 * @var int $event_details_map_width
2768
+	 */
2769
+	public $event_details_map_width;
2770
+
2771
+	/**
2772
+	 * @var int $event_details_map_height
2773
+	 */
2774
+	public $event_details_map_height;
2775
+
2776
+	/**
2777
+	 * @var int $event_details_map_zoom
2778
+	 */
2779
+	public $event_details_map_zoom;
2780
+
2781
+	/**
2782
+	 * @var boolean $event_details_display_nav
2783
+	 */
2784
+	public $event_details_display_nav;
2785
+
2786
+	/**
2787
+	 * @var boolean $event_details_nav_size
2788
+	 */
2789
+	public $event_details_nav_size;
2790
+
2791
+	/**
2792
+	 * @var string $event_details_control_type
2793
+	 */
2794
+	public $event_details_control_type;
2795
+
2796
+	/**
2797
+	 * @var string $event_details_map_align
2798
+	 */
2799
+	public $event_details_map_align;
2800
+
2801
+	/**
2802
+	 * @var int $event_list_map_width
2803
+	 */
2804
+	public $event_list_map_width;
2805
+
2806
+	/**
2807
+	 * @var int $event_list_map_height
2808
+	 */
2809
+	public $event_list_map_height;
2810
+
2811
+	/**
2812
+	 * @var int $event_list_map_zoom
2813
+	 */
2814
+	public $event_list_map_zoom;
2815
+
2816
+	/**
2817
+	 * @var boolean $event_list_display_nav
2818
+	 */
2819
+	public $event_list_display_nav;
2820
+
2821
+	/**
2822
+	 * @var boolean $event_list_nav_size
2823
+	 */
2824
+	public $event_list_nav_size;
2825
+
2826
+	/**
2827
+	 * @var string $event_list_control_type
2828
+	 */
2829
+	public $event_list_control_type;
2830
+
2831
+	/**
2832
+	 * @var string $event_list_map_align
2833
+	 */
2834
+	public $event_list_map_align;
2835
+
2836
+
2837
+	/**
2838
+	 *    class constructor
2839
+	 *
2840
+	 * @access    public
2841
+	 */
2842
+	public function __construct()
2843
+	{
2844
+		// set default map settings
2845
+		$this->use_google_maps = true;
2846
+		$this->google_map_api_key = '';
2847
+		// for event details pages (reg page)
2848
+		$this->event_details_map_width = 585;            // ee_map_width_single
2849
+		$this->event_details_map_height = 362;            // ee_map_height_single
2850
+		$this->event_details_map_zoom = 14;            // ee_map_zoom_single
2851
+		$this->event_details_display_nav = true;            // ee_map_nav_display_single
2852
+		$this->event_details_nav_size = false;            // ee_map_nav_size_single
2853
+		$this->event_details_control_type = 'default';        // ee_map_type_control_single
2854
+		$this->event_details_map_align = 'center';            // ee_map_align_single
2855
+		// for event list pages
2856
+		$this->event_list_map_width = 300;            // ee_map_width
2857
+		$this->event_list_map_height = 185;        // ee_map_height
2858
+		$this->event_list_map_zoom = 12;            // ee_map_zoom
2859
+		$this->event_list_display_nav = false;        // ee_map_nav_display
2860
+		$this->event_list_nav_size = true;            // ee_map_nav_size
2861
+		$this->event_list_control_type = 'dropdown';        // ee_map_type_control
2862
+		$this->event_list_map_align = 'center';            // ee_map_align
2863
+	}
2864 2864
 }
2865 2865
 
2866 2866
 /**
@@ -2869,46 +2869,46 @@  discard block
 block discarded – undo
2869 2869
 class EE_Events_Archive_Config extends EE_Config_Base
2870 2870
 {
2871 2871
 
2872
-    public $display_status_banner;
2872
+	public $display_status_banner;
2873 2873
 
2874
-    public $display_description;
2874
+	public $display_description;
2875 2875
 
2876
-    public $display_ticket_selector;
2876
+	public $display_ticket_selector;
2877 2877
 
2878
-    public $display_datetimes;
2878
+	public $display_datetimes;
2879 2879
 
2880
-    public $display_venue;
2880
+	public $display_venue;
2881 2881
 
2882
-    public $display_expired_events;
2882
+	public $display_expired_events;
2883 2883
 
2884
-    public $use_sortable_display_order;
2884
+	public $use_sortable_display_order;
2885 2885
 
2886
-    public $display_order_tickets;
2886
+	public $display_order_tickets;
2887 2887
 
2888
-    public $display_order_datetimes;
2888
+	public $display_order_datetimes;
2889 2889
 
2890
-    public $display_order_event;
2890
+	public $display_order_event;
2891 2891
 
2892
-    public $display_order_venue;
2892
+	public $display_order_venue;
2893 2893
 
2894 2894
 
2895
-    /**
2896
-     *    class constructor
2897
-     */
2898
-    public function __construct()
2899
-    {
2900
-        $this->display_status_banner = 0;
2901
-        $this->display_description = 1;
2902
-        $this->display_ticket_selector = 0;
2903
-        $this->display_datetimes = 1;
2904
-        $this->display_venue = 0;
2905
-        $this->display_expired_events = 0;
2906
-        $this->use_sortable_display_order = false;
2907
-        $this->display_order_tickets = 100;
2908
-        $this->display_order_datetimes = 110;
2909
-        $this->display_order_event = 120;
2910
-        $this->display_order_venue = 130;
2911
-    }
2895
+	/**
2896
+	 *    class constructor
2897
+	 */
2898
+	public function __construct()
2899
+	{
2900
+		$this->display_status_banner = 0;
2901
+		$this->display_description = 1;
2902
+		$this->display_ticket_selector = 0;
2903
+		$this->display_datetimes = 1;
2904
+		$this->display_venue = 0;
2905
+		$this->display_expired_events = 0;
2906
+		$this->use_sortable_display_order = false;
2907
+		$this->display_order_tickets = 100;
2908
+		$this->display_order_datetimes = 110;
2909
+		$this->display_order_event = 120;
2910
+		$this->display_order_venue = 130;
2911
+	}
2912 2912
 }
2913 2913
 
2914 2914
 /**
@@ -2917,34 +2917,34 @@  discard block
 block discarded – undo
2917 2917
 class EE_Event_Single_Config extends EE_Config_Base
2918 2918
 {
2919 2919
 
2920
-    public $display_status_banner_single;
2920
+	public $display_status_banner_single;
2921 2921
 
2922
-    public $display_venue;
2922
+	public $display_venue;
2923 2923
 
2924
-    public $use_sortable_display_order;
2924
+	public $use_sortable_display_order;
2925 2925
 
2926
-    public $display_order_tickets;
2926
+	public $display_order_tickets;
2927 2927
 
2928
-    public $display_order_datetimes;
2928
+	public $display_order_datetimes;
2929 2929
 
2930
-    public $display_order_event;
2930
+	public $display_order_event;
2931 2931
 
2932
-    public $display_order_venue;
2932
+	public $display_order_venue;
2933 2933
 
2934 2934
 
2935
-    /**
2936
-     *    class constructor
2937
-     */
2938
-    public function __construct()
2939
-    {
2940
-        $this->display_status_banner_single = 0;
2941
-        $this->display_venue = 1;
2942
-        $this->use_sortable_display_order = false;
2943
-        $this->display_order_tickets = 100;
2944
-        $this->display_order_datetimes = 110;
2945
-        $this->display_order_event = 120;
2946
-        $this->display_order_venue = 130;
2947
-    }
2935
+	/**
2936
+	 *    class constructor
2937
+	 */
2938
+	public function __construct()
2939
+	{
2940
+		$this->display_status_banner_single = 0;
2941
+		$this->display_venue = 1;
2942
+		$this->use_sortable_display_order = false;
2943
+		$this->display_order_tickets = 100;
2944
+		$this->display_order_datetimes = 110;
2945
+		$this->display_order_event = 120;
2946
+		$this->display_order_venue = 130;
2947
+	}
2948 2948
 }
2949 2949
 
2950 2950
 /**
@@ -2953,172 +2953,172 @@  discard block
 block discarded – undo
2953 2953
 class EE_Ticket_Selector_Config extends EE_Config_Base
2954 2954
 {
2955 2955
 
2956
-    /**
2957
-     * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2958
-     */
2959
-    const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2960
-
2961
-    /**
2962
-     * constant to indicate that a datetime selector should only be shown for ticket selectors
2963
-     * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2964
-     */
2965
-    const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2966
-
2967
-    /**
2968
-     * @var boolean $show_ticket_sale_columns
2969
-     */
2970
-    public $show_ticket_sale_columns;
2971
-
2972
-    /**
2973
-     * @var boolean $show_ticket_details
2974
-     */
2975
-    public $show_ticket_details;
2976
-
2977
-    /**
2978
-     * @var boolean $show_expired_tickets
2979
-     */
2980
-    public $show_expired_tickets;
2981
-
2982
-    /**
2983
-     * whether or not to display a dropdown box populated with event datetimes
2984
-     * that toggles which tickets are displayed for a ticket selector.
2985
-     * uses one of the *_DATETIME_SELECTOR constants defined above
2986
-     *
2987
-     * @var string $show_datetime_selector
2988
-     */
2989
-    private $show_datetime_selector = 'no_datetime_selector';
2990
-
2991
-    /**
2992
-     * the number of datetimes an event has to have before conditionally displaying a datetime selector
2993
-     *
2994
-     * @var int $datetime_selector_threshold
2995
-     */
2996
-    private $datetime_selector_threshold = 3;
2997
-
2998
-    /**
2999
-     * determines the maximum number of "checked" dates in the date and time filter
3000
-     *
3001
-     * @var int $datetime_selector_checked
3002
-     */
3003
-    private $datetime_selector_max_checked = 10;
3004
-
3005
-
3006
-    /**
3007
-     *    class constructor
3008
-     */
3009
-    public function __construct()
3010
-    {
3011
-        $this->show_ticket_sale_columns = true;
3012
-        $this->show_ticket_details = true;
3013
-        $this->show_expired_tickets = true;
3014
-        $this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3015
-        $this->datetime_selector_threshold = 3;
3016
-        $this->datetime_selector_max_checked = 10;
3017
-    }
3018
-
3019
-
3020
-    /**
3021
-     * returns true if a datetime selector should be displayed
3022
-     *
3023
-     * @param array $datetimes
3024
-     * @return bool
3025
-     */
3026
-    public function showDatetimeSelector(array $datetimes)
3027
-    {
3028
-        // if the settings are NOT: don't show OR below threshold, THEN active = true
3029
-        return ! (
3030
-            $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
3031
-            || (
3032
-                $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
3033
-                && count($datetimes) < $this->getDatetimeSelectorThreshold()
3034
-            )
3035
-        );
3036
-    }
3037
-
3038
-
3039
-    /**
3040
-     * @return string
3041
-     */
3042
-    public function getShowDatetimeSelector()
3043
-    {
3044
-        return $this->show_datetime_selector;
3045
-    }
3046
-
3047
-
3048
-    /**
3049
-     * @param bool $keys_only
3050
-     * @return array
3051
-     */
3052
-    public function getShowDatetimeSelectorOptions($keys_only = true)
3053
-    {
3054
-        return $keys_only
3055
-            ? array(
3056
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3057
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3058
-            )
3059
-            : array(
3060
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3061
-                    'Do not show date & time filter',
3062
-                    'event_espresso'
3063
-                ),
3064
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3065
-                    'Maybe show date & time filter',
3066
-                    'event_espresso'
3067
-                ),
3068
-            );
3069
-    }
3070
-
3071
-
3072
-    /**
3073
-     * @param string $show_datetime_selector
3074
-     */
3075
-    public function setShowDatetimeSelector($show_datetime_selector)
3076
-    {
3077
-        $this->show_datetime_selector = in_array(
3078
-            $show_datetime_selector,
3079
-            $this->getShowDatetimeSelectorOptions(),
3080
-            true
3081
-        )
3082
-            ? $show_datetime_selector
3083
-            : \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3084
-    }
3085
-
3086
-
3087
-    /**
3088
-     * @return int
3089
-     */
3090
-    public function getDatetimeSelectorThreshold()
3091
-    {
3092
-        return $this->datetime_selector_threshold;
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * @param int $datetime_selector_threshold
3098
-     */
3099
-    public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3100
-    {
3101
-        $datetime_selector_threshold = absint($datetime_selector_threshold);
3102
-        $this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3103
-    }
3104
-
3105
-
3106
-    /**
3107
-     * @return int
3108
-     */
3109
-    public function getDatetimeSelectorMaxChecked()
3110
-    {
3111
-        return $this->datetime_selector_max_checked;
3112
-    }
3113
-
3114
-
3115
-    /**
3116
-     * @param int $datetime_selector_max_checked
3117
-     */
3118
-    public function setDatetimeSelectorMaxChecked($datetime_selector_max_checked)
3119
-    {
3120
-        $this->datetime_selector_max_checked = absint($datetime_selector_max_checked);
3121
-    }
2956
+	/**
2957
+	 * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2958
+	 */
2959
+	const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2960
+
2961
+	/**
2962
+	 * constant to indicate that a datetime selector should only be shown for ticket selectors
2963
+	 * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2964
+	 */
2965
+	const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2966
+
2967
+	/**
2968
+	 * @var boolean $show_ticket_sale_columns
2969
+	 */
2970
+	public $show_ticket_sale_columns;
2971
+
2972
+	/**
2973
+	 * @var boolean $show_ticket_details
2974
+	 */
2975
+	public $show_ticket_details;
2976
+
2977
+	/**
2978
+	 * @var boolean $show_expired_tickets
2979
+	 */
2980
+	public $show_expired_tickets;
2981
+
2982
+	/**
2983
+	 * whether or not to display a dropdown box populated with event datetimes
2984
+	 * that toggles which tickets are displayed for a ticket selector.
2985
+	 * uses one of the *_DATETIME_SELECTOR constants defined above
2986
+	 *
2987
+	 * @var string $show_datetime_selector
2988
+	 */
2989
+	private $show_datetime_selector = 'no_datetime_selector';
2990
+
2991
+	/**
2992
+	 * the number of datetimes an event has to have before conditionally displaying a datetime selector
2993
+	 *
2994
+	 * @var int $datetime_selector_threshold
2995
+	 */
2996
+	private $datetime_selector_threshold = 3;
2997
+
2998
+	/**
2999
+	 * determines the maximum number of "checked" dates in the date and time filter
3000
+	 *
3001
+	 * @var int $datetime_selector_checked
3002
+	 */
3003
+	private $datetime_selector_max_checked = 10;
3004
+
3005
+
3006
+	/**
3007
+	 *    class constructor
3008
+	 */
3009
+	public function __construct()
3010
+	{
3011
+		$this->show_ticket_sale_columns = true;
3012
+		$this->show_ticket_details = true;
3013
+		$this->show_expired_tickets = true;
3014
+		$this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3015
+		$this->datetime_selector_threshold = 3;
3016
+		$this->datetime_selector_max_checked = 10;
3017
+	}
3018
+
3019
+
3020
+	/**
3021
+	 * returns true if a datetime selector should be displayed
3022
+	 *
3023
+	 * @param array $datetimes
3024
+	 * @return bool
3025
+	 */
3026
+	public function showDatetimeSelector(array $datetimes)
3027
+	{
3028
+		// if the settings are NOT: don't show OR below threshold, THEN active = true
3029
+		return ! (
3030
+			$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
3031
+			|| (
3032
+				$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
3033
+				&& count($datetimes) < $this->getDatetimeSelectorThreshold()
3034
+			)
3035
+		);
3036
+	}
3037
+
3038
+
3039
+	/**
3040
+	 * @return string
3041
+	 */
3042
+	public function getShowDatetimeSelector()
3043
+	{
3044
+		return $this->show_datetime_selector;
3045
+	}
3046
+
3047
+
3048
+	/**
3049
+	 * @param bool $keys_only
3050
+	 * @return array
3051
+	 */
3052
+	public function getShowDatetimeSelectorOptions($keys_only = true)
3053
+	{
3054
+		return $keys_only
3055
+			? array(
3056
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3057
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3058
+			)
3059
+			: array(
3060
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3061
+					'Do not show date & time filter',
3062
+					'event_espresso'
3063
+				),
3064
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3065
+					'Maybe show date & time filter',
3066
+					'event_espresso'
3067
+				),
3068
+			);
3069
+	}
3070
+
3071
+
3072
+	/**
3073
+	 * @param string $show_datetime_selector
3074
+	 */
3075
+	public function setShowDatetimeSelector($show_datetime_selector)
3076
+	{
3077
+		$this->show_datetime_selector = in_array(
3078
+			$show_datetime_selector,
3079
+			$this->getShowDatetimeSelectorOptions(),
3080
+			true
3081
+		)
3082
+			? $show_datetime_selector
3083
+			: \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3084
+	}
3085
+
3086
+
3087
+	/**
3088
+	 * @return int
3089
+	 */
3090
+	public function getDatetimeSelectorThreshold()
3091
+	{
3092
+		return $this->datetime_selector_threshold;
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * @param int $datetime_selector_threshold
3098
+	 */
3099
+	public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3100
+	{
3101
+		$datetime_selector_threshold = absint($datetime_selector_threshold);
3102
+		$this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3103
+	}
3104
+
3105
+
3106
+	/**
3107
+	 * @return int
3108
+	 */
3109
+	public function getDatetimeSelectorMaxChecked()
3110
+	{
3111
+		return $this->datetime_selector_max_checked;
3112
+	}
3113
+
3114
+
3115
+	/**
3116
+	 * @param int $datetime_selector_max_checked
3117
+	 */
3118
+	public function setDatetimeSelectorMaxChecked($datetime_selector_max_checked)
3119
+	{
3120
+		$this->datetime_selector_max_checked = absint($datetime_selector_max_checked);
3121
+	}
3122 3122
 }
3123 3123
 
3124 3124
 /**
@@ -3131,81 +3131,81 @@  discard block
 block discarded – undo
3131 3131
 class EE_Environment_Config extends EE_Config_Base
3132 3132
 {
3133 3133
 
3134
-    /**
3135
-     * Hold any php environment variables that we want to track.
3136
-     *
3137
-     * @var stdClass;
3138
-     */
3139
-    public $php;
3140
-
3141
-
3142
-    /**
3143
-     *    constructor
3144
-     */
3145
-    public function __construct()
3146
-    {
3147
-        $this->php = new stdClass();
3148
-        $this->_set_php_values();
3149
-    }
3150
-
3151
-
3152
-    /**
3153
-     * This sets the php environment variables.
3154
-     *
3155
-     * @since 4.4.0
3156
-     * @return void
3157
-     */
3158
-    protected function _set_php_values()
3159
-    {
3160
-        $this->php->max_input_vars = ini_get('max_input_vars');
3161
-        $this->php->version = phpversion();
3162
-    }
3163
-
3164
-
3165
-    /**
3166
-     * helper method for determining whether input_count is
3167
-     * reaching the potential maximum the server can handle
3168
-     * according to max_input_vars
3169
-     *
3170
-     * @param int   $input_count the count of input vars.
3171
-     * @return array {
3172
-     *                           An array that represents whether available space and if no available space the error
3173
-     *                           message.
3174
-     * @type bool   $has_space   whether more inputs can be added.
3175
-     * @type string $msg         Any message to be displayed.
3176
-     *                           }
3177
-     */
3178
-    public function max_input_vars_limit_check($input_count = 0)
3179
-    {
3180
-        if (! empty($this->php->max_input_vars)
3181
-            && ($input_count >= $this->php->max_input_vars)
3182
-            && (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3183
-        ) {
3184
-            return sprintf(
3185
-                __(
3186
-                    'The maximum number of inputs on this page has been exceeded.  You cannot add anymore items (i.e. tickets, datetimes, custom fields) on this page because of your servers PHP "max_input_vars" setting.%1$sThere are %2$d inputs and the maximum amount currently allowed by your server is %3$d.',
3187
-                    'event_espresso'
3188
-                ),
3189
-                '<br>',
3190
-                $input_count,
3191
-                $this->php->max_input_vars
3192
-            );
3193
-        } else {
3194
-            return '';
3195
-        }
3196
-    }
3197
-
3198
-
3199
-    /**
3200
-     * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3201
-     *
3202
-     * @since 4.4.1
3203
-     * @return void
3204
-     */
3205
-    public function recheck_values()
3206
-    {
3207
-        $this->_set_php_values();
3208
-    }
3134
+	/**
3135
+	 * Hold any php environment variables that we want to track.
3136
+	 *
3137
+	 * @var stdClass;
3138
+	 */
3139
+	public $php;
3140
+
3141
+
3142
+	/**
3143
+	 *    constructor
3144
+	 */
3145
+	public function __construct()
3146
+	{
3147
+		$this->php = new stdClass();
3148
+		$this->_set_php_values();
3149
+	}
3150
+
3151
+
3152
+	/**
3153
+	 * This sets the php environment variables.
3154
+	 *
3155
+	 * @since 4.4.0
3156
+	 * @return void
3157
+	 */
3158
+	protected function _set_php_values()
3159
+	{
3160
+		$this->php->max_input_vars = ini_get('max_input_vars');
3161
+		$this->php->version = phpversion();
3162
+	}
3163
+
3164
+
3165
+	/**
3166
+	 * helper method for determining whether input_count is
3167
+	 * reaching the potential maximum the server can handle
3168
+	 * according to max_input_vars
3169
+	 *
3170
+	 * @param int   $input_count the count of input vars.
3171
+	 * @return array {
3172
+	 *                           An array that represents whether available space and if no available space the error
3173
+	 *                           message.
3174
+	 * @type bool   $has_space   whether more inputs can be added.
3175
+	 * @type string $msg         Any message to be displayed.
3176
+	 *                           }
3177
+	 */
3178
+	public function max_input_vars_limit_check($input_count = 0)
3179
+	{
3180
+		if (! empty($this->php->max_input_vars)
3181
+			&& ($input_count >= $this->php->max_input_vars)
3182
+			&& (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3183
+		) {
3184
+			return sprintf(
3185
+				__(
3186
+					'The maximum number of inputs on this page has been exceeded.  You cannot add anymore items (i.e. tickets, datetimes, custom fields) on this page because of your servers PHP "max_input_vars" setting.%1$sThere are %2$d inputs and the maximum amount currently allowed by your server is %3$d.',
3187
+					'event_espresso'
3188
+				),
3189
+				'<br>',
3190
+				$input_count,
3191
+				$this->php->max_input_vars
3192
+			);
3193
+		} else {
3194
+			return '';
3195
+		}
3196
+	}
3197
+
3198
+
3199
+	/**
3200
+	 * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3201
+	 *
3202
+	 * @since 4.4.1
3203
+	 * @return void
3204
+	 */
3205
+	public function recheck_values()
3206
+	{
3207
+		$this->_set_php_values();
3208
+	}
3209 3209
 }
3210 3210
 
3211 3211
 /**
@@ -3218,21 +3218,21 @@  discard block
 block discarded – undo
3218 3218
 class EE_Tax_Config extends EE_Config_Base
3219 3219
 {
3220 3220
 
3221
-    /*
3221
+	/*
3222 3222
      * flag to indicate whether or not to display ticket prices with the taxes included
3223 3223
      *
3224 3224
      * @var boolean $prices_displayed_including_taxes
3225 3225
      */
3226
-    public $prices_displayed_including_taxes;
3226
+	public $prices_displayed_including_taxes;
3227 3227
 
3228 3228
 
3229
-    /**
3230
-     *    class constructor
3231
-     */
3232
-    public function __construct()
3233
-    {
3234
-        $this->prices_displayed_including_taxes = true;
3235
-    }
3229
+	/**
3230
+	 *    class constructor
3231
+	 */
3232
+	public function __construct()
3233
+	{
3234
+		$this->prices_displayed_including_taxes = true;
3235
+	}
3236 3236
 }
3237 3237
 
3238 3238
 /**
@@ -3246,19 +3246,19 @@  discard block
 block discarded – undo
3246 3246
 class EE_Messages_Config extends EE_Config_Base
3247 3247
 {
3248 3248
 
3249
-    /**
3250
-     * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3251
-     * A value of 0 represents never deleting.  Default is 0.
3252
-     *
3253
-     * @var integer
3254
-     */
3255
-    public $delete_threshold;
3249
+	/**
3250
+	 * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3251
+	 * A value of 0 represents never deleting.  Default is 0.
3252
+	 *
3253
+	 * @var integer
3254
+	 */
3255
+	public $delete_threshold;
3256 3256
 
3257 3257
 
3258
-    public function __construct()
3259
-    {
3260
-        $this->delete_threshold = 0;
3261
-    }
3258
+	public function __construct()
3259
+	{
3260
+		$this->delete_threshold = 0;
3261
+	}
3262 3262
 }
3263 3263
 
3264 3264
 /**
@@ -3269,31 +3269,31 @@  discard block
 block discarded – undo
3269 3269
 class EE_Gateway_Config extends EE_Config_Base
3270 3270
 {
3271 3271
 
3272
-    /**
3273
-     * Array with keys that are payment gateways slugs, and values are arrays
3274
-     * with any config info the gateway wants to store
3275
-     *
3276
-     * @var array
3277
-     */
3278
-    public $payment_settings;
3279
-
3280
-    /**
3281
-     * Where keys are gateway slugs, and values are booleans indicating whether or not
3282
-     * the gateway is stored in the uploads directory
3283
-     *
3284
-     * @var array
3285
-     */
3286
-    public $active_gateways;
3287
-
3288
-
3289
-    /**
3290
-     *    class constructor
3291
-     *
3292
-     * @deprecated
3293
-     */
3294
-    public function __construct()
3295
-    {
3296
-        $this->payment_settings = array();
3297
-        $this->active_gateways = array('Invoice' => false);
3298
-    }
3272
+	/**
3273
+	 * Array with keys that are payment gateways slugs, and values are arrays
3274
+	 * with any config info the gateway wants to store
3275
+	 *
3276
+	 * @var array
3277
+	 */
3278
+	public $payment_settings;
3279
+
3280
+	/**
3281
+	 * Where keys are gateway slugs, and values are booleans indicating whether or not
3282
+	 * the gateway is stored in the uploads directory
3283
+	 *
3284
+	 * @var array
3285
+	 */
3286
+	public $active_gateways;
3287
+
3288
+
3289
+	/**
3290
+	 *    class constructor
3291
+	 *
3292
+	 * @deprecated
3293
+	 */
3294
+	public function __construct()
3295
+	{
3296
+		$this->payment_settings = array();
3297
+		$this->active_gateways = array('Invoice' => false);
3298
+	}
3299 3299
 }
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +838 added lines, -838 removed lines patch added patch discarded remove patch
@@ -18,842 +18,842 @@
 block discarded – undo
18 18
 class EE_Payment_Processor extends EE_Processor_Base implements ResettableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Payment_Processor $_instance
23
-     * @access    private
24
-     */
25
-    private static $_instance;
26
-
27
-
28
-    /**
29
-     * @singleton method used to instantiate class object
30
-     * @access    public
31
-     * @return EE_Payment_Processor instance
32
-     */
33
-    public static function instance()
34
-    {
35
-        // check if class object is instantiated
36
-        if (! self::$_instance instanceof EE_Payment_Processor) {
37
-            self::$_instance = new self();
38
-        }
39
-        return self::$_instance;
40
-    }
41
-
42
-
43
-    /**
44
-     * @return EE_Payment_Processor
45
-     */
46
-    public static function reset()
47
-    {
48
-        self::$_instance = null;
49
-        return self::instance();
50
-    }
51
-
52
-
53
-    /**
54
-     *private constructor to prevent direct creation
55
-     *
56
-     * @Constructor
57
-     * @access private
58
-     */
59
-    private function __construct()
60
-    {
61
-        do_action('AHEE__EE_Payment_Processor__construct');
62
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
63
-    }
64
-
65
-
66
-    /**
67
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
68
-     * appropriately. Saves the payment that is generated
69
-     *
70
-     * @param EE_Payment_Method    $payment_method
71
-     * @param EE_Transaction       $transaction
72
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
73
-     *                                           Leave null if payment is for the full amount owing
74
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
75
-     *                                           Receive_form_submission() should have
76
-     *                                           already been called on the billing form
77
-     *                                           (ie, its inputs should have their normalized values set).
78
-     * @param string               $return_url   string used mostly by offsite gateways to specify
79
-     *                                           where to go AFTER the offsite gateway
80
-     * @param string               $method       like 'CART', indicates who the client who called this was
81
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
82
-     * @param boolean              $update_txn   whether or not to call
83
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
84
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
85
-     * @return EE_Payment
86
-     * @throws EE_Error
87
-     * @throws InvalidArgumentException
88
-     * @throws ReflectionException
89
-     * @throws RuntimeException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     */
93
-    public function process_payment(
94
-        EE_Payment_Method $payment_method,
95
-        EE_Transaction $transaction,
96
-        $amount = null,
97
-        $billing_form = null,
98
-        $return_url = null,
99
-        $method = 'CART',
100
-        $by_admin = false,
101
-        $update_txn = true,
102
-        $cancel_url = ''
103
-    ) {
104
-        if ((float) $amount < 0) {
105
-            throw new EE_Error(
106
-                sprintf(
107
-                    __(
108
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
109
-                        'event_espresso'
110
-                    ),
111
-                    $amount,
112
-                    $transaction->ID()
113
-                )
114
-            );
115
-        }
116
-        // verify payment method
117
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
118
-            $payment_method,
119
-            true
120
-        );
121
-        // verify transaction
122
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
123
-        $transaction->set_payment_method_ID($payment_method->ID());
124
-        // verify payment method type
125
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
126
-            $payment = $payment_method->type_obj()->process_payment(
127
-                $transaction,
128
-                min($amount, $transaction->remaining()), // make sure we don't overcharge
129
-                $billing_form,
130
-                $return_url,
131
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
132
-                $method,
133
-                $by_admin
134
-            );
135
-            // check if payment method uses an off-site gateway
136
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
137
-                // don't process payments for off-site gateways yet because no payment has occurred yet
138
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
139
-            }
140
-            return $payment;
141
-        }
142
-        EE_Error::add_error(
143
-            sprintf(
144
-                __(
145
-                    'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
146
-                    'event_espresso'
147
-                ),
148
-                '<br/>',
149
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
150
-            ),
151
-            __FILE__,
152
-            __FUNCTION__,
153
-            __LINE__
154
-        );
155
-        return null;
156
-    }
157
-
158
-
159
-    /**
160
-     * @param EE_Transaction|int $transaction
161
-     * @param EE_Payment_Method  $payment_method
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidDataTypeException
166
-     * @throws InvalidInterfaceException
167
-     */
168
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
169
-    {
170
-        /** @type \EE_Transaction $transaction */
171
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
172
-        $primary_reg = $transaction->primary_registration();
173
-        if (! $primary_reg instanceof EE_Registration) {
174
-            throw new EE_Error(
175
-                sprintf(
176
-                    __(
177
-                        'Cannot get IPN URL for transaction with ID %d because it has no primary registration',
178
-                        'event_espresso'
179
-                    ),
180
-                    $transaction->ID()
181
-                )
182
-            );
183
-        }
184
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
185
-            $payment_method,
186
-            true
187
-        );
188
-        $url = add_query_arg(
189
-            array(
190
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
191
-                'ee_payment_method' => $payment_method->slug(),
192
-            ),
193
-            EE_Registry::instance()->CFG->core->txn_page_url()
194
-        );
195
-        return $url;
196
-    }
197
-
198
-
199
-    /**
200
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
201
-     * we can easily find what registration the IPN is for and what payment method.
202
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
203
-     * If a payment is found for the IPN info, it is saved.
204
-     *
205
-     * @param array              $_req_data            eg $_REQUEST
206
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
207
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
208
-     * @param boolean            $update_txn           whether or not to call
209
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
210
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
211
-     *                                                 or is processed manually ( false like Mijireh )
212
-     * @throws EE_Error
213
-     * @throws Exception
214
-     * @return EE_Payment
215
-     * @throws \RuntimeException
216
-     * @throws \ReflectionException
217
-     * @throws \InvalidArgumentException
218
-     * @throws InvalidInterfaceException
219
-     * @throws InvalidDataTypeException
220
-     */
221
-    public function process_ipn(
222
-        $_req_data,
223
-        $transaction = null,
224
-        $payment_method = null,
225
-        $update_txn = true,
226
-        $separate_IPN_request = true
227
-    ) {
228
-        EE_Registry::instance()->load_model('Change_Log');
229
-        $_req_data = $this->_remove_unusable_characters_from_array((array) $_req_data);
230
-        EE_Processor_Base::set_IPN($separate_IPN_request);
231
-        $obj_for_log = null;
232
-        if ($transaction instanceof EE_Transaction) {
233
-            $obj_for_log = $transaction;
234
-            if ($payment_method instanceof EE_Payment_Method) {
235
-                $obj_for_log = EEM_Payment::instance()->get_one(
236
-                    array(
237
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
238
-                        'order_by' => array('PAY_timestamp' => 'desc'),
239
-                    )
240
-                );
241
-            }
242
-        } elseif ($payment_method instanceof EE_Payment) {
243
-            $obj_for_log = $payment_method;
244
-        }
245
-        $log = EEM_Change_Log::instance()->log(
246
-            EEM_Change_Log::type_gateway,
247
-            array('IPN data received' => $_req_data),
248
-            $obj_for_log
249
-        );
250
-        try {
251
-            /**
252
-             * @var EE_Payment $payment
253
-             */
254
-            $payment = null;
255
-            if ($transaction && $payment_method) {
256
-                /** @type EE_Transaction $transaction */
257
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
258
-                /** @type EE_Payment_Method $payment_method */
259
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
260
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
261
-                    try {
262
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
263
-                        $log->set_object($payment);
264
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
265
-                        EEM_Change_Log::instance()->log(
266
-                            EEM_Change_Log::type_gateway,
267
-                            array(
268
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
269
-                                'current_url' => EEH_URL::current_url(),
270
-                                'payment'     => $e->getPaymentProperties(),
271
-                                'IPN_data'    => $e->getIpnData(),
272
-                            ),
273
-                            $obj_for_log
274
-                        );
275
-                        return $e->getPayment();
276
-                    }
277
-                } else {
278
-                    // not a payment
279
-                    EE_Error::add_error(
280
-                        sprintf(
281
-                            __(
282
-                                'A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.',
283
-                                'event_espresso'
284
-                            ),
285
-                            '<br/>',
286
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
287
-                        ),
288
-                        __FILE__,
289
-                        __FUNCTION__,
290
-                        __LINE__
291
-                    );
292
-                }
293
-            } else {
294
-                // that's actually pretty ok. The IPN just wasn't able
295
-                // to identify which transaction or payment method this was for
296
-                // give all active payment methods a chance to claim it
297
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
298
-                foreach ($active_payment_methods as $active_payment_method) {
299
-                    try {
300
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
301
-                        $payment_method = $active_payment_method;
302
-                        EEM_Change_Log::instance()->log(
303
-                            EEM_Change_Log::type_gateway,
304
-                            array('IPN data' => $_req_data),
305
-                            $payment
306
-                        );
307
-                        break;
308
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
309
-                        EEM_Change_Log::instance()->log(
310
-                            EEM_Change_Log::type_gateway,
311
-                            array(
312
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
313
-                                'current_url' => EEH_URL::current_url(),
314
-                                'payment'     => $e->getPaymentProperties(),
315
-                                'IPN_data'    => $e->getIpnData(),
316
-                            ),
317
-                            $obj_for_log
318
-                        );
319
-                        return $e->getPayment();
320
-                    } catch (EE_Error $e) {
321
-                        // that's fine- it apparently couldn't handle the IPN
322
-                    }
323
-                }
324
-            }
325
-            // EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
326
-            if ($payment instanceof EE_Payment) {
327
-                $payment->save();
328
-                //  update the TXN
329
-                $this->update_txn_based_on_payment(
330
-                    $transaction,
331
-                    $payment,
332
-                    $update_txn,
333
-                    $separate_IPN_request
334
-                );
335
-            } else {
336
-                // we couldn't find the payment for this IPN... let's try and log at least SOMETHING
337
-                if ($payment_method) {
338
-                    EEM_Change_Log::instance()->log(
339
-                        EEM_Change_Log::type_gateway,
340
-                        array('IPN data' => $_req_data),
341
-                        $payment_method
342
-                    );
343
-                } elseif ($transaction) {
344
-                    EEM_Change_Log::instance()->log(
345
-                        EEM_Change_Log::type_gateway,
346
-                        array('IPN data' => $_req_data),
347
-                        $transaction
348
-                    );
349
-                }
350
-            }
351
-            return $payment;
352
-        } catch (EE_Error $e) {
353
-            do_action(
354
-                'AHEE__log',
355
-                __FILE__,
356
-                __FUNCTION__,
357
-                sprintf(
358
-                    __(
359
-                        'Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"',
360
-                        'event_espresso'
361
-                    ),
362
-                    print_r($transaction, true),
363
-                    print_r($_req_data, true),
364
-                    $e->getMessage()
365
-                )
366
-            );
367
-            throw $e;
368
-        }
369
-    }
370
-
371
-
372
-    /**
373
-     * Removes any non-printable illegal characters from the input,
374
-     * which might cause a raucous when trying to insert into the database
375
-     *
376
-     * @param  array $request_data
377
-     * @return array
378
-     */
379
-    protected function _remove_unusable_characters_from_array(array $request_data)
380
-    {
381
-        $return_data = array();
382
-        foreach ($request_data as $key => $value) {
383
-            $return_data[ $this->_remove_unusable_characters($key) ] = $this->_remove_unusable_characters(
384
-                $value
385
-            );
386
-        }
387
-        return $return_data;
388
-    }
389
-
390
-
391
-    /**
392
-     * Removes any non-printable illegal characters from the input,
393
-     * which might cause a raucous when trying to insert into the database
394
-     *
395
-     * @param string $request_data
396
-     * @return string
397
-     */
398
-    protected function _remove_unusable_characters($request_data)
399
-    {
400
-        return preg_replace('/[^[:print:]]/', '', $request_data);
401
-    }
402
-
403
-
404
-    /**
405
-     * Should be called just before displaying the payment attempt results to the user,
406
-     * when the payment attempt has finished. Some payment methods may have special
407
-     * logic to perform here. For example, if process_payment() happens on a special request
408
-     * and then the user is redirected to a page that displays the payment's status, this
409
-     * should be called while loading the page that displays the payment's status. If the user is
410
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
411
-     * provider.
412
-     *
413
-     * @param EE_Transaction|int $transaction
414
-     * @param bool               $update_txn whether or not to call
415
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
416
-     * @return EE_Payment
417
-     * @throws EE_Error
418
-     * @throws InvalidArgumentException
419
-     * @throws ReflectionException
420
-     * @throws RuntimeException
421
-     * @throws InvalidDataTypeException
422
-     * @throws InvalidInterfaceException
423
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
424
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
425
-     */
426
-    public function finalize_payment_for($transaction, $update_txn = true)
427
-    {
428
-        /** @var $transaction EE_Transaction */
429
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
430
-        $last_payment_method = $transaction->payment_method();
431
-        if ($last_payment_method instanceof EE_Payment_Method) {
432
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
433
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
434
-            return $payment;
435
-        }
436
-        return null;
437
-    }
438
-
439
-
440
-    /**
441
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
442
-     *
443
-     * @param EE_Payment_Method $payment_method
444
-     * @param EE_Payment        $payment_to_refund
445
-     * @param array             $refund_info
446
-     * @return EE_Payment
447
-     * @throws EE_Error
448
-     * @throws InvalidArgumentException
449
-     * @throws ReflectionException
450
-     * @throws RuntimeException
451
-     * @throws InvalidDataTypeException
452
-     * @throws InvalidInterfaceException
453
-     */
454
-    public function process_refund(
455
-        EE_Payment_Method $payment_method,
456
-        EE_Payment $payment_to_refund,
457
-        array $refund_info = array()
458
-    ) {
459
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
460
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
461
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
462
-        }
463
-        return $payment_to_refund;
464
-    }
465
-
466
-
467
-    /**
468
-     * This should be called each time there may have been an update to a
469
-     * payment on a transaction (ie, we asked for a payment to process a
470
-     * payment for a transaction, or we told a payment method about an IPN, or
471
-     * we told a payment method to
472
-     * "finalize_payment_for" (a transaction), or we told a payment method to
473
-     * process a refund. This should handle firing the correct hooks to
474
-     * indicate
475
-     * what exactly happened and updating the transaction appropriately). This
476
-     * could be integrated directly into EE_Transaction upon save, but we want
477
-     * this logic to be separate from 'normal' plain-jane saving and updating
478
-     * of transactions and payments, and to be tied to payment processing.
479
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
480
-     * of previous code to decide whether or not to save (because the payment passed into
481
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
482
-     * in which case we only want that payment object for some temporary usage during this request,
483
-     * but we don't want it to be saved).
484
-     *
485
-     * @param EE_Transaction|int $transaction
486
-     * @param EE_Payment         $payment
487
-     * @param boolean            $update_txn
488
-     *                        whether or not to call
489
-     *                        EE_Transaction_Processor::
490
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
491
-     *                        (you can save 1 DB query if you know you're going
492
-     *                        to save it later instead)
493
-     * @param bool               $IPN
494
-     *                        if processing IPNs or other similar payment
495
-     *                        related activities that occur in alternate
496
-     *                        requests than the main one that is processing the
497
-     *                        TXN, then set this to true to check whether the
498
-     *                        TXN is locked before updating
499
-     * @throws EE_Error
500
-     * @throws InvalidArgumentException
501
-     * @throws ReflectionException
502
-     * @throws RuntimeException
503
-     * @throws InvalidDataTypeException
504
-     * @throws InvalidInterfaceException
505
-     */
506
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
507
-    {
508
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
509
-        /** @type EE_Transaction $transaction */
510
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
511
-        // can we freely update the TXN at this moment?
512
-        if ($IPN && $transaction->is_locked()) {
513
-            // don't update the transaction at this exact moment
514
-            // because the TXN is active in another request
515
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
516
-                time(),
517
-                $transaction->ID(),
518
-                $payment->ID()
519
-            );
520
-        } else {
521
-            // verify payment and that it has been saved
522
-            if ($payment instanceof EE_Payment && $payment->ID()) {
523
-                if ($payment->payment_method() instanceof EE_Payment_Method
524
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
525
-                ) {
526
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
527
-                    // update TXN registrations with payment info
528
-                    $this->process_registration_payments($transaction, $payment);
529
-                }
530
-                $do_action = $payment->just_approved()
531
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
532
-                    : $do_action;
533
-            } else {
534
-                // send out notifications
535
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
536
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
537
-            }
538
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
539
-                /** @type EE_Transaction_Payments $transaction_payments */
540
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
541
-                // set new value for total paid
542
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
543
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
544
-                if ($update_txn) {
545
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
546
-                }
547
-            }
548
-            // granular hook for others to use.
549
-            do_action($do_action, $transaction, $payment);
550
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
551
-            // global hook for others to use.
552
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
553
-        }
554
-    }
555
-
556
-
557
-    /**
558
-     * update registrations REG_paid field after successful payment and link registrations with payment
559
-     *
560
-     * @param EE_Transaction    $transaction
561
-     * @param EE_Payment        $payment
562
-     * @param EE_Registration[] $registrations
563
-     * @throws EE_Error
564
-     * @throws InvalidArgumentException
565
-     * @throws RuntimeException
566
-     * @throws InvalidDataTypeException
567
-     * @throws InvalidInterfaceException
568
-     */
569
-    public function process_registration_payments(
570
-        EE_Transaction $transaction,
571
-        EE_Payment $payment,
572
-        array $registrations = array()
573
-    ) {
574
-        // only process if payment was successful
575
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
576
-            return;
577
-        }
578
-        // EEM_Registration::instance()->show_next_x_db_queries();
579
-        if (empty($registrations)) {
580
-            // find registrations with monies owing that can receive a payment
581
-            $registrations = $transaction->registrations(
582
-                array(
583
-                    array(
584
-                        // only these reg statuses can receive payments
585
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
586
-                        'REG_final_price'  => array('!=', 0),
587
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
588
-                    ),
589
-                )
590
-            );
591
-        }
592
-        // still nothing ??!??
593
-        if (empty($registrations)) {
594
-            return;
595
-        }
596
-        // todo: break out the following logic into a separate strategy class
597
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
598
-        // todo: which would apply payments using the capitalist "first come first paid" approach
599
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
600
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
601
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
602
-        $refund = $payment->is_a_refund();
603
-        // how much is available to apply to registrations?
604
-        $available_payment_amount = abs($payment->amount());
605
-        foreach ($registrations as $registration) {
606
-            if ($registration instanceof EE_Registration) {
607
-                // nothing left?
608
-                if ($available_payment_amount <= 0) {
609
-                    break;
610
-                }
611
-                if ($refund) {
612
-                    $available_payment_amount = $this->process_registration_refund(
613
-                        $registration,
614
-                        $payment,
615
-                        $available_payment_amount
616
-                    );
617
-                } else {
618
-                    $available_payment_amount = $this->process_registration_payment(
619
-                        $registration,
620
-                        $payment,
621
-                        $available_payment_amount
622
-                    );
623
-                }
624
-            }
625
-        }
626
-        if ($available_payment_amount > 0
627
-            && apply_filters(
628
-                'FHEE__EE_Payment_Processor__process_registration_payments__display_notifications',
629
-                false
630
-            )) {
631
-            EE_Error::add_attention(
632
-                sprintf(
633
-                    __(
634
-                        'A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
635
-                        'event_espresso'
636
-                    ),
637
-                    EEH_Template::format_currency($available_payment_amount),
638
-                    implode(', ', array_keys($registrations)),
639
-                    '<br/>',
640
-                    EEH_Template::format_currency($payment->amount())
641
-                ),
642
-                __FILE__,
643
-                __FUNCTION__,
644
-                __LINE__
645
-            );
646
-        }
647
-    }
648
-
649
-
650
-    /**
651
-     * update registration REG_paid field after successful payment and link registration with payment
652
-     *
653
-     * @param EE_Registration $registration
654
-     * @param EE_Payment      $payment
655
-     * @param float           $available_payment_amount
656
-     * @return float
657
-     * @throws EE_Error
658
-     * @throws InvalidArgumentException
659
-     * @throws RuntimeException
660
-     * @throws InvalidDataTypeException
661
-     * @throws InvalidInterfaceException
662
-     */
663
-    public function process_registration_payment(
664
-        EE_Registration $registration,
665
-        EE_Payment $payment,
666
-        $available_payment_amount = 0.00
667
-    ) {
668
-        $owing = $registration->final_price() - $registration->paid();
669
-        if ($owing > 0) {
670
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
671
-            $payment_amount = min($available_payment_amount, $owing);
672
-            // update $available_payment_amount
673
-            $available_payment_amount -= $payment_amount;
674
-            // calculate and set new REG_paid
675
-            $registration->set_paid($registration->paid() + $payment_amount);
676
-            // now save it
677
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
678
-        }
679
-        return $available_payment_amount;
680
-    }
681
-
682
-
683
-    /**
684
-     * update registration REG_paid field after successful payment and link registration with payment
685
-     *
686
-     * @param EE_Registration $registration
687
-     * @param EE_Payment      $payment
688
-     * @param float           $payment_amount
689
-     * @return void
690
-     * @throws EE_Error
691
-     * @throws InvalidArgumentException
692
-     * @throws InvalidDataTypeException
693
-     * @throws InvalidInterfaceException
694
-     */
695
-    protected function _apply_registration_payment(
696
-        EE_Registration $registration,
697
-        EE_Payment $payment,
698
-        $payment_amount = 0.00
699
-    ) {
700
-        // find any existing reg payment records for this registration and payment
701
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
702
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
703
-        );
704
-        // if existing registration payment exists
705
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
706
-            // then update that record
707
-            $existing_reg_payment->set_amount($payment_amount);
708
-            $existing_reg_payment->save();
709
-        } else {
710
-            // or add new relation between registration and payment and set amount
711
-            $registration->_add_relation_to(
712
-                $payment,
713
-                'Payment',
714
-                array('RPY_amount' => $payment_amount)
715
-            );
716
-            // make it stick
717
-            $registration->save();
718
-        }
719
-    }
720
-
721
-
722
-    /**
723
-     * update registration REG_paid field after refund and link registration with payment
724
-     *
725
-     * @param EE_Registration $registration
726
-     * @param EE_Payment      $payment
727
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
728
-     * @return float
729
-     * @throws EE_Error
730
-     * @throws InvalidArgumentException
731
-     * @throws RuntimeException
732
-     * @throws InvalidDataTypeException
733
-     * @throws InvalidInterfaceException
734
-     */
735
-    public function process_registration_refund(
736
-        EE_Registration $registration,
737
-        EE_Payment $payment,
738
-        $available_refund_amount = 0.00
739
-    ) {
740
-        // EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
741
-        if ($registration->paid() > 0) {
742
-            // ensure $available_refund_amount is NOT negative
743
-            $available_refund_amount = (float) abs($available_refund_amount);
744
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
745
-            $refund_amount = min($available_refund_amount, (float) $registration->paid());
746
-            // update $available_payment_amount
747
-            $available_refund_amount -= $refund_amount;
748
-            // calculate and set new REG_paid
749
-            $registration->set_paid($registration->paid() - $refund_amount);
750
-            // convert payment amount back to a negative value for storage in the db
751
-            $refund_amount = (float) abs($refund_amount) * -1;
752
-            // now save it
753
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
754
-        }
755
-        return $available_refund_amount;
756
-    }
757
-
758
-
759
-    /**
760
-     * Process payments and transaction after payment process completed.
761
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
762
-     * if this request happens to be processing an IPN,
763
-     * then we will also set the Payment Options Reg Step to completed,
764
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
765
-     *
766
-     * @param EE_Transaction $transaction
767
-     * @param EE_Payment     $payment
768
-     * @param bool           $IPN
769
-     * @throws EE_Error
770
-     * @throws InvalidArgumentException
771
-     * @throws ReflectionException
772
-     * @throws RuntimeException
773
-     * @throws InvalidDataTypeException
774
-     * @throws InvalidInterfaceException
775
-     */
776
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
777
-    {
778
-        /** @type EE_Transaction_Processor $transaction_processor */
779
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
780
-        // is the Payment Options Reg Step completed ?
781
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
782
-        // if the Payment Options Reg Step is completed...
783
-        $revisit = $payment_options_step_completed === true;
784
-        // then this is kinda sorta a revisit with regards to payments at least
785
-        $transaction_processor->set_revisit($revisit);
786
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
787
-        if ($IPN
788
-            && $payment_options_step_completed !== true
789
-            && ($payment->is_approved() || $payment->is_pending())
790
-        ) {
791
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
792
-                'payment_options'
793
-            );
794
-        }
795
-        // maybe update status, but don't save transaction just yet
796
-        $transaction->update_status_based_on_total_paid(false);
797
-        // check if 'finalize_registration' step has been completed...
798
-        $finalized = $transaction->reg_step_completed('finalize_registration');
799
-        //  if this is an IPN and the final step has not been initiated
800
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
801
-            // and if it hasn't already been set as being started...
802
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
803
-        }
804
-        $transaction->save();
805
-        // because the above will return false if the final step was not fully completed, we need to check again...
806
-        if ($IPN && $finalized !== false) {
807
-            // and if we are all good to go, then send out notifications
808
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
809
-            // ok, now process the transaction according to the payment
810
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
811
-                $transaction,
812
-                $payment
813
-            );
814
-        }
815
-        // DEBUG LOG
816
-        $payment_method = $payment->payment_method();
817
-        if ($payment_method instanceof EE_Payment_Method) {
818
-            $payment_method_type_obj = $payment_method->type_obj();
819
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
820
-                $gateway = $payment_method_type_obj->get_gateway();
821
-                if ($gateway instanceof EE_Gateway) {
822
-                    $gateway->log(
823
-                        array(
824
-                            'message'               => (string) __('Post Payment Transaction Details', 'event_espresso'),
825
-                            'transaction'           => $transaction->model_field_array(),
826
-                            'finalized'             => $finalized,
827
-                            'IPN'                   => $IPN,
828
-                            'deliver_notifications' => has_filter(
829
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
830
-                            ),
831
-                        ),
832
-                        $payment
833
-                    );
834
-                }
835
-            }
836
-        }
837
-    }
838
-
839
-
840
-    /**
841
-     * Force posts to PayPal to use TLS v1.2. See:
842
-     * https://core.trac.wordpress.org/ticket/36320
843
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
844
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
845
-     * This will affect PayPal standard, pro, express, and Payflow.
846
-     *
847
-     * @param $handle
848
-     * @param $r
849
-     * @param $url
850
-     */
851
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
852
-    {
853
-        if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
854
-            // Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
855
-            // instead of the constant because it might not be defined
856
-            curl_setopt($handle, CURLOPT_SSLVERSION, 6);
857
-        }
858
-    }
21
+	/**
22
+	 * @var EE_Payment_Processor $_instance
23
+	 * @access    private
24
+	 */
25
+	private static $_instance;
26
+
27
+
28
+	/**
29
+	 * @singleton method used to instantiate class object
30
+	 * @access    public
31
+	 * @return EE_Payment_Processor instance
32
+	 */
33
+	public static function instance()
34
+	{
35
+		// check if class object is instantiated
36
+		if (! self::$_instance instanceof EE_Payment_Processor) {
37
+			self::$_instance = new self();
38
+		}
39
+		return self::$_instance;
40
+	}
41
+
42
+
43
+	/**
44
+	 * @return EE_Payment_Processor
45
+	 */
46
+	public static function reset()
47
+	{
48
+		self::$_instance = null;
49
+		return self::instance();
50
+	}
51
+
52
+
53
+	/**
54
+	 *private constructor to prevent direct creation
55
+	 *
56
+	 * @Constructor
57
+	 * @access private
58
+	 */
59
+	private function __construct()
60
+	{
61
+		do_action('AHEE__EE_Payment_Processor__construct');
62
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
63
+	}
64
+
65
+
66
+	/**
67
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
68
+	 * appropriately. Saves the payment that is generated
69
+	 *
70
+	 * @param EE_Payment_Method    $payment_method
71
+	 * @param EE_Transaction       $transaction
72
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
73
+	 *                                           Leave null if payment is for the full amount owing
74
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
75
+	 *                                           Receive_form_submission() should have
76
+	 *                                           already been called on the billing form
77
+	 *                                           (ie, its inputs should have their normalized values set).
78
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
79
+	 *                                           where to go AFTER the offsite gateway
80
+	 * @param string               $method       like 'CART', indicates who the client who called this was
81
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
82
+	 * @param boolean              $update_txn   whether or not to call
83
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
84
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
85
+	 * @return EE_Payment
86
+	 * @throws EE_Error
87
+	 * @throws InvalidArgumentException
88
+	 * @throws ReflectionException
89
+	 * @throws RuntimeException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 */
93
+	public function process_payment(
94
+		EE_Payment_Method $payment_method,
95
+		EE_Transaction $transaction,
96
+		$amount = null,
97
+		$billing_form = null,
98
+		$return_url = null,
99
+		$method = 'CART',
100
+		$by_admin = false,
101
+		$update_txn = true,
102
+		$cancel_url = ''
103
+	) {
104
+		if ((float) $amount < 0) {
105
+			throw new EE_Error(
106
+				sprintf(
107
+					__(
108
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
109
+						'event_espresso'
110
+					),
111
+					$amount,
112
+					$transaction->ID()
113
+				)
114
+			);
115
+		}
116
+		// verify payment method
117
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
118
+			$payment_method,
119
+			true
120
+		);
121
+		// verify transaction
122
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
123
+		$transaction->set_payment_method_ID($payment_method->ID());
124
+		// verify payment method type
125
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
126
+			$payment = $payment_method->type_obj()->process_payment(
127
+				$transaction,
128
+				min($amount, $transaction->remaining()), // make sure we don't overcharge
129
+				$billing_form,
130
+				$return_url,
131
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
132
+				$method,
133
+				$by_admin
134
+			);
135
+			// check if payment method uses an off-site gateway
136
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
137
+				// don't process payments for off-site gateways yet because no payment has occurred yet
138
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
139
+			}
140
+			return $payment;
141
+		}
142
+		EE_Error::add_error(
143
+			sprintf(
144
+				__(
145
+					'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
146
+					'event_espresso'
147
+				),
148
+				'<br/>',
149
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
150
+			),
151
+			__FILE__,
152
+			__FUNCTION__,
153
+			__LINE__
154
+		);
155
+		return null;
156
+	}
157
+
158
+
159
+	/**
160
+	 * @param EE_Transaction|int $transaction
161
+	 * @param EE_Payment_Method  $payment_method
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws InvalidInterfaceException
167
+	 */
168
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
169
+	{
170
+		/** @type \EE_Transaction $transaction */
171
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
172
+		$primary_reg = $transaction->primary_registration();
173
+		if (! $primary_reg instanceof EE_Registration) {
174
+			throw new EE_Error(
175
+				sprintf(
176
+					__(
177
+						'Cannot get IPN URL for transaction with ID %d because it has no primary registration',
178
+						'event_espresso'
179
+					),
180
+					$transaction->ID()
181
+				)
182
+			);
183
+		}
184
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj(
185
+			$payment_method,
186
+			true
187
+		);
188
+		$url = add_query_arg(
189
+			array(
190
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
191
+				'ee_payment_method' => $payment_method->slug(),
192
+			),
193
+			EE_Registry::instance()->CFG->core->txn_page_url()
194
+		);
195
+		return $url;
196
+	}
197
+
198
+
199
+	/**
200
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
201
+	 * we can easily find what registration the IPN is for and what payment method.
202
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
203
+	 * If a payment is found for the IPN info, it is saved.
204
+	 *
205
+	 * @param array              $_req_data            eg $_REQUEST
206
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
207
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
208
+	 * @param boolean            $update_txn           whether or not to call
209
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
210
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
211
+	 *                                                 or is processed manually ( false like Mijireh )
212
+	 * @throws EE_Error
213
+	 * @throws Exception
214
+	 * @return EE_Payment
215
+	 * @throws \RuntimeException
216
+	 * @throws \ReflectionException
217
+	 * @throws \InvalidArgumentException
218
+	 * @throws InvalidInterfaceException
219
+	 * @throws InvalidDataTypeException
220
+	 */
221
+	public function process_ipn(
222
+		$_req_data,
223
+		$transaction = null,
224
+		$payment_method = null,
225
+		$update_txn = true,
226
+		$separate_IPN_request = true
227
+	) {
228
+		EE_Registry::instance()->load_model('Change_Log');
229
+		$_req_data = $this->_remove_unusable_characters_from_array((array) $_req_data);
230
+		EE_Processor_Base::set_IPN($separate_IPN_request);
231
+		$obj_for_log = null;
232
+		if ($transaction instanceof EE_Transaction) {
233
+			$obj_for_log = $transaction;
234
+			if ($payment_method instanceof EE_Payment_Method) {
235
+				$obj_for_log = EEM_Payment::instance()->get_one(
236
+					array(
237
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
238
+						'order_by' => array('PAY_timestamp' => 'desc'),
239
+					)
240
+				);
241
+			}
242
+		} elseif ($payment_method instanceof EE_Payment) {
243
+			$obj_for_log = $payment_method;
244
+		}
245
+		$log = EEM_Change_Log::instance()->log(
246
+			EEM_Change_Log::type_gateway,
247
+			array('IPN data received' => $_req_data),
248
+			$obj_for_log
249
+		);
250
+		try {
251
+			/**
252
+			 * @var EE_Payment $payment
253
+			 */
254
+			$payment = null;
255
+			if ($transaction && $payment_method) {
256
+				/** @type EE_Transaction $transaction */
257
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
258
+				/** @type EE_Payment_Method $payment_method */
259
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
260
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
261
+					try {
262
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
263
+						$log->set_object($payment);
264
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
265
+						EEM_Change_Log::instance()->log(
266
+							EEM_Change_Log::type_gateway,
267
+							array(
268
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
269
+								'current_url' => EEH_URL::current_url(),
270
+								'payment'     => $e->getPaymentProperties(),
271
+								'IPN_data'    => $e->getIpnData(),
272
+							),
273
+							$obj_for_log
274
+						);
275
+						return $e->getPayment();
276
+					}
277
+				} else {
278
+					// not a payment
279
+					EE_Error::add_error(
280
+						sprintf(
281
+							__(
282
+								'A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.',
283
+								'event_espresso'
284
+							),
285
+							'<br/>',
286
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
287
+						),
288
+						__FILE__,
289
+						__FUNCTION__,
290
+						__LINE__
291
+					);
292
+				}
293
+			} else {
294
+				// that's actually pretty ok. The IPN just wasn't able
295
+				// to identify which transaction or payment method this was for
296
+				// give all active payment methods a chance to claim it
297
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
298
+				foreach ($active_payment_methods as $active_payment_method) {
299
+					try {
300
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
301
+						$payment_method = $active_payment_method;
302
+						EEM_Change_Log::instance()->log(
303
+							EEM_Change_Log::type_gateway,
304
+							array('IPN data' => $_req_data),
305
+							$payment
306
+						);
307
+						break;
308
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
309
+						EEM_Change_Log::instance()->log(
310
+							EEM_Change_Log::type_gateway,
311
+							array(
312
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
313
+								'current_url' => EEH_URL::current_url(),
314
+								'payment'     => $e->getPaymentProperties(),
315
+								'IPN_data'    => $e->getIpnData(),
316
+							),
317
+							$obj_for_log
318
+						);
319
+						return $e->getPayment();
320
+					} catch (EE_Error $e) {
321
+						// that's fine- it apparently couldn't handle the IPN
322
+					}
323
+				}
324
+			}
325
+			// EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
326
+			if ($payment instanceof EE_Payment) {
327
+				$payment->save();
328
+				//  update the TXN
329
+				$this->update_txn_based_on_payment(
330
+					$transaction,
331
+					$payment,
332
+					$update_txn,
333
+					$separate_IPN_request
334
+				);
335
+			} else {
336
+				// we couldn't find the payment for this IPN... let's try and log at least SOMETHING
337
+				if ($payment_method) {
338
+					EEM_Change_Log::instance()->log(
339
+						EEM_Change_Log::type_gateway,
340
+						array('IPN data' => $_req_data),
341
+						$payment_method
342
+					);
343
+				} elseif ($transaction) {
344
+					EEM_Change_Log::instance()->log(
345
+						EEM_Change_Log::type_gateway,
346
+						array('IPN data' => $_req_data),
347
+						$transaction
348
+					);
349
+				}
350
+			}
351
+			return $payment;
352
+		} catch (EE_Error $e) {
353
+			do_action(
354
+				'AHEE__log',
355
+				__FILE__,
356
+				__FUNCTION__,
357
+				sprintf(
358
+					__(
359
+						'Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"',
360
+						'event_espresso'
361
+					),
362
+					print_r($transaction, true),
363
+					print_r($_req_data, true),
364
+					$e->getMessage()
365
+				)
366
+			);
367
+			throw $e;
368
+		}
369
+	}
370
+
371
+
372
+	/**
373
+	 * Removes any non-printable illegal characters from the input,
374
+	 * which might cause a raucous when trying to insert into the database
375
+	 *
376
+	 * @param  array $request_data
377
+	 * @return array
378
+	 */
379
+	protected function _remove_unusable_characters_from_array(array $request_data)
380
+	{
381
+		$return_data = array();
382
+		foreach ($request_data as $key => $value) {
383
+			$return_data[ $this->_remove_unusable_characters($key) ] = $this->_remove_unusable_characters(
384
+				$value
385
+			);
386
+		}
387
+		return $return_data;
388
+	}
389
+
390
+
391
+	/**
392
+	 * Removes any non-printable illegal characters from the input,
393
+	 * which might cause a raucous when trying to insert into the database
394
+	 *
395
+	 * @param string $request_data
396
+	 * @return string
397
+	 */
398
+	protected function _remove_unusable_characters($request_data)
399
+	{
400
+		return preg_replace('/[^[:print:]]/', '', $request_data);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Should be called just before displaying the payment attempt results to the user,
406
+	 * when the payment attempt has finished. Some payment methods may have special
407
+	 * logic to perform here. For example, if process_payment() happens on a special request
408
+	 * and then the user is redirected to a page that displays the payment's status, this
409
+	 * should be called while loading the page that displays the payment's status. If the user is
410
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
411
+	 * provider.
412
+	 *
413
+	 * @param EE_Transaction|int $transaction
414
+	 * @param bool               $update_txn whether or not to call
415
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
416
+	 * @return EE_Payment
417
+	 * @throws EE_Error
418
+	 * @throws InvalidArgumentException
419
+	 * @throws ReflectionException
420
+	 * @throws RuntimeException
421
+	 * @throws InvalidDataTypeException
422
+	 * @throws InvalidInterfaceException
423
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
424
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
425
+	 */
426
+	public function finalize_payment_for($transaction, $update_txn = true)
427
+	{
428
+		/** @var $transaction EE_Transaction */
429
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
430
+		$last_payment_method = $transaction->payment_method();
431
+		if ($last_payment_method instanceof EE_Payment_Method) {
432
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
433
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
434
+			return $payment;
435
+		}
436
+		return null;
437
+	}
438
+
439
+
440
+	/**
441
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
442
+	 *
443
+	 * @param EE_Payment_Method $payment_method
444
+	 * @param EE_Payment        $payment_to_refund
445
+	 * @param array             $refund_info
446
+	 * @return EE_Payment
447
+	 * @throws EE_Error
448
+	 * @throws InvalidArgumentException
449
+	 * @throws ReflectionException
450
+	 * @throws RuntimeException
451
+	 * @throws InvalidDataTypeException
452
+	 * @throws InvalidInterfaceException
453
+	 */
454
+	public function process_refund(
455
+		EE_Payment_Method $payment_method,
456
+		EE_Payment $payment_to_refund,
457
+		array $refund_info = array()
458
+	) {
459
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
460
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
461
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
462
+		}
463
+		return $payment_to_refund;
464
+	}
465
+
466
+
467
+	/**
468
+	 * This should be called each time there may have been an update to a
469
+	 * payment on a transaction (ie, we asked for a payment to process a
470
+	 * payment for a transaction, or we told a payment method about an IPN, or
471
+	 * we told a payment method to
472
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
473
+	 * process a refund. This should handle firing the correct hooks to
474
+	 * indicate
475
+	 * what exactly happened and updating the transaction appropriately). This
476
+	 * could be integrated directly into EE_Transaction upon save, but we want
477
+	 * this logic to be separate from 'normal' plain-jane saving and updating
478
+	 * of transactions and payments, and to be tied to payment processing.
479
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
480
+	 * of previous code to decide whether or not to save (because the payment passed into
481
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
482
+	 * in which case we only want that payment object for some temporary usage during this request,
483
+	 * but we don't want it to be saved).
484
+	 *
485
+	 * @param EE_Transaction|int $transaction
486
+	 * @param EE_Payment         $payment
487
+	 * @param boolean            $update_txn
488
+	 *                        whether or not to call
489
+	 *                        EE_Transaction_Processor::
490
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
491
+	 *                        (you can save 1 DB query if you know you're going
492
+	 *                        to save it later instead)
493
+	 * @param bool               $IPN
494
+	 *                        if processing IPNs or other similar payment
495
+	 *                        related activities that occur in alternate
496
+	 *                        requests than the main one that is processing the
497
+	 *                        TXN, then set this to true to check whether the
498
+	 *                        TXN is locked before updating
499
+	 * @throws EE_Error
500
+	 * @throws InvalidArgumentException
501
+	 * @throws ReflectionException
502
+	 * @throws RuntimeException
503
+	 * @throws InvalidDataTypeException
504
+	 * @throws InvalidInterfaceException
505
+	 */
506
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
507
+	{
508
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
509
+		/** @type EE_Transaction $transaction */
510
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
511
+		// can we freely update the TXN at this moment?
512
+		if ($IPN && $transaction->is_locked()) {
513
+			// don't update the transaction at this exact moment
514
+			// because the TXN is active in another request
515
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
516
+				time(),
517
+				$transaction->ID(),
518
+				$payment->ID()
519
+			);
520
+		} else {
521
+			// verify payment and that it has been saved
522
+			if ($payment instanceof EE_Payment && $payment->ID()) {
523
+				if ($payment->payment_method() instanceof EE_Payment_Method
524
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
525
+				) {
526
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
527
+					// update TXN registrations with payment info
528
+					$this->process_registration_payments($transaction, $payment);
529
+				}
530
+				$do_action = $payment->just_approved()
531
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
532
+					: $do_action;
533
+			} else {
534
+				// send out notifications
535
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
536
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
537
+			}
538
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
539
+				/** @type EE_Transaction_Payments $transaction_payments */
540
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
541
+				// set new value for total paid
542
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
543
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
544
+				if ($update_txn) {
545
+					$this->_post_payment_processing($transaction, $payment, $IPN);
546
+				}
547
+			}
548
+			// granular hook for others to use.
549
+			do_action($do_action, $transaction, $payment);
550
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
551
+			// global hook for others to use.
552
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
553
+		}
554
+	}
555
+
556
+
557
+	/**
558
+	 * update registrations REG_paid field after successful payment and link registrations with payment
559
+	 *
560
+	 * @param EE_Transaction    $transaction
561
+	 * @param EE_Payment        $payment
562
+	 * @param EE_Registration[] $registrations
563
+	 * @throws EE_Error
564
+	 * @throws InvalidArgumentException
565
+	 * @throws RuntimeException
566
+	 * @throws InvalidDataTypeException
567
+	 * @throws InvalidInterfaceException
568
+	 */
569
+	public function process_registration_payments(
570
+		EE_Transaction $transaction,
571
+		EE_Payment $payment,
572
+		array $registrations = array()
573
+	) {
574
+		// only process if payment was successful
575
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
576
+			return;
577
+		}
578
+		// EEM_Registration::instance()->show_next_x_db_queries();
579
+		if (empty($registrations)) {
580
+			// find registrations with monies owing that can receive a payment
581
+			$registrations = $transaction->registrations(
582
+				array(
583
+					array(
584
+						// only these reg statuses can receive payments
585
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
586
+						'REG_final_price'  => array('!=', 0),
587
+						'REG_final_price*' => array('!=', 'REG_paid', true),
588
+					),
589
+				)
590
+			);
591
+		}
592
+		// still nothing ??!??
593
+		if (empty($registrations)) {
594
+			return;
595
+		}
596
+		// todo: break out the following logic into a separate strategy class
597
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
598
+		// todo: which would apply payments using the capitalist "first come first paid" approach
599
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
600
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
601
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
602
+		$refund = $payment->is_a_refund();
603
+		// how much is available to apply to registrations?
604
+		$available_payment_amount = abs($payment->amount());
605
+		foreach ($registrations as $registration) {
606
+			if ($registration instanceof EE_Registration) {
607
+				// nothing left?
608
+				if ($available_payment_amount <= 0) {
609
+					break;
610
+				}
611
+				if ($refund) {
612
+					$available_payment_amount = $this->process_registration_refund(
613
+						$registration,
614
+						$payment,
615
+						$available_payment_amount
616
+					);
617
+				} else {
618
+					$available_payment_amount = $this->process_registration_payment(
619
+						$registration,
620
+						$payment,
621
+						$available_payment_amount
622
+					);
623
+				}
624
+			}
625
+		}
626
+		if ($available_payment_amount > 0
627
+			&& apply_filters(
628
+				'FHEE__EE_Payment_Processor__process_registration_payments__display_notifications',
629
+				false
630
+			)) {
631
+			EE_Error::add_attention(
632
+				sprintf(
633
+					__(
634
+						'A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
635
+						'event_espresso'
636
+					),
637
+					EEH_Template::format_currency($available_payment_amount),
638
+					implode(', ', array_keys($registrations)),
639
+					'<br/>',
640
+					EEH_Template::format_currency($payment->amount())
641
+				),
642
+				__FILE__,
643
+				__FUNCTION__,
644
+				__LINE__
645
+			);
646
+		}
647
+	}
648
+
649
+
650
+	/**
651
+	 * update registration REG_paid field after successful payment and link registration with payment
652
+	 *
653
+	 * @param EE_Registration $registration
654
+	 * @param EE_Payment      $payment
655
+	 * @param float           $available_payment_amount
656
+	 * @return float
657
+	 * @throws EE_Error
658
+	 * @throws InvalidArgumentException
659
+	 * @throws RuntimeException
660
+	 * @throws InvalidDataTypeException
661
+	 * @throws InvalidInterfaceException
662
+	 */
663
+	public function process_registration_payment(
664
+		EE_Registration $registration,
665
+		EE_Payment $payment,
666
+		$available_payment_amount = 0.00
667
+	) {
668
+		$owing = $registration->final_price() - $registration->paid();
669
+		if ($owing > 0) {
670
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
671
+			$payment_amount = min($available_payment_amount, $owing);
672
+			// update $available_payment_amount
673
+			$available_payment_amount -= $payment_amount;
674
+			// calculate and set new REG_paid
675
+			$registration->set_paid($registration->paid() + $payment_amount);
676
+			// now save it
677
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
678
+		}
679
+		return $available_payment_amount;
680
+	}
681
+
682
+
683
+	/**
684
+	 * update registration REG_paid field after successful payment and link registration with payment
685
+	 *
686
+	 * @param EE_Registration $registration
687
+	 * @param EE_Payment      $payment
688
+	 * @param float           $payment_amount
689
+	 * @return void
690
+	 * @throws EE_Error
691
+	 * @throws InvalidArgumentException
692
+	 * @throws InvalidDataTypeException
693
+	 * @throws InvalidInterfaceException
694
+	 */
695
+	protected function _apply_registration_payment(
696
+		EE_Registration $registration,
697
+		EE_Payment $payment,
698
+		$payment_amount = 0.00
699
+	) {
700
+		// find any existing reg payment records for this registration and payment
701
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
702
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
703
+		);
704
+		// if existing registration payment exists
705
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
706
+			// then update that record
707
+			$existing_reg_payment->set_amount($payment_amount);
708
+			$existing_reg_payment->save();
709
+		} else {
710
+			// or add new relation between registration and payment and set amount
711
+			$registration->_add_relation_to(
712
+				$payment,
713
+				'Payment',
714
+				array('RPY_amount' => $payment_amount)
715
+			);
716
+			// make it stick
717
+			$registration->save();
718
+		}
719
+	}
720
+
721
+
722
+	/**
723
+	 * update registration REG_paid field after refund and link registration with payment
724
+	 *
725
+	 * @param EE_Registration $registration
726
+	 * @param EE_Payment      $payment
727
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
728
+	 * @return float
729
+	 * @throws EE_Error
730
+	 * @throws InvalidArgumentException
731
+	 * @throws RuntimeException
732
+	 * @throws InvalidDataTypeException
733
+	 * @throws InvalidInterfaceException
734
+	 */
735
+	public function process_registration_refund(
736
+		EE_Registration $registration,
737
+		EE_Payment $payment,
738
+		$available_refund_amount = 0.00
739
+	) {
740
+		// EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
741
+		if ($registration->paid() > 0) {
742
+			// ensure $available_refund_amount is NOT negative
743
+			$available_refund_amount = (float) abs($available_refund_amount);
744
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
745
+			$refund_amount = min($available_refund_amount, (float) $registration->paid());
746
+			// update $available_payment_amount
747
+			$available_refund_amount -= $refund_amount;
748
+			// calculate and set new REG_paid
749
+			$registration->set_paid($registration->paid() - $refund_amount);
750
+			// convert payment amount back to a negative value for storage in the db
751
+			$refund_amount = (float) abs($refund_amount) * -1;
752
+			// now save it
753
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
754
+		}
755
+		return $available_refund_amount;
756
+	}
757
+
758
+
759
+	/**
760
+	 * Process payments and transaction after payment process completed.
761
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
762
+	 * if this request happens to be processing an IPN,
763
+	 * then we will also set the Payment Options Reg Step to completed,
764
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
765
+	 *
766
+	 * @param EE_Transaction $transaction
767
+	 * @param EE_Payment     $payment
768
+	 * @param bool           $IPN
769
+	 * @throws EE_Error
770
+	 * @throws InvalidArgumentException
771
+	 * @throws ReflectionException
772
+	 * @throws RuntimeException
773
+	 * @throws InvalidDataTypeException
774
+	 * @throws InvalidInterfaceException
775
+	 */
776
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
777
+	{
778
+		/** @type EE_Transaction_Processor $transaction_processor */
779
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
780
+		// is the Payment Options Reg Step completed ?
781
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
782
+		// if the Payment Options Reg Step is completed...
783
+		$revisit = $payment_options_step_completed === true;
784
+		// then this is kinda sorta a revisit with regards to payments at least
785
+		$transaction_processor->set_revisit($revisit);
786
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
787
+		if ($IPN
788
+			&& $payment_options_step_completed !== true
789
+			&& ($payment->is_approved() || $payment->is_pending())
790
+		) {
791
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
792
+				'payment_options'
793
+			);
794
+		}
795
+		// maybe update status, but don't save transaction just yet
796
+		$transaction->update_status_based_on_total_paid(false);
797
+		// check if 'finalize_registration' step has been completed...
798
+		$finalized = $transaction->reg_step_completed('finalize_registration');
799
+		//  if this is an IPN and the final step has not been initiated
800
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
801
+			// and if it hasn't already been set as being started...
802
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
803
+		}
804
+		$transaction->save();
805
+		// because the above will return false if the final step was not fully completed, we need to check again...
806
+		if ($IPN && $finalized !== false) {
807
+			// and if we are all good to go, then send out notifications
808
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
809
+			// ok, now process the transaction according to the payment
810
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
811
+				$transaction,
812
+				$payment
813
+			);
814
+		}
815
+		// DEBUG LOG
816
+		$payment_method = $payment->payment_method();
817
+		if ($payment_method instanceof EE_Payment_Method) {
818
+			$payment_method_type_obj = $payment_method->type_obj();
819
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
820
+				$gateway = $payment_method_type_obj->get_gateway();
821
+				if ($gateway instanceof EE_Gateway) {
822
+					$gateway->log(
823
+						array(
824
+							'message'               => (string) __('Post Payment Transaction Details', 'event_espresso'),
825
+							'transaction'           => $transaction->model_field_array(),
826
+							'finalized'             => $finalized,
827
+							'IPN'                   => $IPN,
828
+							'deliver_notifications' => has_filter(
829
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
830
+							),
831
+						),
832
+						$payment
833
+					);
834
+				}
835
+			}
836
+		}
837
+	}
838
+
839
+
840
+	/**
841
+	 * Force posts to PayPal to use TLS v1.2. See:
842
+	 * https://core.trac.wordpress.org/ticket/36320
843
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
844
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
845
+	 * This will affect PayPal standard, pro, express, and Payflow.
846
+	 *
847
+	 * @param $handle
848
+	 * @param $r
849
+	 * @param $url
850
+	 */
851
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
852
+	{
853
+		if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
854
+			// Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
855
+			// instead of the constant because it might not be defined
856
+			curl_setopt($handle, CURLOPT_SSLVERSION, 6);
857
+		}
858
+	}
859 859
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 1 patch
Indentation   +666 added lines, -666 removed lines patch added patch discarded remove patch
@@ -11,674 +11,674 @@
 block discarded – undo
11 11
  */
12 12
 // Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
13 13
 if (! function_exists('mb_strcut')) {
14
-    /**
15
-     * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
16
-     * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
17
-     * @param $string
18
-     * @param $start
19
-     * @param $length
20
-     * @return bool|string
21
-     */
22
-    function mb_strcut($string, $start, $length = null)
23
-    {
24
-        return mb_substr($string, $start, $length);
25
-    }
14
+	/**
15
+	 * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
16
+	 * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
17
+	 * @param $string
18
+	 * @param $start
19
+	 * @param $length
20
+	 * @return bool|string
21
+	 */
22
+	function mb_strcut($string, $start, $length = null)
23
+	{
24
+		return mb_substr($string, $start, $length);
25
+	}
26 26
 }
27 27
 class EEG_Paypal_Express extends EE_Offsite_Gateway
28 28
 {
29 29
 
30
-    /**
31
-     * Merchant API Username.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_api_username;
36
-
37
-    /**
38
-     * Merchant API Password.
39
-     *
40
-     * @var string
41
-     */
42
-    protected $_api_password;
43
-
44
-    /**
45
-     * API Signature.
46
-     *
47
-     * @var string
48
-     */
49
-    protected $_api_signature;
50
-
51
-    /**
52
-     * Request Shipping address on PP checkout page.
53
-     *
54
-     * @var string
55
-     */
56
-    protected $_request_shipping_addr;
57
-
58
-    /**
59
-     * Business/personal logo.
60
-     *
61
-     * @var string
62
-     */
63
-    protected $_image_url;
64
-
65
-    /**
66
-     * gateway URL variable
67
-     *
68
-     * @var string
69
-     */
70
-    protected $_base_gateway_url = '';
71
-
72
-
73
-
74
-    /**
75
-     * EEG_Paypal_Express constructor.
76
-     */
77
-    public function __construct()
78
-    {
79
-        $this->_currencies_supported = array(
80
-            'USD',
81
-            'AUD',
82
-            'BRL',
83
-            'CAD',
84
-            'CZK',
85
-            'DKK',
86
-            'EUR',
87
-            'HKD',
88
-            'HUF',
89
-            'ILS',
90
-            'JPY',
91
-            'MYR',
92
-            'MXN',
93
-            'NOK',
94
-            'NZD',
95
-            'PHP',
96
-            'PLN',
97
-            'GBP',
98
-            'RUB',
99
-            'SGD',
100
-            'SEK',
101
-            'CHF',
102
-            'TWD',
103
-            'THB',
104
-            'TRY',
105
-            'INR',
106
-        );
107
-        parent::__construct();
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Sets the gateway URL variable based on whether debug mode is enabled or not.
114
-     *
115
-     * @param array $settings_array
116
-     */
117
-    public function set_settings($settings_array)
118
-    {
119
-        parent::set_settings($settings_array);
120
-        // Redirect URL.
121
-        $this->_base_gateway_url = $this->_debug_mode
122
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
123
-            : 'https://api-3t.paypal.com/nvp';
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * @param EEI_Payment $payment
130
-     * @param array       $billing_info
131
-     * @param string      $return_url
132
-     * @param string      $notify_url
133
-     * @param string      $cancel_url
134
-     * @return \EE_Payment|\EEI_Payment
135
-     * @throws \EE_Error
136
-     */
137
-    public function set_redirection_info(
138
-        $payment,
139
-        $billing_info = array(),
140
-        $return_url = null,
141
-        $notify_url = null,
142
-        $cancel_url = null
143
-    ) {
144
-        if (! $payment instanceof EEI_Payment) {
145
-            $payment->set_gateway_response(
146
-                esc_html__(
147
-                    'Error. No associated payment was found.',
148
-                    'event_espresso'
149
-                )
150
-            );
151
-            $payment->set_status($this->_pay_model->failed_status());
152
-            return $payment;
153
-        }
154
-        $transaction = $payment->transaction();
155
-        if (! $transaction instanceof EEI_Transaction) {
156
-            $payment->set_gateway_response(
157
-                esc_html__(
158
-                    'Could not process this payment because it has no associated transaction.',
159
-                    'event_espresso'
160
-                )
161
-            );
162
-            $payment->set_status($this->_pay_model->failed_status());
163
-            return $payment;
164
-        }
165
-        $gateway_formatter = $this->_get_gateway_formatter();
166
-        $order_description = mb_strcut($gateway_formatter->formatOrderDescription($payment), 0, 127);
167
-        $primary_registration = $transaction->primary_registration();
168
-        $primary_attendee = $primary_registration instanceof EE_Registration
169
-            ? $primary_registration->attendee()
170
-            : false;
171
-        $locale = explode('-', get_bloginfo('language'));
172
-        // Gather request parameters.
173
-        $token_request_dtls = array(
174
-            'METHOD'                         => 'SetExpressCheckout',
175
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
176
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
177
-            'PAYMENTREQUEST_0_DESC'          => $order_description,
178
-            'RETURNURL'                      => $return_url,
179
-            'CANCELURL'                      => $cancel_url,
180
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
181
-            // Buyer does not need to create a PayPal account to check out.
182
-            // This is referred to as PayPal Account Optional.
183
-            'SOLUTIONTYPE'                   => 'Sole',
184
-            // Locale of the pages displayed by PayPal during Express Checkout.
185
-            'LOCALECODE'                     => $locale[1]
186
-        );
187
-        // Show itemized list.
188
-        $itemized_list = $this->itemize_list($payment, $transaction);
189
-        $token_request_dtls = array_merge($token_request_dtls, $itemized_list);
190
-        // Automatically filling out shipping and contact information.
191
-        if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
192
-            // If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
193
-            $token_request_dtls['NOSHIPPING'] = '2';
194
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
195
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
196
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
197
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTATE'] = $primary_attendee->state_abbrev();
198
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
199
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
200
-            $token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
201
-            $token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
202
-        } elseif (! $this->_request_shipping_addr) {
203
-            // Do not request shipping details on the PP Checkout page.
204
-            $token_request_dtls['NOSHIPPING'] = '1';
205
-            $token_request_dtls['REQCONFIRMSHIPPING'] = '0';
206
-        }
207
-        // Used a business/personal logo on the PayPal page.
208
-        if (! empty($this->_image_url)) {
209
-            $token_request_dtls['LOGOIMG'] = $this->_image_url;
210
-        }
211
-        $token_request_dtls = apply_filters(
212
-            'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
213
-            $token_request_dtls,
214
-            $this
215
-        );
216
-        // Request PayPal token.
217
-        $token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
218
-        $token_rstatus = $this->_ppExpress_check_response($token_request_response);
219
-        $response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args']))
220
-            ? $token_rstatus['args']
221
-            : array();
222
-        if ($token_rstatus['status']) {
223
-            // We got the Token so we may continue with the payment and redirect the client.
224
-            $payment->set_details($response_args);
225
-            $gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
226
-            $payment->set_redirect_url(
227
-                $gateway_url
228
-                . '/checkoutnow?useraction=commit&cmd=_express-checkout&token='
229
-                . $response_args['TOKEN']
230
-            );
231
-        } else {
232
-            if (isset($response_args['L_ERRORCODE'])) {
233
-                $payment->set_gateway_response($response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']);
234
-            } else {
235
-                $payment->set_gateway_response(
236
-                    esc_html__(
237
-                        'Error occurred while trying to setup the Express Checkout.',
238
-                        'event_espresso'
239
-                    )
240
-                );
241
-            }
242
-            $payment->set_details($response_args);
243
-            $payment->set_status($this->_pay_model->failed_status());
244
-        }
245
-        return $payment;
246
-    }
247
-
248
-
249
-
250
-    /**
251
-     * @param array           $update_info {
252
-     * @type string           $gateway_txn_id
253
-     * @type string status an EEMI_Payment status
254
-     *                                     }
255
-     * @param EEI_Transaction $transaction
256
-     * @return EEI_Payment
257
-     */
258
-    public function handle_payment_update($update_info, $transaction)
259
-    {
260
-        $payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
261
-        if ($payment instanceof EEI_Payment) {
262
-            $this->log(array('Return from Authorization' => $update_info), $payment);
263
-            $transaction = $payment->transaction();
264
-            if (! $transaction instanceof EEI_Transaction) {
265
-                $payment->set_gateway_response(
266
-                    esc_html__(
267
-                        'Could not process this payment because it has no associated transaction.',
268
-                        'event_espresso'
269
-                    )
270
-                );
271
-                $payment->set_status($this->_pay_model->failed_status());
272
-                return $payment;
273
-            }
274
-            $primary_registrant = $transaction->primary_registration();
275
-            $payment_details = $payment->details();
276
-            // Check if we still have the token.
277
-            if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
278
-                $payment->set_status($this->_pay_model->failed_status());
279
-                return $payment;
280
-            }
281
-            $cdetails_request_dtls = array(
282
-                'METHOD' => 'GetExpressCheckoutDetails',
283
-                'TOKEN'  => $payment_details['TOKEN'],
284
-            );
285
-            // Request Customer Details.
286
-            $cdetails_request_response = $this->_ppExpress_request(
287
-                $cdetails_request_dtls,
288
-                'Customer Details',
289
-                $payment
290
-            );
291
-            $cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
292
-            $cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']))
293
-                ? $cdetails_rstatus['args']
294
-                : array();
295
-            if ($cdetails_rstatus['status']) {
296
-                // We got the PayerID so now we can Complete the transaction.
297
-                $docheckout_request_dtls = array(
298
-                    'METHOD'                         => 'DoExpressCheckoutPayment',
299
-                    'PAYERID'                        => $cdata_response_args['PAYERID'],
300
-                    'TOKEN'                          => $payment_details['TOKEN'],
301
-                    'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
302
-                    'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
303
-                    'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
304
-                );
305
-                 // Include itemized list.
306
-                $itemized_list = $this->itemize_list(
307
-                    $payment,
308
-                    $transaction,
309
-                    $cdata_response_args
310
-                );
311
-                $docheckout_request_dtls = array_merge($docheckout_request_dtls, $itemized_list);
312
-                // Payment Checkout/Capture.
313
-                $docheckout_request_response = $this->_ppExpress_request(
314
-                    $docheckout_request_dtls,
315
-                    'Do Payment',
316
-                    $payment
317
-                );
318
-                $docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
319
-                $docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']))
320
-                    ? $docheckout_rstatus['args']
321
-                    : array();
322
-                if ($docheckout_rstatus['status']) {
323
-                    // All is well, payment approved.
324
-                    $primary_registration_code = $primary_registrant instanceof EE_Registration ?
325
-                        $primary_registrant->reg_code()
326
-                        : '';
327
-                    $payment->set_extra_accntng($primary_registration_code);
328
-                    $payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT'])
329
-                        ? (float) $docheckout_response_args['PAYMENTINFO_0_AMT']
330
-                        : 0);
331
-                    $payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'])
332
-                        ? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']
333
-                        : null);
334
-                    $payment->set_details($cdata_response_args);
335
-                    $payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK'])
336
-                        ? $docheckout_response_args['PAYMENTINFO_0_ACK']
337
-                        : '');
338
-                    $payment->set_status($this->_pay_model->approved_status());
339
-                } else {
340
-                    if (isset($docheckout_response_args['L_ERRORCODE'])) {
341
-                        $payment->set_gateway_response(
342
-                            $docheckout_response_args['L_ERRORCODE']
343
-                            . '; '
344
-                            . $docheckout_response_args['L_SHORTMESSAGE']
345
-                        );
346
-                    } else {
347
-                        $payment->set_gateway_response(
348
-                            esc_html__(
349
-                                'Error occurred while trying to Capture the funds.',
350
-                                'event_espresso'
351
-                            )
352
-                        );
353
-                    }
354
-                    $payment->set_details($docheckout_response_args);
355
-                    $payment->set_status($this->_pay_model->declined_status());
356
-                }
357
-            } else {
358
-                if (isset($cdata_response_args['L_ERRORCODE'])) {
359
-                    $payment->set_gateway_response(
360
-                        $cdata_response_args['L_ERRORCODE']
361
-                        . '; '
362
-                        . $cdata_response_args['L_SHORTMESSAGE']
363
-                    );
364
-                } else {
365
-                    $payment->set_gateway_response(
366
-                        esc_html__(
367
-                            'Error occurred while trying to get payment Details from PayPal.',
368
-                            'event_espresso'
369
-                        )
370
-                    );
371
-                }
372
-                $payment->set_details($cdata_response_args);
373
-                $payment->set_status($this->_pay_model->failed_status());
374
-            }
375
-        } else {
376
-            $payment->set_gateway_response(
377
-                esc_html__(
378
-                    'Error occurred while trying to process the payment.',
379
-                    'event_espresso'
380
-                )
381
-            );
382
-            $payment->set_status($this->_pay_model->failed_status());
383
-        }
384
-        return $payment;
385
-    }
386
-
387
-
388
-
389
-    /**
390
-     *  Make a list of items that are in the giver transaction.
391
-     *
392
-     * @param EEI_Payment     $payment
393
-     * @param EEI_Transaction $transaction
394
-     * @param array           $request_response_args Data from a previous communication with PP.
395
-     * @return array
396
-     */
397
-    public function itemize_list(EEI_Payment $payment, EEI_Transaction $transaction, $request_response_args = array())
398
-    {
399
-        $itemized_list = array();
400
-        $gateway_formatter = $this->_get_gateway_formatter();
401
-        // If we have data from a previous communication with PP (on this transaction) we may use that for our list...
402
-        if (! empty($request_response_args)
403
-            && array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
404
-            && array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
405
-        ) {
406
-            foreach ($request_response_args as $arg_key => $arg_val) {
407
-                if (strpos($arg_key, 'PAYMENTREQUEST_') !== false
408
-                    && strpos($arg_key, 'NOTIFYURL') === false
409
-                ) {
410
-                    $itemized_list[ $arg_key ] = $arg_val;
411
-                }
412
-            }
413
-            // If we got only a few Items then something is not right.
414
-            if (count($itemized_list) > 2) {
415
-                return $itemized_list;
416
-            } else {
417
-                if (WP_DEBUG) {
418
-                    throw new EE_Error(
419
-                        sprintf(
420
-                            esc_html__(
421
-                                // @codingStandardsIgnoreStart
422
-                                'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
423
-                                // @codingStandardsIgnoreEnd
424
-                                'event_espresso'
425
-                            ),
426
-                            wp_json_encode($itemized_list)
427
-                        )
428
-                    );
429
-                }
430
-                // Reset the list and log an error, maybe allow to try and generate a new list (below).
431
-                $itemized_list = array();
432
-                $this->log(
433
-                    array(
434
-                        (string) esc_html__(
435
-                            'Could not generate a proper item list with:',
436
-                            'event_espresso'
437
-                        ) => $request_response_args
438
-                    ),
439
-                    $payment
440
-                );
441
-            }
442
-        }
443
-        // ...otherwise we generate a new list for this transaction.
444
-        if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
445
-            $item_num = 0;
446
-            $itemized_sum = 0;
447
-            $total_line_items = $transaction->total_line_item();
448
-            // Go through each item in the list.
449
-            foreach ($total_line_items->get_items() as $line_item) {
450
-                if ($line_item instanceof EE_Line_Item) {
451
-                    // PayPal doesn't like line items with 0.00 amount, so we may skip those.
452
-                    if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
453
-                        continue;
454
-                    }
455
-                    $unit_price = $line_item->unit_price();
456
-                    $line_item_quantity = $line_item->quantity();
457
-                    // This is a discount.
458
-                    if ($line_item->is_percent()) {
459
-                        $unit_price = $line_item->total();
460
-                        $line_item_quantity = 1;
461
-                    }
462
-                    // Item Name.
463
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_NAME' . $item_num ] = mb_strcut(
464
-                        $gateway_formatter->formatLineItemName($line_item, $payment),
465
-                        0,
466
-                        127
467
-                    );
468
-                    // Item description.
469
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_DESC' . $item_num ] = mb_strcut(
470
-                        $gateway_formatter->formatLineItemDesc($line_item, $payment),
471
-                        0,
472
-                        127
473
-                    );
474
-                    // Cost of individual item.
475
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_AMT' . $item_num ] = $gateway_formatter->formatCurrency($unit_price);
476
-                    // Item Number.
477
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_NUMBER' . $item_num ] = $item_num + 1;
478
-                    // Item quantity.
479
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_QTY' . $item_num ] = $line_item_quantity;
480
-                    // Digital item is sold.
481
-                    $itemized_list[ 'L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num ] = 'Physical';
482
-                    $itemized_sum += $line_item->total();
483
-                    ++$item_num;
484
-                }
485
-            }
486
-            // Item's sales S/H and tax amount.
487
-            $itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $total_line_items->get_items_total();
488
-            $itemized_list['PAYMENTREQUEST_0_TAXAMT'] = $total_line_items->get_total_tax();
489
-            $itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
490
-            $itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
491
-            $itemized_sum_diff_from_txn_total = round(
492
-                $transaction->total() - $itemized_sum - $total_line_items->get_total_tax(),
493
-                2
494
-            );
495
-            // If we were not able to recognize some item like promotion, surcharge or cancellation,
496
-            // add the difference as an extra line item.
497
-            if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
498
-                // Item Name.
499
-                $itemized_list[ 'L_PAYMENTREQUEST_0_NAME' . $item_num ] = mb_strcut(
500
-                    esc_html__(
501
-                        'Other (promotion/surcharge/cancellation)',
502
-                        'event_espresso'
503
-                    ),
504
-                    0,
505
-                    127
506
-                );
507
-                // Item description.
508
-                $itemized_list[ 'L_PAYMENTREQUEST_0_DESC' . $item_num ] = '';
509
-                // Cost of individual item.
510
-                $itemized_list[ 'L_PAYMENTREQUEST_0_AMT' . $item_num ] = $gateway_formatter->formatCurrency(
511
-                    $itemized_sum_diff_from_txn_total
512
-                );
513
-                // Item Number.
514
-                $itemized_list[ 'L_PAYMENTREQUEST_0_NUMBER' . $item_num ] = $item_num + 1;
515
-                // Item quantity.
516
-                $itemized_list[ 'L_PAYMENTREQUEST_0_QTY' . $item_num ] = 1;
517
-                // Digital item is sold.
518
-                $itemized_list[ 'L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num ] = 'Physical';
519
-                $item_num++;
520
-            }
521
-        } else {
522
-            // Just one Item.
523
-            // Item Name.
524
-            $itemized_list['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
525
-                $gateway_formatter->formatPartialPaymentLineItemName($payment),
526
-                0,
527
-                127
528
-            );
529
-            // Item description.
530
-            $itemized_list['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
531
-                $gateway_formatter->formatPartialPaymentLineItemDesc($payment),
532
-                0,
533
-                127
534
-            );
535
-            // Cost of individual item.
536
-            $itemized_list['L_PAYMENTREQUEST_0_AMT0'] = $gateway_formatter->formatCurrency($payment->amount());
537
-            // Item Number.
538
-            $itemized_list['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
539
-            // Item quantity.
540
-            $itemized_list['L_PAYMENTREQUEST_0_QTY0'] = 1;
541
-            // Digital item is sold.
542
-            $itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
543
-            // Item's sales S/H and tax amount.
544
-            $itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $gateway_formatter->formatCurrency($payment->amount());
545
-            $itemized_list['PAYMENTREQUEST_0_TAXAMT'] = '0';
546
-            $itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
547
-            $itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
548
-        }
549
-        return $itemized_list;
550
-    }
551
-
552
-
553
-
554
-    /**
555
-     *  Make the Express checkout request.
556
-     *
557
-     * @param array       $request_params
558
-     * @param string      $request_text
559
-     * @param EEI_Payment $payment
560
-     * @return mixed
561
-     */
562
-    public function _ppExpress_request($request_params, $request_text, $payment)
563
-    {
564
-        $request_dtls = array(
565
-            'VERSION' => '204.0',
566
-            'USER' => urlencode($this->_api_username),
567
-            'PWD' => urlencode($this->_api_password),
568
-            'SIGNATURE' => urlencode($this->_api_signature),
569
-            // EE will blow up if you change this
570
-            'BUTTONSOURCE' => 'EventEspresso_SP',
571
-        );
572
-        $dtls = array_merge($request_dtls, $request_params);
573
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
574
-        // Request Customer Details.
575
-        $request_response = wp_remote_post(
576
-            $this->_base_gateway_url,
577
-            array(
578
-                'method'      => 'POST',
579
-                'timeout'     => 45,
580
-                'httpversion' => '1.1',
581
-                'cookies'     => array(),
582
-                'headers'     => array(),
583
-                'body'        => http_build_query($dtls, '', '&'),
584
-            )
585
-        );
586
-        // Log the response.
587
-        $this->log(array($request_text . ' Response' => $request_response), $payment);
588
-        return $request_response;
589
-    }
590
-
591
-
592
-
593
-    /**
594
-     *  Check the response status.
595
-     *
596
-     * @param mixed $request_response
597
-     * @return array
598
-     */
599
-    public function _ppExpress_check_response($request_response)
600
-    {
601
-        if (is_wp_error($request_response) || empty($request_response['body'])) {
602
-            // If we got here then there was an error in this request.
603
-            return array('status' => false, 'args' => $request_response);
604
-        }
605
-        $response_args = array();
606
-        parse_str(urldecode($request_response['body']), $response_args);
607
-        if (! isset($response_args['ACK'])) {
608
-            return array('status' => false, 'args' => $request_response);
609
-        }
610
-        if ((
611
-                isset($response_args['PAYERID'])
612
-                || isset($response_args['TOKEN'])
613
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
614
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
615
-            )
616
-            && in_array($response_args['ACK'], array('Success', 'SuccessWithWarning'), true)
617
-        ) {
618
-            // Response status OK, return response parameters for further processing.
619
-            return array('status' => true, 'args' => $response_args);
620
-        }
621
-        $errors = $this->_get_errors($response_args);
622
-        return array('status' => false, 'args' => $errors);
623
-    }
624
-
625
-
626
-
627
-    /**
628
-     *  Log a "Cleared" request.
629
-     *
630
-     * @param array       $request
631
-     * @param EEI_Payment $payment
632
-     * @param string      $info
633
-     * @return void
634
-     */
635
-    private function _log_clean_request($request, $payment, $info)
636
-    {
637
-        $cleaned_request_data = $request;
638
-        unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
639
-        $this->log(array($info => $cleaned_request_data), $payment);
640
-    }
641
-
642
-
643
-
644
-    /**
645
-     *  Get error from the response data.
646
-     *
647
-     * @param array $data_array
648
-     * @return array
649
-     */
650
-    private function _get_errors($data_array)
651
-    {
652
-        $errors = array();
653
-        $n = 0;
654
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
655
-            $l_error_code = isset($data_array[ "L_ERRORCODE{$n}" ])
656
-                ? $data_array[ "L_ERRORCODE{$n}" ]
657
-                : '';
658
-            $l_severity_code = isset($data_array[ "L_SEVERITYCODE{$n}" ])
659
-                ? $data_array[ "L_SEVERITYCODE{$n}" ]
660
-                : '';
661
-            $l_short_message = isset($data_array[ "L_SHORTMESSAGE{$n}" ])
662
-                ? $data_array[ "L_SHORTMESSAGE{$n}" ]
663
-                : '';
664
-            $l_long_message = isset($data_array[ "L_LONGMESSAGE{$n}" ])
665
-                ? $data_array[ "L_LONGMESSAGE{$n}" ]
666
-                : '';
667
-            if ($n === 0) {
668
-                $errors = array(
669
-                    'L_ERRORCODE'    => $l_error_code,
670
-                    'L_SHORTMESSAGE' => $l_short_message,
671
-                    'L_LONGMESSAGE'  => $l_long_message,
672
-                    'L_SEVERITYCODE' => $l_severity_code,
673
-                );
674
-            } else {
675
-                $errors['L_ERRORCODE'] .= ', ' . $l_error_code;
676
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
677
-                $errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
678
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
679
-            }
680
-            $n++;
681
-        }
682
-        return $errors;
683
-    }
30
+	/**
31
+	 * Merchant API Username.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_api_username;
36
+
37
+	/**
38
+	 * Merchant API Password.
39
+	 *
40
+	 * @var string
41
+	 */
42
+	protected $_api_password;
43
+
44
+	/**
45
+	 * API Signature.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	protected $_api_signature;
50
+
51
+	/**
52
+	 * Request Shipping address on PP checkout page.
53
+	 *
54
+	 * @var string
55
+	 */
56
+	protected $_request_shipping_addr;
57
+
58
+	/**
59
+	 * Business/personal logo.
60
+	 *
61
+	 * @var string
62
+	 */
63
+	protected $_image_url;
64
+
65
+	/**
66
+	 * gateway URL variable
67
+	 *
68
+	 * @var string
69
+	 */
70
+	protected $_base_gateway_url = '';
71
+
72
+
73
+
74
+	/**
75
+	 * EEG_Paypal_Express constructor.
76
+	 */
77
+	public function __construct()
78
+	{
79
+		$this->_currencies_supported = array(
80
+			'USD',
81
+			'AUD',
82
+			'BRL',
83
+			'CAD',
84
+			'CZK',
85
+			'DKK',
86
+			'EUR',
87
+			'HKD',
88
+			'HUF',
89
+			'ILS',
90
+			'JPY',
91
+			'MYR',
92
+			'MXN',
93
+			'NOK',
94
+			'NZD',
95
+			'PHP',
96
+			'PLN',
97
+			'GBP',
98
+			'RUB',
99
+			'SGD',
100
+			'SEK',
101
+			'CHF',
102
+			'TWD',
103
+			'THB',
104
+			'TRY',
105
+			'INR',
106
+		);
107
+		parent::__construct();
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
114
+	 *
115
+	 * @param array $settings_array
116
+	 */
117
+	public function set_settings($settings_array)
118
+	{
119
+		parent::set_settings($settings_array);
120
+		// Redirect URL.
121
+		$this->_base_gateway_url = $this->_debug_mode
122
+			? 'https://api-3t.sandbox.paypal.com/nvp'
123
+			: 'https://api-3t.paypal.com/nvp';
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * @param EEI_Payment $payment
130
+	 * @param array       $billing_info
131
+	 * @param string      $return_url
132
+	 * @param string      $notify_url
133
+	 * @param string      $cancel_url
134
+	 * @return \EE_Payment|\EEI_Payment
135
+	 * @throws \EE_Error
136
+	 */
137
+	public function set_redirection_info(
138
+		$payment,
139
+		$billing_info = array(),
140
+		$return_url = null,
141
+		$notify_url = null,
142
+		$cancel_url = null
143
+	) {
144
+		if (! $payment instanceof EEI_Payment) {
145
+			$payment->set_gateway_response(
146
+				esc_html__(
147
+					'Error. No associated payment was found.',
148
+					'event_espresso'
149
+				)
150
+			);
151
+			$payment->set_status($this->_pay_model->failed_status());
152
+			return $payment;
153
+		}
154
+		$transaction = $payment->transaction();
155
+		if (! $transaction instanceof EEI_Transaction) {
156
+			$payment->set_gateway_response(
157
+				esc_html__(
158
+					'Could not process this payment because it has no associated transaction.',
159
+					'event_espresso'
160
+				)
161
+			);
162
+			$payment->set_status($this->_pay_model->failed_status());
163
+			return $payment;
164
+		}
165
+		$gateway_formatter = $this->_get_gateway_formatter();
166
+		$order_description = mb_strcut($gateway_formatter->formatOrderDescription($payment), 0, 127);
167
+		$primary_registration = $transaction->primary_registration();
168
+		$primary_attendee = $primary_registration instanceof EE_Registration
169
+			? $primary_registration->attendee()
170
+			: false;
171
+		$locale = explode('-', get_bloginfo('language'));
172
+		// Gather request parameters.
173
+		$token_request_dtls = array(
174
+			'METHOD'                         => 'SetExpressCheckout',
175
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
176
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
177
+			'PAYMENTREQUEST_0_DESC'          => $order_description,
178
+			'RETURNURL'                      => $return_url,
179
+			'CANCELURL'                      => $cancel_url,
180
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
181
+			// Buyer does not need to create a PayPal account to check out.
182
+			// This is referred to as PayPal Account Optional.
183
+			'SOLUTIONTYPE'                   => 'Sole',
184
+			// Locale of the pages displayed by PayPal during Express Checkout.
185
+			'LOCALECODE'                     => $locale[1]
186
+		);
187
+		// Show itemized list.
188
+		$itemized_list = $this->itemize_list($payment, $transaction);
189
+		$token_request_dtls = array_merge($token_request_dtls, $itemized_list);
190
+		// Automatically filling out shipping and contact information.
191
+		if ($this->_request_shipping_addr && $primary_attendee instanceof EEI_Attendee) {
192
+			// If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
193
+			$token_request_dtls['NOSHIPPING'] = '2';
194
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET'] = $primary_attendee->address();
195
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTREET2'] = $primary_attendee->address2();
196
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCITY'] = $primary_attendee->city();
197
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOSTATE'] = $primary_attendee->state_abbrev();
198
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
199
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOZIP'] = $primary_attendee->zip();
200
+			$token_request_dtls['PAYMENTREQUEST_0_EMAIL'] = $primary_attendee->email();
201
+			$token_request_dtls['PAYMENTREQUEST_0_SHIPTOPHONENUM'] = $primary_attendee->phone();
202
+		} elseif (! $this->_request_shipping_addr) {
203
+			// Do not request shipping details on the PP Checkout page.
204
+			$token_request_dtls['NOSHIPPING'] = '1';
205
+			$token_request_dtls['REQCONFIRMSHIPPING'] = '0';
206
+		}
207
+		// Used a business/personal logo on the PayPal page.
208
+		if (! empty($this->_image_url)) {
209
+			$token_request_dtls['LOGOIMG'] = $this->_image_url;
210
+		}
211
+		$token_request_dtls = apply_filters(
212
+			'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
213
+			$token_request_dtls,
214
+			$this
215
+		);
216
+		// Request PayPal token.
217
+		$token_request_response = $this->_ppExpress_request($token_request_dtls, 'Payment Token', $payment);
218
+		$token_rstatus = $this->_ppExpress_check_response($token_request_response);
219
+		$response_args = (isset($token_rstatus['args']) && is_array($token_rstatus['args']))
220
+			? $token_rstatus['args']
221
+			: array();
222
+		if ($token_rstatus['status']) {
223
+			// We got the Token so we may continue with the payment and redirect the client.
224
+			$payment->set_details($response_args);
225
+			$gateway_url = $this->_debug_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
226
+			$payment->set_redirect_url(
227
+				$gateway_url
228
+				. '/checkoutnow?useraction=commit&cmd=_express-checkout&token='
229
+				. $response_args['TOKEN']
230
+			);
231
+		} else {
232
+			if (isset($response_args['L_ERRORCODE'])) {
233
+				$payment->set_gateway_response($response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']);
234
+			} else {
235
+				$payment->set_gateway_response(
236
+					esc_html__(
237
+						'Error occurred while trying to setup the Express Checkout.',
238
+						'event_espresso'
239
+					)
240
+				);
241
+			}
242
+			$payment->set_details($response_args);
243
+			$payment->set_status($this->_pay_model->failed_status());
244
+		}
245
+		return $payment;
246
+	}
247
+
248
+
249
+
250
+	/**
251
+	 * @param array           $update_info {
252
+	 * @type string           $gateway_txn_id
253
+	 * @type string status an EEMI_Payment status
254
+	 *                                     }
255
+	 * @param EEI_Transaction $transaction
256
+	 * @return EEI_Payment
257
+	 */
258
+	public function handle_payment_update($update_info, $transaction)
259
+	{
260
+		$payment = $transaction instanceof EEI_Transaction ? $transaction->last_payment() : null;
261
+		if ($payment instanceof EEI_Payment) {
262
+			$this->log(array('Return from Authorization' => $update_info), $payment);
263
+			$transaction = $payment->transaction();
264
+			if (! $transaction instanceof EEI_Transaction) {
265
+				$payment->set_gateway_response(
266
+					esc_html__(
267
+						'Could not process this payment because it has no associated transaction.',
268
+						'event_espresso'
269
+					)
270
+				);
271
+				$payment->set_status($this->_pay_model->failed_status());
272
+				return $payment;
273
+			}
274
+			$primary_registrant = $transaction->primary_registration();
275
+			$payment_details = $payment->details();
276
+			// Check if we still have the token.
277
+			if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
278
+				$payment->set_status($this->_pay_model->failed_status());
279
+				return $payment;
280
+			}
281
+			$cdetails_request_dtls = array(
282
+				'METHOD' => 'GetExpressCheckoutDetails',
283
+				'TOKEN'  => $payment_details['TOKEN'],
284
+			);
285
+			// Request Customer Details.
286
+			$cdetails_request_response = $this->_ppExpress_request(
287
+				$cdetails_request_dtls,
288
+				'Customer Details',
289
+				$payment
290
+			);
291
+			$cdetails_rstatus = $this->_ppExpress_check_response($cdetails_request_response);
292
+			$cdata_response_args = (isset($cdetails_rstatus['args']) && is_array($cdetails_rstatus['args']))
293
+				? $cdetails_rstatus['args']
294
+				: array();
295
+			if ($cdetails_rstatus['status']) {
296
+				// We got the PayerID so now we can Complete the transaction.
297
+				$docheckout_request_dtls = array(
298
+					'METHOD'                         => 'DoExpressCheckoutPayment',
299
+					'PAYERID'                        => $cdata_response_args['PAYERID'],
300
+					'TOKEN'                          => $payment_details['TOKEN'],
301
+					'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
302
+					'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
303
+					'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
304
+				);
305
+				 // Include itemized list.
306
+				$itemized_list = $this->itemize_list(
307
+					$payment,
308
+					$transaction,
309
+					$cdata_response_args
310
+				);
311
+				$docheckout_request_dtls = array_merge($docheckout_request_dtls, $itemized_list);
312
+				// Payment Checkout/Capture.
313
+				$docheckout_request_response = $this->_ppExpress_request(
314
+					$docheckout_request_dtls,
315
+					'Do Payment',
316
+					$payment
317
+				);
318
+				$docheckout_rstatus = $this->_ppExpress_check_response($docheckout_request_response);
319
+				$docheckout_response_args = (isset($docheckout_rstatus['args']) && is_array($docheckout_rstatus['args']))
320
+					? $docheckout_rstatus['args']
321
+					: array();
322
+				if ($docheckout_rstatus['status']) {
323
+					// All is well, payment approved.
324
+					$primary_registration_code = $primary_registrant instanceof EE_Registration ?
325
+						$primary_registrant->reg_code()
326
+						: '';
327
+					$payment->set_extra_accntng($primary_registration_code);
328
+					$payment->set_amount(isset($docheckout_response_args['PAYMENTINFO_0_AMT'])
329
+						? (float) $docheckout_response_args['PAYMENTINFO_0_AMT']
330
+						: 0);
331
+					$payment->set_txn_id_chq_nmbr(isset($docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID'])
332
+						? $docheckout_response_args['PAYMENTINFO_0_TRANSACTIONID']
333
+						: null);
334
+					$payment->set_details($cdata_response_args);
335
+					$payment->set_gateway_response(isset($docheckout_response_args['PAYMENTINFO_0_ACK'])
336
+						? $docheckout_response_args['PAYMENTINFO_0_ACK']
337
+						: '');
338
+					$payment->set_status($this->_pay_model->approved_status());
339
+				} else {
340
+					if (isset($docheckout_response_args['L_ERRORCODE'])) {
341
+						$payment->set_gateway_response(
342
+							$docheckout_response_args['L_ERRORCODE']
343
+							. '; '
344
+							. $docheckout_response_args['L_SHORTMESSAGE']
345
+						);
346
+					} else {
347
+						$payment->set_gateway_response(
348
+							esc_html__(
349
+								'Error occurred while trying to Capture the funds.',
350
+								'event_espresso'
351
+							)
352
+						);
353
+					}
354
+					$payment->set_details($docheckout_response_args);
355
+					$payment->set_status($this->_pay_model->declined_status());
356
+				}
357
+			} else {
358
+				if (isset($cdata_response_args['L_ERRORCODE'])) {
359
+					$payment->set_gateway_response(
360
+						$cdata_response_args['L_ERRORCODE']
361
+						. '; '
362
+						. $cdata_response_args['L_SHORTMESSAGE']
363
+					);
364
+				} else {
365
+					$payment->set_gateway_response(
366
+						esc_html__(
367
+							'Error occurred while trying to get payment Details from PayPal.',
368
+							'event_espresso'
369
+						)
370
+					);
371
+				}
372
+				$payment->set_details($cdata_response_args);
373
+				$payment->set_status($this->_pay_model->failed_status());
374
+			}
375
+		} else {
376
+			$payment->set_gateway_response(
377
+				esc_html__(
378
+					'Error occurred while trying to process the payment.',
379
+					'event_espresso'
380
+				)
381
+			);
382
+			$payment->set_status($this->_pay_model->failed_status());
383
+		}
384
+		return $payment;
385
+	}
386
+
387
+
388
+
389
+	/**
390
+	 *  Make a list of items that are in the giver transaction.
391
+	 *
392
+	 * @param EEI_Payment     $payment
393
+	 * @param EEI_Transaction $transaction
394
+	 * @param array           $request_response_args Data from a previous communication with PP.
395
+	 * @return array
396
+	 */
397
+	public function itemize_list(EEI_Payment $payment, EEI_Transaction $transaction, $request_response_args = array())
398
+	{
399
+		$itemized_list = array();
400
+		$gateway_formatter = $this->_get_gateway_formatter();
401
+		// If we have data from a previous communication with PP (on this transaction) we may use that for our list...
402
+		if (! empty($request_response_args)
403
+			&& array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
404
+			&& array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
405
+		) {
406
+			foreach ($request_response_args as $arg_key => $arg_val) {
407
+				if (strpos($arg_key, 'PAYMENTREQUEST_') !== false
408
+					&& strpos($arg_key, 'NOTIFYURL') === false
409
+				) {
410
+					$itemized_list[ $arg_key ] = $arg_val;
411
+				}
412
+			}
413
+			// If we got only a few Items then something is not right.
414
+			if (count($itemized_list) > 2) {
415
+				return $itemized_list;
416
+			} else {
417
+				if (WP_DEBUG) {
418
+					throw new EE_Error(
419
+						sprintf(
420
+							esc_html__(
421
+								// @codingStandardsIgnoreStart
422
+								'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
423
+								// @codingStandardsIgnoreEnd
424
+								'event_espresso'
425
+							),
426
+							wp_json_encode($itemized_list)
427
+						)
428
+					);
429
+				}
430
+				// Reset the list and log an error, maybe allow to try and generate a new list (below).
431
+				$itemized_list = array();
432
+				$this->log(
433
+					array(
434
+						(string) esc_html__(
435
+							'Could not generate a proper item list with:',
436
+							'event_espresso'
437
+						) => $request_response_args
438
+					),
439
+					$payment
440
+				);
441
+			}
442
+		}
443
+		// ...otherwise we generate a new list for this transaction.
444
+		if ($this->_money->compare_floats($payment->amount(), $transaction->total(), '==')) {
445
+			$item_num = 0;
446
+			$itemized_sum = 0;
447
+			$total_line_items = $transaction->total_line_item();
448
+			// Go through each item in the list.
449
+			foreach ($total_line_items->get_items() as $line_item) {
450
+				if ($line_item instanceof EE_Line_Item) {
451
+					// PayPal doesn't like line items with 0.00 amount, so we may skip those.
452
+					if (EEH_Money::compare_floats($line_item->total(), '0.00', '==')) {
453
+						continue;
454
+					}
455
+					$unit_price = $line_item->unit_price();
456
+					$line_item_quantity = $line_item->quantity();
457
+					// This is a discount.
458
+					if ($line_item->is_percent()) {
459
+						$unit_price = $line_item->total();
460
+						$line_item_quantity = 1;
461
+					}
462
+					// Item Name.
463
+					$itemized_list[ 'L_PAYMENTREQUEST_0_NAME' . $item_num ] = mb_strcut(
464
+						$gateway_formatter->formatLineItemName($line_item, $payment),
465
+						0,
466
+						127
467
+					);
468
+					// Item description.
469
+					$itemized_list[ 'L_PAYMENTREQUEST_0_DESC' . $item_num ] = mb_strcut(
470
+						$gateway_formatter->formatLineItemDesc($line_item, $payment),
471
+						0,
472
+						127
473
+					);
474
+					// Cost of individual item.
475
+					$itemized_list[ 'L_PAYMENTREQUEST_0_AMT' . $item_num ] = $gateway_formatter->formatCurrency($unit_price);
476
+					// Item Number.
477
+					$itemized_list[ 'L_PAYMENTREQUEST_0_NUMBER' . $item_num ] = $item_num + 1;
478
+					// Item quantity.
479
+					$itemized_list[ 'L_PAYMENTREQUEST_0_QTY' . $item_num ] = $line_item_quantity;
480
+					// Digital item is sold.
481
+					$itemized_list[ 'L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num ] = 'Physical';
482
+					$itemized_sum += $line_item->total();
483
+					++$item_num;
484
+				}
485
+			}
486
+			// Item's sales S/H and tax amount.
487
+			$itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $total_line_items->get_items_total();
488
+			$itemized_list['PAYMENTREQUEST_0_TAXAMT'] = $total_line_items->get_total_tax();
489
+			$itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
490
+			$itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
491
+			$itemized_sum_diff_from_txn_total = round(
492
+				$transaction->total() - $itemized_sum - $total_line_items->get_total_tax(),
493
+				2
494
+			);
495
+			// If we were not able to recognize some item like promotion, surcharge or cancellation,
496
+			// add the difference as an extra line item.
497
+			if ($this->_money->compare_floats($itemized_sum_diff_from_txn_total, 0, '!=')) {
498
+				// Item Name.
499
+				$itemized_list[ 'L_PAYMENTREQUEST_0_NAME' . $item_num ] = mb_strcut(
500
+					esc_html__(
501
+						'Other (promotion/surcharge/cancellation)',
502
+						'event_espresso'
503
+					),
504
+					0,
505
+					127
506
+				);
507
+				// Item description.
508
+				$itemized_list[ 'L_PAYMENTREQUEST_0_DESC' . $item_num ] = '';
509
+				// Cost of individual item.
510
+				$itemized_list[ 'L_PAYMENTREQUEST_0_AMT' . $item_num ] = $gateway_formatter->formatCurrency(
511
+					$itemized_sum_diff_from_txn_total
512
+				);
513
+				// Item Number.
514
+				$itemized_list[ 'L_PAYMENTREQUEST_0_NUMBER' . $item_num ] = $item_num + 1;
515
+				// Item quantity.
516
+				$itemized_list[ 'L_PAYMENTREQUEST_0_QTY' . $item_num ] = 1;
517
+				// Digital item is sold.
518
+				$itemized_list[ 'L_PAYMENTREQUEST_0_ITEMCATEGORY' . $item_num ] = 'Physical';
519
+				$item_num++;
520
+			}
521
+		} else {
522
+			// Just one Item.
523
+			// Item Name.
524
+			$itemized_list['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
525
+				$gateway_formatter->formatPartialPaymentLineItemName($payment),
526
+				0,
527
+				127
528
+			);
529
+			// Item description.
530
+			$itemized_list['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
531
+				$gateway_formatter->formatPartialPaymentLineItemDesc($payment),
532
+				0,
533
+				127
534
+			);
535
+			// Cost of individual item.
536
+			$itemized_list['L_PAYMENTREQUEST_0_AMT0'] = $gateway_formatter->formatCurrency($payment->amount());
537
+			// Item Number.
538
+			$itemized_list['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
539
+			// Item quantity.
540
+			$itemized_list['L_PAYMENTREQUEST_0_QTY0'] = 1;
541
+			// Digital item is sold.
542
+			$itemized_list['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
543
+			// Item's sales S/H and tax amount.
544
+			$itemized_list['PAYMENTREQUEST_0_ITEMAMT'] = $gateway_formatter->formatCurrency($payment->amount());
545
+			$itemized_list['PAYMENTREQUEST_0_TAXAMT'] = '0';
546
+			$itemized_list['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
547
+			$itemized_list['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
548
+		}
549
+		return $itemized_list;
550
+	}
551
+
552
+
553
+
554
+	/**
555
+	 *  Make the Express checkout request.
556
+	 *
557
+	 * @param array       $request_params
558
+	 * @param string      $request_text
559
+	 * @param EEI_Payment $payment
560
+	 * @return mixed
561
+	 */
562
+	public function _ppExpress_request($request_params, $request_text, $payment)
563
+	{
564
+		$request_dtls = array(
565
+			'VERSION' => '204.0',
566
+			'USER' => urlencode($this->_api_username),
567
+			'PWD' => urlencode($this->_api_password),
568
+			'SIGNATURE' => urlencode($this->_api_signature),
569
+			// EE will blow up if you change this
570
+			'BUTTONSOURCE' => 'EventEspresso_SP',
571
+		);
572
+		$dtls = array_merge($request_dtls, $request_params);
573
+		$this->_log_clean_request($dtls, $payment, $request_text . ' Request');
574
+		// Request Customer Details.
575
+		$request_response = wp_remote_post(
576
+			$this->_base_gateway_url,
577
+			array(
578
+				'method'      => 'POST',
579
+				'timeout'     => 45,
580
+				'httpversion' => '1.1',
581
+				'cookies'     => array(),
582
+				'headers'     => array(),
583
+				'body'        => http_build_query($dtls, '', '&'),
584
+			)
585
+		);
586
+		// Log the response.
587
+		$this->log(array($request_text . ' Response' => $request_response), $payment);
588
+		return $request_response;
589
+	}
590
+
591
+
592
+
593
+	/**
594
+	 *  Check the response status.
595
+	 *
596
+	 * @param mixed $request_response
597
+	 * @return array
598
+	 */
599
+	public function _ppExpress_check_response($request_response)
600
+	{
601
+		if (is_wp_error($request_response) || empty($request_response['body'])) {
602
+			// If we got here then there was an error in this request.
603
+			return array('status' => false, 'args' => $request_response);
604
+		}
605
+		$response_args = array();
606
+		parse_str(urldecode($request_response['body']), $response_args);
607
+		if (! isset($response_args['ACK'])) {
608
+			return array('status' => false, 'args' => $request_response);
609
+		}
610
+		if ((
611
+				isset($response_args['PAYERID'])
612
+				|| isset($response_args['TOKEN'])
613
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
614
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
615
+			)
616
+			&& in_array($response_args['ACK'], array('Success', 'SuccessWithWarning'), true)
617
+		) {
618
+			// Response status OK, return response parameters for further processing.
619
+			return array('status' => true, 'args' => $response_args);
620
+		}
621
+		$errors = $this->_get_errors($response_args);
622
+		return array('status' => false, 'args' => $errors);
623
+	}
624
+
625
+
626
+
627
+	/**
628
+	 *  Log a "Cleared" request.
629
+	 *
630
+	 * @param array       $request
631
+	 * @param EEI_Payment $payment
632
+	 * @param string      $info
633
+	 * @return void
634
+	 */
635
+	private function _log_clean_request($request, $payment, $info)
636
+	{
637
+		$cleaned_request_data = $request;
638
+		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
639
+		$this->log(array($info => $cleaned_request_data), $payment);
640
+	}
641
+
642
+
643
+
644
+	/**
645
+	 *  Get error from the response data.
646
+	 *
647
+	 * @param array $data_array
648
+	 * @return array
649
+	 */
650
+	private function _get_errors($data_array)
651
+	{
652
+		$errors = array();
653
+		$n = 0;
654
+		while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
655
+			$l_error_code = isset($data_array[ "L_ERRORCODE{$n}" ])
656
+				? $data_array[ "L_ERRORCODE{$n}" ]
657
+				: '';
658
+			$l_severity_code = isset($data_array[ "L_SEVERITYCODE{$n}" ])
659
+				? $data_array[ "L_SEVERITYCODE{$n}" ]
660
+				: '';
661
+			$l_short_message = isset($data_array[ "L_SHORTMESSAGE{$n}" ])
662
+				? $data_array[ "L_SHORTMESSAGE{$n}" ]
663
+				: '';
664
+			$l_long_message = isset($data_array[ "L_LONGMESSAGE{$n}" ])
665
+				? $data_array[ "L_LONGMESSAGE{$n}" ]
666
+				: '';
667
+			if ($n === 0) {
668
+				$errors = array(
669
+					'L_ERRORCODE'    => $l_error_code,
670
+					'L_SHORTMESSAGE' => $l_short_message,
671
+					'L_LONGMESSAGE'  => $l_long_message,
672
+					'L_SEVERITYCODE' => $l_severity_code,
673
+				);
674
+			} else {
675
+				$errors['L_ERRORCODE'] .= ', ' . $l_error_code;
676
+				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
677
+				$errors['L_LONGMESSAGE'] .= ', ' . $l_long_message;
678
+				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
679
+			}
680
+			$n++;
681
+		}
682
+		return $errors;
683
+	}
684 684
 }
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Strategy.core.php 2 patches
Indentation   +443 added lines, -443 removed lines patch added patch discarded remove patch
@@ -16,447 +16,447 @@
 block discarded – undo
16 16
 class EE_CPT_Strategy extends EE_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_CPT_Strategy $_instance
21
-     */
22
-    private static $_instance;
23
-
24
-    /**
25
-     * the current page, if it utilizes CPTs
26
-     *
27
-     * @var array $CPT
28
-     */
29
-    protected $CPT;
30
-
31
-    /**
32
-     * return value from CustomPostTypeDefinitions::getDefinitions()
33
-     *
34
-     * @var array $_CPTs
35
-     */
36
-    protected $_CPTs = array();
37
-
38
-    /**
39
-     * @var array $_CPT_taxonomies
40
-     */
41
-    protected $_CPT_taxonomies = array();
42
-
43
-    /**
44
-     * @var array $_CPT_terms
45
-     */
46
-    protected $_CPT_terms = array();
47
-
48
-    /**
49
-     * @var array $_CPT_endpoints
50
-     */
51
-    protected $_CPT_endpoints = array();
52
-
53
-    /**
54
-     * @var EEM_Base $CPT_model
55
-     */
56
-    protected $CPT_model;
57
-
58
-    /**
59
-     * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
60
-     */
61
-    protected $query_modifier;
62
-
63
-
64
-    /**
65
-     * @singleton method used to instantiate class object
66
-     * @param CustomPostTypeDefinitions|null $custom_post_types
67
-     * @param CustomTaxonomyDefinitions|null $taxonomies
68
-     * @return EE_CPT_Strategy
69
-     */
70
-    public static function instance(
71
-        CustomPostTypeDefinitions $custom_post_types = null,
72
-        CustomTaxonomyDefinitions $taxonomies = null
73
-    ) {
74
-        // check if class object is instantiated
75
-        if (! self::$_instance instanceof EE_CPT_Strategy
76
-            && $custom_post_types instanceof CustomPostTypeDefinitions
77
-            && $taxonomies instanceof CustomTaxonomyDefinitions
78
-        ) {
79
-            self::$_instance = new self($custom_post_types, $taxonomies);
80
-        }
81
-        return self::$_instance;
82
-    }
83
-
84
-
85
-    /**
86
-     * @param CustomPostTypeDefinitions $custom_post_types
87
-     * @param CustomTaxonomyDefinitions $taxonomies
88
-     */
89
-    protected function __construct(
90
-        CustomPostTypeDefinitions $custom_post_types,
91
-        CustomTaxonomyDefinitions $taxonomies
92
-    ) {
93
-        // get CPT data
94
-        $this->_CPTs = $custom_post_types->getDefinitions();
95
-        $this->_CPT_endpoints = $this->_set_CPT_endpoints();
96
-        $this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
97
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
98
-    }
99
-
100
-
101
-    /**
102
-     * @return array
103
-     */
104
-    public function get_CPT_endpoints()
105
-    {
106
-        return $this->_CPT_endpoints;
107
-    }
108
-
109
-
110
-    /**
111
-     * @return array
112
-     */
113
-    public function get_CPT_taxonomies()
114
-    {
115
-        return $this->_CPT_taxonomies;
116
-    }
117
-
118
-
119
-    /**
120
-     * add CPT "slugs" to array of default espresso "pages"
121
-     *
122
-     * @return array
123
-     */
124
-    private function _set_CPT_endpoints()
125
-    {
126
-        $_CPT_endpoints = array();
127
-        if (is_array($this->_CPTs)) {
128
-            foreach ($this->_CPTs as $CPT_type => $CPT) {
129
-                if (isset($CPT['plural_slug'])) {
130
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
-                }
132
-            }
133
-        }
134
-        return $_CPT_endpoints;
135
-    }
136
-
137
-
138
-    /**
139
-     * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
140
-     * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
141
-     * adding EE objects to the post to facilitate further querying of related data etc)
142
-     *
143
-     * @param WP_Query $WP_Query
144
-     * @return void
145
-     * @throws \EE_Error
146
-     * @throws \InvalidArgumentException
147
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
148
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
149
-     */
150
-    public function pre_get_posts($WP_Query)
151
-    {
152
-        // check that post-type is set
153
-        if (! $WP_Query instanceof WP_Query) {
154
-            return;
155
-        }
156
-        // add our conditionals
157
-        $this->_set_EE_tags_on_WP_Query($WP_Query);
158
-        // check for terms
159
-        $this->_set_post_type_for_terms($WP_Query);
160
-        // make sure paging is always set
161
-        $this->_set_paging($WP_Query);
162
-        // is a taxonomy set ?
163
-        $this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
164
-        // loop thru post_types if set
165
-        $this->_process_WP_Query_post_types($WP_Query);
166
-    }
167
-
168
-
169
-    /**
170
-     * @param WP_Query $WP_Query
171
-     * @return void
172
-     */
173
-    private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
174
-    {
175
-        $WP_Query->is_espresso_event_single = false;
176
-        $WP_Query->is_espresso_event_archive = false;
177
-        $WP_Query->is_espresso_event_taxonomy = false;
178
-        $WP_Query->is_espresso_venue_single = false;
179
-        $WP_Query->is_espresso_venue_archive = false;
180
-        $WP_Query->is_espresso_venue_taxonomy = false;
181
-    }
182
-
183
-
184
-    /**
185
-     * @return void
186
-     * @throws EE_Error
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidInterfaceException
190
-     */
191
-    private function _set_CPT_terms()
192
-    {
193
-        if (empty($this->_CPT_terms)) {
194
-            $terms = EEM_Term::instance()->get_all_CPT_post_tags();
195
-            foreach ($terms as $term) {
196
-                if ($term instanceof EE_Term) {
197
-                    $this->_CPT_terms[ $term->slug() ] = $term;
198
-                }
199
-            }
200
-        }
201
-    }
202
-
203
-
204
-    /**
205
-     * @param WP_Query $WP_Query
206
-     * @return void
207
-     * @throws EE_Error
208
-     * @throws InvalidArgumentException
209
-     * @throws InvalidDataTypeException
210
-     * @throws InvalidInterfaceException
211
-     */
212
-    private function _set_post_type_for_terms(WP_Query $WP_Query)
213
-    {
214
-        // is a tag set ?
215
-        if (isset($WP_Query->query['tag'])) {
216
-            // get term for tag
217
-            $term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
218
-            // verify the term
219
-            if ($term instanceof EE_Term) {
220
-                $term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
221
-                $term->post_type = apply_filters(
222
-                    'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
223
-                    $term->post_type,
224
-                    $term
225
-                );
226
-                // if a post type is already set
227
-                if (isset($WP_Query->query_vars['post_type'])) {
228
-                    // add to existing array
229
-                    $term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
230
-                }
231
-                // just set post_type to our CPT
232
-                $WP_Query->set('post_type', array_unique($term->post_type));
233
-            }
234
-        }
235
-    }
236
-
237
-
238
-    /**
239
-     * @param WP_Query $WP_Query
240
-     * @return void
241
-     */
242
-    public function _set_paging($WP_Query)
243
-    {
244
-        if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
245
-            $page = get_query_var('page') ? get_query_var('page') : null;
246
-            $paged = get_query_var('paged') ? get_query_var('paged') : $page;
247
-            $WP_Query->set('paged', $paged);
248
-        }
249
-    }
250
-
251
-
252
-    /**
253
-     * @param \WP_Query $WP_Query
254
-     */
255
-    protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
256
-    {
257
-        // is a taxonomy set ?
258
-        if ($WP_Query->is_tax) {
259
-            // loop thru our taxonomies
260
-            foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
261
-                // check if one of our taxonomies is set as a query var
262
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
-                    // but which CPT does that correspond to??? hmmm... guess we gotta go looping
264
-                    foreach ($this->_CPTs as $post_type => $CPT) {
265
-                        // verify our CPT has args, is public and has taxonomies set
266
-                        if (isset($CPT['args']['public'])
267
-                            && $CPT['args']['public']
268
-                            && ! empty($CPT['args']['taxonomies'])
269
-                            && in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
270
-                        ) {
271
-                            // if so, then add this CPT post_type to the current query's array of post_types'
272
-                            $WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
273
-                                ? (array) $WP_Query->query_vars['post_type']
274
-                                : array();
275
-                            $WP_Query->query_vars['post_type'][] = $post_type;
276
-                            switch ($post_type) {
277
-                                case 'espresso_events':
278
-                                    $WP_Query->is_espresso_event_taxonomy = true;
279
-                                    break;
280
-                                case 'espresso_venues':
281
-                                    $WP_Query->is_espresso_venue_taxonomy = true;
282
-                                    break;
283
-                                default:
284
-                                    do_action(
285
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
286
-                                        $WP_Query,
287
-                                        $this
288
-                                    );
289
-                            }
290
-                        }
291
-                    }
292
-                }
293
-            }
294
-        }
295
-    }
296
-
297
-
298
-    /**
299
-     * @param \WP_Query $WP_Query
300
-     * @throws InvalidArgumentException
301
-     * @throws InvalidDataTypeException
302
-     * @throws InvalidInterfaceException
303
-     */
304
-    protected function _process_WP_Query_post_types(WP_Query $WP_Query)
305
-    {
306
-        if (isset($WP_Query->query_vars['post_type'])) {
307
-            // loop thru post_types as array
308
-            foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
309
-                // is current query for an EE CPT ?
310
-                if (isset($this->_CPTs[ $post_type ])) {
311
-                    // is EE on or off ?
312
-                    if (EE_Maintenance_Mode::instance()->level()) {
313
-                        // reroute CPT template view to maintenance_mode.template.php
314
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
315
-                            add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
316
-                        }
317
-                        if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
318
-                            add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
319
-                        }
320
-                        return;
321
-                    }
322
-                    $this->_generate_CptQueryModifier($WP_Query, $post_type);
323
-                }
324
-            }
325
-        }
326
-    }
327
-
328
-
329
-    /**
330
-     * @param \WP_Query $WP_Query
331
-     * @param string    $post_type
332
-     * @throws InvalidArgumentException
333
-     * @throws InvalidDataTypeException
334
-     * @throws InvalidInterfaceException
335
-     */
336
-    protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
337
-    {
338
-        $this->query_modifier = LoaderFactory::getLoader()->getShared(
339
-            'EventEspresso\core\CPTs\CptQueryModifier',
340
-            array(
341
-                $post_type,
342
-                $this->_CPTs[ $post_type ],
343
-                $WP_Query,
344
-            )
345
-        );
346
-        $this->_CPT_taxonomies = $this->query_modifier->taxonomies();
347
-    }
348
-
349
-
350
-    /**
351
-     * inject_EE_shortcode_placeholder
352
-     * in order to display the M-Mode notice on our CPT routes,
353
-     * we need to first inject what looks like one of our shortcodes,
354
-     * so that it can be replaced with the actual M-Mode notice
355
-     *
356
-     * @return string
357
-     */
358
-    public function inject_EE_shortcode_placeholder()
359
-    {
360
-        return '[ESPRESSO_';
361
-    }
362
-
363
-
364
-    /**
365
-     * @deprecated
366
-     * @since  4.8.41
367
-     * @return void
368
-     */
369
-    public function _possibly_set_ee_request_var()
370
-    {
371
-        $this->query_modifier->setRequestVarsIfCpt();
372
-    }
373
-
374
-
375
-    /**
376
-     * @deprecated
377
-     * @since  4.8.41
378
-     * @param  $SQL
379
-     * @return string
380
-     */
381
-    public function posts_fields($SQL)
382
-    {
383
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
384
-            return $this->query_modifier->postsFields($SQL);
385
-        }
386
-        return $SQL;
387
-    }
388
-
389
-
390
-    /**
391
-     * @deprecated
392
-     * @since  4.8.41
393
-     * @param  $SQL
394
-     * @return string
395
-     */
396
-    public function posts_join($SQL)
397
-    {
398
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
399
-            return $this->query_modifier->postsJoin($SQL);
400
-        }
401
-        return $SQL;
402
-    }
403
-
404
-
405
-    /**
406
-     * @deprecated
407
-     * @since  4.8.41
408
-     * @param  \WP_Post[] $posts
409
-     * @return \WP_Post[]
410
-     */
411
-    public function the_posts($posts)
412
-    {
413
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
414
-            $this->query_modifier->thePosts($posts);
415
-        }
416
-        return $posts;
417
-    }
418
-
419
-
420
-    /**
421
-     * @deprecated
422
-     * @since  4.8.41
423
-     * @param $url
424
-     * @param $ID
425
-     * @return string
426
-     */
427
-    public function get_edit_post_link($url, $ID)
428
-    {
429
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
430
-            return $this->query_modifier->getEditPostLink($url, $ID);
431
-        }
432
-        return '';
433
-    }
434
-
435
-
436
-    /**
437
-     * @deprecated
438
-     * @since  4.8.41
439
-     * @param null $WP_Query
440
-     */
441
-    protected function _do_template_filters($WP_Query = null)
442
-    {
443
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
444
-            $this->query_modifier->addTemplateFilters();
445
-        }
446
-    }
447
-
448
-
449
-    /**
450
-     * @deprecated
451
-     * @since  4.8.41
452
-     * @param string $current_template Existing default template path derived for this page call.
453
-     * @return string the path to the full template file.
454
-     */
455
-    public function single_cpt_template($current_template)
456
-    {
457
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
458
-            return $this->query_modifier->singleCptTemplate($current_template);
459
-        }
460
-        return $current_template;
461
-    }
19
+	/**
20
+	 * @var EE_CPT_Strategy $_instance
21
+	 */
22
+	private static $_instance;
23
+
24
+	/**
25
+	 * the current page, if it utilizes CPTs
26
+	 *
27
+	 * @var array $CPT
28
+	 */
29
+	protected $CPT;
30
+
31
+	/**
32
+	 * return value from CustomPostTypeDefinitions::getDefinitions()
33
+	 *
34
+	 * @var array $_CPTs
35
+	 */
36
+	protected $_CPTs = array();
37
+
38
+	/**
39
+	 * @var array $_CPT_taxonomies
40
+	 */
41
+	protected $_CPT_taxonomies = array();
42
+
43
+	/**
44
+	 * @var array $_CPT_terms
45
+	 */
46
+	protected $_CPT_terms = array();
47
+
48
+	/**
49
+	 * @var array $_CPT_endpoints
50
+	 */
51
+	protected $_CPT_endpoints = array();
52
+
53
+	/**
54
+	 * @var EEM_Base $CPT_model
55
+	 */
56
+	protected $CPT_model;
57
+
58
+	/**
59
+	 * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
60
+	 */
61
+	protected $query_modifier;
62
+
63
+
64
+	/**
65
+	 * @singleton method used to instantiate class object
66
+	 * @param CustomPostTypeDefinitions|null $custom_post_types
67
+	 * @param CustomTaxonomyDefinitions|null $taxonomies
68
+	 * @return EE_CPT_Strategy
69
+	 */
70
+	public static function instance(
71
+		CustomPostTypeDefinitions $custom_post_types = null,
72
+		CustomTaxonomyDefinitions $taxonomies = null
73
+	) {
74
+		// check if class object is instantiated
75
+		if (! self::$_instance instanceof EE_CPT_Strategy
76
+			&& $custom_post_types instanceof CustomPostTypeDefinitions
77
+			&& $taxonomies instanceof CustomTaxonomyDefinitions
78
+		) {
79
+			self::$_instance = new self($custom_post_types, $taxonomies);
80
+		}
81
+		return self::$_instance;
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param CustomPostTypeDefinitions $custom_post_types
87
+	 * @param CustomTaxonomyDefinitions $taxonomies
88
+	 */
89
+	protected function __construct(
90
+		CustomPostTypeDefinitions $custom_post_types,
91
+		CustomTaxonomyDefinitions $taxonomies
92
+	) {
93
+		// get CPT data
94
+		$this->_CPTs = $custom_post_types->getDefinitions();
95
+		$this->_CPT_endpoints = $this->_set_CPT_endpoints();
96
+		$this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
97
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
98
+	}
99
+
100
+
101
+	/**
102
+	 * @return array
103
+	 */
104
+	public function get_CPT_endpoints()
105
+	{
106
+		return $this->_CPT_endpoints;
107
+	}
108
+
109
+
110
+	/**
111
+	 * @return array
112
+	 */
113
+	public function get_CPT_taxonomies()
114
+	{
115
+		return $this->_CPT_taxonomies;
116
+	}
117
+
118
+
119
+	/**
120
+	 * add CPT "slugs" to array of default espresso "pages"
121
+	 *
122
+	 * @return array
123
+	 */
124
+	private function _set_CPT_endpoints()
125
+	{
126
+		$_CPT_endpoints = array();
127
+		if (is_array($this->_CPTs)) {
128
+			foreach ($this->_CPTs as $CPT_type => $CPT) {
129
+				if (isset($CPT['plural_slug'])) {
130
+					$_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
+				}
132
+			}
133
+		}
134
+		return $_CPT_endpoints;
135
+	}
136
+
137
+
138
+	/**
139
+	 * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
140
+	 * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
141
+	 * adding EE objects to the post to facilitate further querying of related data etc)
142
+	 *
143
+	 * @param WP_Query $WP_Query
144
+	 * @return void
145
+	 * @throws \EE_Error
146
+	 * @throws \InvalidArgumentException
147
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
148
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
149
+	 */
150
+	public function pre_get_posts($WP_Query)
151
+	{
152
+		// check that post-type is set
153
+		if (! $WP_Query instanceof WP_Query) {
154
+			return;
155
+		}
156
+		// add our conditionals
157
+		$this->_set_EE_tags_on_WP_Query($WP_Query);
158
+		// check for terms
159
+		$this->_set_post_type_for_terms($WP_Query);
160
+		// make sure paging is always set
161
+		$this->_set_paging($WP_Query);
162
+		// is a taxonomy set ?
163
+		$this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
164
+		// loop thru post_types if set
165
+		$this->_process_WP_Query_post_types($WP_Query);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param WP_Query $WP_Query
171
+	 * @return void
172
+	 */
173
+	private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
174
+	{
175
+		$WP_Query->is_espresso_event_single = false;
176
+		$WP_Query->is_espresso_event_archive = false;
177
+		$WP_Query->is_espresso_event_taxonomy = false;
178
+		$WP_Query->is_espresso_venue_single = false;
179
+		$WP_Query->is_espresso_venue_archive = false;
180
+		$WP_Query->is_espresso_venue_taxonomy = false;
181
+	}
182
+
183
+
184
+	/**
185
+	 * @return void
186
+	 * @throws EE_Error
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidInterfaceException
190
+	 */
191
+	private function _set_CPT_terms()
192
+	{
193
+		if (empty($this->_CPT_terms)) {
194
+			$terms = EEM_Term::instance()->get_all_CPT_post_tags();
195
+			foreach ($terms as $term) {
196
+				if ($term instanceof EE_Term) {
197
+					$this->_CPT_terms[ $term->slug() ] = $term;
198
+				}
199
+			}
200
+		}
201
+	}
202
+
203
+
204
+	/**
205
+	 * @param WP_Query $WP_Query
206
+	 * @return void
207
+	 * @throws EE_Error
208
+	 * @throws InvalidArgumentException
209
+	 * @throws InvalidDataTypeException
210
+	 * @throws InvalidInterfaceException
211
+	 */
212
+	private function _set_post_type_for_terms(WP_Query $WP_Query)
213
+	{
214
+		// is a tag set ?
215
+		if (isset($WP_Query->query['tag'])) {
216
+			// get term for tag
217
+			$term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
218
+			// verify the term
219
+			if ($term instanceof EE_Term) {
220
+				$term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
221
+				$term->post_type = apply_filters(
222
+					'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
223
+					$term->post_type,
224
+					$term
225
+				);
226
+				// if a post type is already set
227
+				if (isset($WP_Query->query_vars['post_type'])) {
228
+					// add to existing array
229
+					$term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
230
+				}
231
+				// just set post_type to our CPT
232
+				$WP_Query->set('post_type', array_unique($term->post_type));
233
+			}
234
+		}
235
+	}
236
+
237
+
238
+	/**
239
+	 * @param WP_Query $WP_Query
240
+	 * @return void
241
+	 */
242
+	public function _set_paging($WP_Query)
243
+	{
244
+		if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
245
+			$page = get_query_var('page') ? get_query_var('page') : null;
246
+			$paged = get_query_var('paged') ? get_query_var('paged') : $page;
247
+			$WP_Query->set('paged', $paged);
248
+		}
249
+	}
250
+
251
+
252
+	/**
253
+	 * @param \WP_Query $WP_Query
254
+	 */
255
+	protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
256
+	{
257
+		// is a taxonomy set ?
258
+		if ($WP_Query->is_tax) {
259
+			// loop thru our taxonomies
260
+			foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
261
+				// check if one of our taxonomies is set as a query var
262
+				if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
+					// but which CPT does that correspond to??? hmmm... guess we gotta go looping
264
+					foreach ($this->_CPTs as $post_type => $CPT) {
265
+						// verify our CPT has args, is public and has taxonomies set
266
+						if (isset($CPT['args']['public'])
267
+							&& $CPT['args']['public']
268
+							&& ! empty($CPT['args']['taxonomies'])
269
+							&& in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
270
+						) {
271
+							// if so, then add this CPT post_type to the current query's array of post_types'
272
+							$WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
273
+								? (array) $WP_Query->query_vars['post_type']
274
+								: array();
275
+							$WP_Query->query_vars['post_type'][] = $post_type;
276
+							switch ($post_type) {
277
+								case 'espresso_events':
278
+									$WP_Query->is_espresso_event_taxonomy = true;
279
+									break;
280
+								case 'espresso_venues':
281
+									$WP_Query->is_espresso_venue_taxonomy = true;
282
+									break;
283
+								default:
284
+									do_action(
285
+										'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
286
+										$WP_Query,
287
+										$this
288
+									);
289
+							}
290
+						}
291
+					}
292
+				}
293
+			}
294
+		}
295
+	}
296
+
297
+
298
+	/**
299
+	 * @param \WP_Query $WP_Query
300
+	 * @throws InvalidArgumentException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws InvalidInterfaceException
303
+	 */
304
+	protected function _process_WP_Query_post_types(WP_Query $WP_Query)
305
+	{
306
+		if (isset($WP_Query->query_vars['post_type'])) {
307
+			// loop thru post_types as array
308
+			foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
309
+				// is current query for an EE CPT ?
310
+				if (isset($this->_CPTs[ $post_type ])) {
311
+					// is EE on or off ?
312
+					if (EE_Maintenance_Mode::instance()->level()) {
313
+						// reroute CPT template view to maintenance_mode.template.php
314
+						if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
315
+							add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
316
+						}
317
+						if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
318
+							add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
319
+						}
320
+						return;
321
+					}
322
+					$this->_generate_CptQueryModifier($WP_Query, $post_type);
323
+				}
324
+			}
325
+		}
326
+	}
327
+
328
+
329
+	/**
330
+	 * @param \WP_Query $WP_Query
331
+	 * @param string    $post_type
332
+	 * @throws InvalidArgumentException
333
+	 * @throws InvalidDataTypeException
334
+	 * @throws InvalidInterfaceException
335
+	 */
336
+	protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
337
+	{
338
+		$this->query_modifier = LoaderFactory::getLoader()->getShared(
339
+			'EventEspresso\core\CPTs\CptQueryModifier',
340
+			array(
341
+				$post_type,
342
+				$this->_CPTs[ $post_type ],
343
+				$WP_Query,
344
+			)
345
+		);
346
+		$this->_CPT_taxonomies = $this->query_modifier->taxonomies();
347
+	}
348
+
349
+
350
+	/**
351
+	 * inject_EE_shortcode_placeholder
352
+	 * in order to display the M-Mode notice on our CPT routes,
353
+	 * we need to first inject what looks like one of our shortcodes,
354
+	 * so that it can be replaced with the actual M-Mode notice
355
+	 *
356
+	 * @return string
357
+	 */
358
+	public function inject_EE_shortcode_placeholder()
359
+	{
360
+		return '[ESPRESSO_';
361
+	}
362
+
363
+
364
+	/**
365
+	 * @deprecated
366
+	 * @since  4.8.41
367
+	 * @return void
368
+	 */
369
+	public function _possibly_set_ee_request_var()
370
+	{
371
+		$this->query_modifier->setRequestVarsIfCpt();
372
+	}
373
+
374
+
375
+	/**
376
+	 * @deprecated
377
+	 * @since  4.8.41
378
+	 * @param  $SQL
379
+	 * @return string
380
+	 */
381
+	public function posts_fields($SQL)
382
+	{
383
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
384
+			return $this->query_modifier->postsFields($SQL);
385
+		}
386
+		return $SQL;
387
+	}
388
+
389
+
390
+	/**
391
+	 * @deprecated
392
+	 * @since  4.8.41
393
+	 * @param  $SQL
394
+	 * @return string
395
+	 */
396
+	public function posts_join($SQL)
397
+	{
398
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
399
+			return $this->query_modifier->postsJoin($SQL);
400
+		}
401
+		return $SQL;
402
+	}
403
+
404
+
405
+	/**
406
+	 * @deprecated
407
+	 * @since  4.8.41
408
+	 * @param  \WP_Post[] $posts
409
+	 * @return \WP_Post[]
410
+	 */
411
+	public function the_posts($posts)
412
+	{
413
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
414
+			$this->query_modifier->thePosts($posts);
415
+		}
416
+		return $posts;
417
+	}
418
+
419
+
420
+	/**
421
+	 * @deprecated
422
+	 * @since  4.8.41
423
+	 * @param $url
424
+	 * @param $ID
425
+	 * @return string
426
+	 */
427
+	public function get_edit_post_link($url, $ID)
428
+	{
429
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
430
+			return $this->query_modifier->getEditPostLink($url, $ID);
431
+		}
432
+		return '';
433
+	}
434
+
435
+
436
+	/**
437
+	 * @deprecated
438
+	 * @since  4.8.41
439
+	 * @param null $WP_Query
440
+	 */
441
+	protected function _do_template_filters($WP_Query = null)
442
+	{
443
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
444
+			$this->query_modifier->addTemplateFilters();
445
+		}
446
+	}
447
+
448
+
449
+	/**
450
+	 * @deprecated
451
+	 * @since  4.8.41
452
+	 * @param string $current_template Existing default template path derived for this page call.
453
+	 * @return string the path to the full template file.
454
+	 */
455
+	public function single_cpt_template($current_template)
456
+	{
457
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
458
+			return $this->query_modifier->singleCptTemplate($current_template);
459
+		}
460
+		return $current_template;
461
+	}
462 462
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
         CustomTaxonomyDefinitions $taxonomies = null
73 73
     ) {
74 74
         // check if class object is instantiated
75
-        if (! self::$_instance instanceof EE_CPT_Strategy
75
+        if ( ! self::$_instance instanceof EE_CPT_Strategy
76 76
             && $custom_post_types instanceof CustomPostTypeDefinitions
77 77
             && $taxonomies instanceof CustomTaxonomyDefinitions
78 78
         ) {
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
         if (is_array($this->_CPTs)) {
128 128
             foreach ($this->_CPTs as $CPT_type => $CPT) {
129 129
                 if (isset($CPT['plural_slug'])) {
130
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
130
+                    $_CPT_endpoints [(string) $CPT['plural_slug']] = $CPT_type;
131 131
                 }
132 132
             }
133 133
         }
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
     public function pre_get_posts($WP_Query)
151 151
     {
152 152
         // check that post-type is set
153
-        if (! $WP_Query instanceof WP_Query) {
153
+        if ( ! $WP_Query instanceof WP_Query) {
154 154
             return;
155 155
         }
156 156
         // add our conditionals
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
             $terms = EEM_Term::instance()->get_all_CPT_post_tags();
195 195
             foreach ($terms as $term) {
196 196
                 if ($term instanceof EE_Term) {
197
-                    $this->_CPT_terms[ $term->slug() ] = $term;
197
+                    $this->_CPT_terms[$term->slug()] = $term;
198 198
                 }
199 199
             }
200 200
         }
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
             // loop thru our taxonomies
260 260
             foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
261 261
                 // check if one of our taxonomies is set as a query var
262
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
262
+                if (isset($WP_Query->query[$CPT_taxonomy])) {
263 263
                     // but which CPT does that correspond to??? hmmm... guess we gotta go looping
264 264
                     foreach ($this->_CPTs as $post_type => $CPT) {
265 265
                         // verify our CPT has args, is public and has taxonomies set
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
                                     break;
283 283
                                 default:
284 284
                                     do_action(
285
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
285
+                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_'.$post_type.'_post_type',
286 286
                                         $WP_Query,
287 287
                                         $this
288 288
                                     );
@@ -307,11 +307,11 @@  discard block
 block discarded – undo
307 307
             // loop thru post_types as array
308 308
             foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
309 309
                 // is current query for an EE CPT ?
310
-                if (isset($this->_CPTs[ $post_type ])) {
310
+                if (isset($this->_CPTs[$post_type])) {
311 311
                     // is EE on or off ?
312 312
                     if (EE_Maintenance_Mode::instance()->level()) {
313 313
                         // reroute CPT template view to maintenance_mode.template.php
314
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
314
+                        if ( ! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
315 315
                             add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
316 316
                         }
317 317
                         if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
             'EventEspresso\core\CPTs\CptQueryModifier',
340 340
             array(
341 341
                 $post_type,
342
-                $this->_CPTs[ $post_type ],
342
+                $this->_CPTs[$post_type],
343 343
                 $WP_Query,
344 344
             )
345 345
         );
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_6_0.dms.php 1 patch
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -14,9 +14,9 @@  discard block
 block discarded – undo
14 14
 $stages = glob(EE_CORE . 'data_migration_scripts/4_6_0_stages/*');
15 15
 $class_to_filepath = array();
16 16
 foreach ($stages as $filepath) {
17
-    $matches = array();
18
-    preg_match('~4_6_0_stages/(.*).dmsstage.php~', $filepath, $matches);
19
-    $class_to_filepath[ $matches[1] ] = $filepath;
17
+	$matches = array();
18
+	preg_match('~4_6_0_stages/(.*).dmsstage.php~', $filepath, $matches);
19
+	$class_to_filepath[ $matches[1] ] = $filepath;
20 20
 }
21 21
 // give addons a chance to autoload their stages too
22 22
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_6_0__autoloaded_stages', $class_to_filepath);
@@ -35,69 +35,69 @@  discard block
 block discarded – undo
35 35
 class EE_DMS_Core_4_6_0 extends EE_Data_Migration_Script_Base
36 36
 {
37 37
 
38
-    /**
39
-     * return EE_DMS_Core_4_6_0
40
-     *
41
-     * @param TableManager  $table_manager
42
-     * @param TableAnalysis $table_analysis
43
-     */
44
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
45
-    {
46
-        $this->_pretty_name = __("Data Update to Event Espresso 4.6.0", "event_espresso");
47
-        $this->_priority = 10;
48
-        $this->_migration_stages = array(
49
-            new EE_DMS_4_6_0_gateways(),
50
-            new EE_DMS_4_6_0_question_types(),
51
-            new EE_DMS_4_6_0_country_system_question(),
52
-            new EE_DMS_4_6_0_state_system_question(),
53
-            new EE_DMS_4_6_0_billing_info(),
54
-            new EE_DMS_4_6_0_transactions(),
55
-            new EE_DMS_4_6_0_payments(),
56
-            new EE_DMS_4_6_0_invoice_settings(),
57
-        );
58
-        parent::__construct($table_manager, $table_analysis);
59
-    }
38
+	/**
39
+	 * return EE_DMS_Core_4_6_0
40
+	 *
41
+	 * @param TableManager  $table_manager
42
+	 * @param TableAnalysis $table_analysis
43
+	 */
44
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
45
+	{
46
+		$this->_pretty_name = __("Data Update to Event Espresso 4.6.0", "event_espresso");
47
+		$this->_priority = 10;
48
+		$this->_migration_stages = array(
49
+			new EE_DMS_4_6_0_gateways(),
50
+			new EE_DMS_4_6_0_question_types(),
51
+			new EE_DMS_4_6_0_country_system_question(),
52
+			new EE_DMS_4_6_0_state_system_question(),
53
+			new EE_DMS_4_6_0_billing_info(),
54
+			new EE_DMS_4_6_0_transactions(),
55
+			new EE_DMS_4_6_0_payments(),
56
+			new EE_DMS_4_6_0_invoice_settings(),
57
+		);
58
+		parent::__construct($table_manager, $table_analysis);
59
+	}
60 60
 
61 61
 
62 62
 
63
-    /**
64
-     * @param array $version_array
65
-     * @return bool
66
-     */
67
-    public function can_migrate_from_version($version_array)
68
-    {
69
-        $version_string = $version_array['Core'];
70
-        if (version_compare($version_string, '4.6.0', '<=') && version_compare($version_string, '4.5.0', '>=')) {
63
+	/**
64
+	 * @param array $version_array
65
+	 * @return bool
66
+	 */
67
+	public function can_migrate_from_version($version_array)
68
+	{
69
+		$version_string = $version_array['Core'];
70
+		if (version_compare($version_string, '4.6.0', '<=') && version_compare($version_string, '4.5.0', '>=')) {
71 71
 //          echo "$version_string can be migrated from";
72
-            return true;
73
-        } elseif (! $version_string) {
72
+			return true;
73
+		} elseif (! $version_string) {
74 74
 //          echo "no version string provided: $version_string";
75
-            // no version string provided... this must be pre 4.3
76
-            return false;// changed mind. dont want people thinking they should migrate yet because they cant
77
-        } else {
75
+			// no version string provided... this must be pre 4.3
76
+			return false;// changed mind. dont want people thinking they should migrate yet because they cant
77
+		} else {
78 78
 //          echo "$version_string doesnt apply";
79
-            return false;
80
-        }
81
-    }
79
+			return false;
80
+		}
81
+	}
82 82
 
83 83
 
84 84
 
85
-    /**
86
-     * @return bool
87
-     */
88
-    public function schema_changes_before_migration()
89
-    {
90
-        // relies on 4.1's EEH_Activation::create_table
91
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
92
-        $table_name = 'esp_answer';
93
-        $sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
85
+	/**
86
+	 * @return bool
87
+	 */
88
+	public function schema_changes_before_migration()
89
+	{
90
+		// relies on 4.1's EEH_Activation::create_table
91
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
92
+		$table_name = 'esp_answer';
93
+		$sql = " ANS_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
94 94
 					REG_ID INT UNSIGNED NOT NULL,
95 95
 					QST_ID INT UNSIGNED NOT NULL,
96 96
 					ANS_value TEXT NOT NULL,
97 97
 					PRIMARY KEY  (ANS_ID)";
98
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
99
-        $table_name = 'esp_attendee_meta';
100
-        $sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
98
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
99
+		$table_name = 'esp_attendee_meta';
100
+		$sql = "ATTM_ID INT(10) UNSIGNED NOT	NULL AUTO_INCREMENT,
101 101
 						ATT_ID BIGINT(20) UNSIGNED NOT NULL,
102 102
 						ATT_fname VARCHAR(45) NOT NULL,
103 103
 						ATT_lname VARCHAR(45) NOT	NULL,
@@ -113,9 +113,9 @@  discard block
 block discarded – undo
113 113
 								KEY ATT_fname (ATT_fname),
114 114
 								KEY ATT_lname (ATT_lname),
115 115
 								KEY ATT_email (ATT_email(191))";
116
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
117
-        $table_name = 'esp_country';
118
-        $sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
116
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
117
+		$table_name = 'esp_country';
118
+		$sql = "CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
119 119
 					  CNT_ISO3 VARCHAR(3) COLLATE utf8_bin NOT NULL,
120 120
 					  RGN_ID TINYINT(3) UNSIGNED DEFAULT NULL,
121 121
 					  CNT_name VARCHAR(45) COLLATE utf8_bin NOT NULL,
@@ -131,24 +131,24 @@  discard block
 block discarded – undo
131 131
 					  CNT_is_EU TINYINT(1) DEFAULT '0',
132 132
 					  CNT_active TINYINT(1) DEFAULT '0',
133 133
 					  PRIMARY KEY  (CNT_ISO)";
134
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
135
-        $table_name = 'esp_currency';
136
-        $sql = "CUR_code VARCHAR(6) COLLATE utf8_bin NOT NULL,
134
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
135
+		$table_name = 'esp_currency';
136
+		$sql = "CUR_code VARCHAR(6) COLLATE utf8_bin NOT NULL,
137 137
 				CUR_single VARCHAR(45) COLLATE utf8_bin DEFAULT 'dollar',
138 138
 				CUR_plural VARCHAR(45) COLLATE utf8_bin DEFAULT 'dollars',
139 139
 				CUR_sign VARCHAR(45) COLLATE utf8_bin DEFAULT '$',
140 140
 				CUR_dec_plc VARCHAR(1) COLLATE utf8_bin NOT NULL DEFAULT '2',
141 141
 				CUR_active TINYINT(1) DEFAULT '0',
142 142
 				PRIMARY KEY  (CUR_code)";
143
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
144
-        $table_name = 'esp_currency_payment_method';
145
-        $sql = "CPM_ID INT(11) NOT NULL AUTO_INCREMENT,
143
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
144
+		$table_name = 'esp_currency_payment_method';
145
+		$sql = "CPM_ID INT(11) NOT NULL AUTO_INCREMENT,
146 146
 				CUR_code  VARCHAR(6) COLLATE utf8_bin NOT NULL,
147 147
 				PMD_ID INT(11) NOT NULL,
148 148
 				PRIMARY KEY  (CPM_ID)";
149
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
150
-        $table_name = 'esp_datetime';
151
-        $sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
149
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
150
+		$table_name = 'esp_datetime';
151
+		$sql = "DTT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
152 152
 				  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
153 153
 				  DTT_name VARCHAR(255) NOT NULL DEFAULT '',
154 154
 				  DTT_description TEXT NOT NULL,
@@ -163,9 +163,9 @@  discard block
 block discarded – undo
163 163
 						PRIMARY KEY  (DTT_ID),
164 164
 						KEY EVT_ID (EVT_ID),
165 165
 						KEY DTT_is_primary (DTT_is_primary)";
166
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
167
-        $table_name = 'esp_event_meta';
168
-        $sql = "
166
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
167
+		$table_name = 'esp_event_meta';
168
+		$sql = "
169 169
 			EVTM_ID INT NOT NULL AUTO_INCREMENT,
170 170
 			EVT_ID BIGINT(20) UNSIGNED NOT NULL,
171 171
 			EVT_display_desc TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
@@ -180,31 +180,31 @@  discard block
 block discarded – undo
180 180
 			EVT_external_URL VARCHAR(200) NULL,
181 181
 			EVT_donations TINYINT(1) NULL,
182 182
 			PRIMARY KEY  (EVTM_ID)";
183
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
184
-        $table_name = 'esp_event_question_group';
185
-        $sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
183
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
184
+		$table_name = 'esp_event_question_group';
185
+		$sql = "EQG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
186 186
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL,
187 187
 					QSG_ID INT UNSIGNED NOT NULL,
188 188
 					EQG_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
189 189
 					PRIMARY KEY  (EQG_ID)";
190
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
191
-        $table_name = 'esp_event_venue';
192
-        $sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
190
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
191
+		$table_name = 'esp_event_venue';
192
+		$sql = "EVV_ID INT(11) NOT NULL AUTO_INCREMENT,
193 193
 				EVT_ID BIGINT(20) UNSIGNED NOT NULL,
194 194
 				VNU_ID BIGINT(20) UNSIGNED NOT NULL,
195 195
 				EVV_primary TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
196 196
 				PRIMARY KEY  (EVV_ID)";
197
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
198
-        $table_name = 'esp_extra_meta';
199
-        $sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
197
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
198
+		$table_name = 'esp_extra_meta';
199
+		$sql = "EXM_ID INT(11) NOT NULL AUTO_INCREMENT,
200 200
 				OBJ_ID INT(11) DEFAULT NULL,
201 201
 				EXM_type VARCHAR(45) DEFAULT NULL,
202 202
 				EXM_key VARCHAR(45) DEFAULT NULL,
203 203
 				EXM_value TEXT,
204 204
 				PRIMARY KEY  (EXM_ID)";
205
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
206
-        $table_name = 'esp_line_item';
207
-        $sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
205
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
206
+		$table_name = 'esp_line_item';
207
+		$sql = "LIN_ID INT(11) NOT NULL AUTO_INCREMENT,
208 208
 				LIN_code VARCHAR(245) NOT NULL DEFAULT '',
209 209
 				TXN_ID INT(11) DEFAULT NULL,
210 210
 				LIN_name VARCHAR(245) NOT NULL DEFAULT '',
@@ -220,9 +220,9 @@  discard block
 block discarded – undo
220 220
 				OBJ_ID INT(11) DEFAULT NULL,
221 221
 				OBJ_type VARCHAR(45)DEFAULT NULL,
222 222
 				PRIMARY KEY  (LIN_ID)";
223
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
224
-        $table_name = 'esp_log';
225
-        $sql = "LOG_ID INT(11) NOT NULL AUTO_INCREMENT,
223
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
224
+		$table_name = 'esp_log';
225
+		$sql = "LOG_ID INT(11) NOT NULL AUTO_INCREMENT,
226 226
 				LOG_time DATETIME DEFAULT NULL,
227 227
 				OBJ_ID VARCHAR(45) DEFAULT NULL,
228 228
 				OBJ_type VARCHAR(45) DEFAULT NULL,
@@ -230,19 +230,19 @@  discard block
 block discarded – undo
230 230
 				LOG_message TEXT,
231 231
 				LOG_wp_user INT(11) DEFAULT NULL,
232 232
 				PRIMARY KEY  (LOG_ID)";
233
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
234
-        $table_name = 'esp_message_template';
235
-        $sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
233
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
234
+		$table_name = 'esp_message_template';
235
+		$sql = "MTP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
236 236
 					GRP_ID INT(10) UNSIGNED NOT NULL,
237 237
 					MTP_context VARCHAR(50) NOT NULL,
238 238
 					MTP_template_field VARCHAR(30) NOT NULL,
239 239
 					MTP_content TEXT NOT NULL,
240 240
 					PRIMARY KEY  (MTP_ID),
241 241
 					KEY GRP_ID (GRP_ID)";
242
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
243
-        $this->_get_table_manager()->dropIndex('esp_message_template_group', 'EVT_ID');
244
-        $table_name = 'esp_message_template_group';
245
-        $sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
242
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
243
+		$this->_get_table_manager()->dropIndex('esp_message_template_group', 'EVT_ID');
244
+		$table_name = 'esp_message_template_group';
245
+		$sql = "GRP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
246 246
 					MTP_user_id INT(10) NOT NULL DEFAULT '1',
247 247
 					MTP_name VARCHAR(245) NOT NULL DEFAULT '',
248 248
 					MTP_description VARCHAR(245) NOT NULL DEFAULT '',
@@ -254,17 +254,17 @@  discard block
 block discarded – undo
254 254
 					MTP_is_active TINYINT(1) NOT NULL DEFAULT '1',
255 255
 					PRIMARY KEY  (GRP_ID),
256 256
 					KEY MTP_user_id (MTP_user_id)";
257
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
258
-        $table_name = 'esp_event_message_template';
259
-        $sql = "EMT_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
257
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
258
+		$table_name = 'esp_event_message_template';
259
+		$sql = "EMT_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
260 260
 					EVT_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
261 261
 					GRP_ID INT(10) UNSIGNED NOT NULL DEFAULT 0,
262 262
 					PRIMARY KEY  (EMT_ID),
263 263
 					KEY EVT_ID (EVT_ID),
264 264
 					KEY GRP_ID (GRP_ID)";
265
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
266
-        $table_name = 'esp_payment';
267
-        $sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
265
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
266
+		$table_name = 'esp_payment';
267
+		$sql = "PAY_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
268 268
 					TXN_ID INT(10) UNSIGNED DEFAULT NULL,
269 269
 					STS_ID VARCHAR(3) COLLATE utf8_bin DEFAULT NULL,
270 270
 					PAY_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -281,9 +281,9 @@  discard block
 block discarded – undo
281 281
 					PRIMARY KEY  (PAY_ID),
282 282
 					KEY TXN_ID (TXN_ID),
283 283
 					KEY PAY_timestamp (PAY_timestamp)";
284
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
285
-        $table_name = 'esp_payment_method';
286
-        $sql = "PMD_ID INT(11) NOT NULL AUTO_INCREMENT,
284
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
285
+		$table_name = 'esp_payment_method';
286
+		$sql = "PMD_ID INT(11) NOT NULL AUTO_INCREMENT,
287 287
 				PMD_type VARCHAR(124) DEFAULT NULL,
288 288
 				PMD_name VARCHAR(255) DEFAULT NULL,
289 289
 				PMD_desc TEXT,
@@ -298,28 +298,28 @@  discard block
 block discarded – undo
298 298
 				PMD_scope VARCHAR(255) NULL DEFAULT 'frontend',
299 299
 				PRIMARY KEY  (PMD_ID),
300 300
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug)";
301
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
302
-        $table_name = "esp_ticket_price";
303
-        $sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
301
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
302
+		$table_name = "esp_ticket_price";
303
+		$sql = "TKP_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
304 304
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
305 305
 					  PRC_ID INT(10) UNSIGNED NOT NULL,
306 306
 					  PRIMARY KEY  (TKP_ID)";
307
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
308
-        $table_name = "esp_datetime_ticket";
309
-        $sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
307
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
308
+		$table_name = "esp_datetime_ticket";
309
+		$sql = "DTK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
310 310
 					  DTT_ID INT(10) UNSIGNED NOT NULL,
311 311
 					  TKT_ID INT(10) UNSIGNED NOT NULL,
312 312
 					  PRIMARY KEY  (DTK_ID)";
313
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
314
-        $table_name = "esp_ticket_template";
315
-        $sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
313
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
314
+		$table_name = "esp_ticket_template";
315
+		$sql = "TTM_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
316 316
 					  TTM_name VARCHAR(45) NOT NULL,
317 317
 					  TTM_description TEXT,
318 318
 					  TTM_file VARCHAR(45),
319 319
 					  PRIMARY KEY  (TTM_ID)";
320
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
321
-        $table_name = 'esp_question';
322
-        $sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
320
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
321
+		$table_name = 'esp_question';
322
+		$sql = 'QST_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
323 323
 					QST_display_text TEXT NOT NULL,
324 324
 					QST_admin_label VARCHAR(255) NOT NULL,
325 325
 					QST_system VARCHAR(25) DEFAULT NULL,
@@ -331,25 +331,25 @@  discard block
 block discarded – undo
331 331
 					QST_wp_user BIGINT UNSIGNED NULL,
332 332
 					QST_deleted TINYINT UNSIGNED NOT NULL DEFAULT 0,
333 333
 					PRIMARY KEY  (QST_ID)';
334
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
335
-        $table_name = 'esp_question_group_question';
336
-        $sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
334
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
335
+		$table_name = 'esp_question_group_question';
336
+		$sql = "QGQ_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
337 337
 					QSG_ID INT UNSIGNED NOT NULL,
338 338
 					QST_ID INT UNSIGNED NOT NULL,
339 339
 					QGQ_order INT UNSIGNED NOT NULL DEFAULT 0,
340 340
 					PRIMARY KEY  (QGQ_ID) ";
341
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
342
-        $table_name = 'esp_question_option';
343
-        $sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
341
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
342
+		$table_name = 'esp_question_option';
343
+		$sql = "QSO_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
344 344
 					QSO_value VARCHAR(255) NOT NULL,
345 345
 					QSO_desc TEXT NOT NULL,
346 346
 					QST_ID INT UNSIGNED NOT NULL,
347 347
 					QSO_order INT UNSIGNED NOT NULL DEFAULT 0,
348 348
 					QSO_deleted TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
349 349
 					PRIMARY KEY  (QSO_ID)";
350
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
351
-        $table_name = 'esp_registration';
352
-        $sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
350
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
351
+		$table_name = 'esp_registration';
352
+		$sql = "REG_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
353 353
 					  EVT_ID BIGINT(20) UNSIGNED NOT NULL,
354 354
 					  ATT_ID BIGINT(20) UNSIGNED NOT NULL,
355 355
 					  TXN_ID INT(10) UNSIGNED NOT NULL,
@@ -372,25 +372,25 @@  discard block
 block discarded – undo
372 372
 					  KEY STS_ID (STS_ID),
373 373
 					  KEY REG_url_link (REG_url_link),
374 374
 					  KEY REG_code (REG_code)";
375
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
376
-        $table_name = 'esp_checkin';
377
-        $sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
375
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
376
+		$table_name = 'esp_checkin';
377
+		$sql = "CHK_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
378 378
 					REG_ID INT(10) UNSIGNED NOT NULL,
379 379
 					DTT_ID INT(10) UNSIGNED NOT NULL,
380 380
 					CHK_in TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
381 381
 					CHK_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
382 382
 					PRIMARY KEY  (CHK_ID)";
383
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
384
-        $table_name = 'esp_state';
385
-        $sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
383
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
384
+		$table_name = 'esp_state';
385
+		$sql = "STA_ID smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
386 386
 					  CNT_ISO VARCHAR(2) COLLATE utf8_bin NOT NULL,
387 387
 					  STA_abbrev VARCHAR(24) COLLATE utf8_bin NOT NULL,
388 388
 					  STA_name VARCHAR(100) COLLATE utf8_bin NOT NULL,
389 389
 					  STA_active TINYINT(1) DEFAULT '1',
390 390
 					  PRIMARY KEY  (STA_ID)";
391
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
392
-        $table_name = 'esp_status';
393
-        $sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
391
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
392
+		$table_name = 'esp_status';
393
+		$sql = "STS_ID VARCHAR(3) COLLATE utf8_bin NOT NULL,
394 394
 					  STS_code VARCHAR(45) COLLATE utf8_bin NOT NULL,
395 395
 					  STS_type set('event','registration','transaction','payment','email') COLLATE utf8_bin NOT NULL,
396 396
 					  STS_can_edit TINYINT(1) NOT NULL DEFAULT 0,
@@ -398,9 +398,9 @@  discard block
 block discarded – undo
398 398
 					  STS_open TINYINT(1) NOT NULL DEFAULT 1,
399 399
 					  UNIQUE KEY STS_ID_UNIQUE (STS_ID),
400 400
 					  KEY STS_type (STS_type)";
401
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
402
-        $table_name = 'esp_transaction';
403
-        $sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
401
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
402
+		$table_name = 'esp_transaction';
403
+		$sql = "TXN_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
404 404
 					  TXN_timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
405 405
 					  TXN_total DECIMAL(10,3) DEFAULT '0.00',
406 406
 					  TXN_paid DECIMAL(10,3) NOT NULL DEFAULT '0.00',
@@ -412,9 +412,9 @@  discard block
 block discarded – undo
412 412
 					  PRIMARY KEY  (TXN_ID),
413 413
 					  KEY TXN_timestamp (TXN_timestamp),
414 414
 					  KEY STS_ID (STS_ID)";
415
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
416
-        $table_name = 'esp_venue_meta';
417
-        $sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
415
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
416
+		$table_name = 'esp_venue_meta';
417
+		$sql = "VNUM_ID INT(11) NOT NULL AUTO_INCREMENT,
418 418
 			VNU_ID BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
419 419
 			VNU_address VARCHAR(255) DEFAULT NULL,
420 420
 			VNU_address2 VARCHAR(255) DEFAULT NULL,
@@ -432,10 +432,10 @@  discard block
 block discarded – undo
432 432
 			PRIMARY KEY  (VNUM_ID),
433 433
 			KEY STA_ID (STA_ID),
434 434
 			KEY CNT_ISO (CNT_ISO)";
435
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
436
-        // modified tables
437
-        $table_name = "esp_price";
438
-        $sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
435
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
436
+		// modified tables
437
+		$table_name = "esp_price";
438
+		$sql = "PRC_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
439 439
 					  PRT_ID TINYINT(3) UNSIGNED NOT NULL,
440 440
 					  PRC_amount DECIMAL(10,3) NOT NULL DEFAULT '0.00',
441 441
 					  PRC_name VARCHAR(245) NOT NULL,
@@ -447,9 +447,9 @@  discard block
 block discarded – undo
447 447
 					  PRC_wp_user BIGINT UNSIGNED NULL,
448 448
 					  PRC_parent INT(10) UNSIGNED DEFAULT 0,
449 449
 					  PRIMARY KEY  (PRC_ID)";
450
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
451
-        $table_name = "esp_price_type";
452
-        $sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
450
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
451
+		$table_name = "esp_price_type";
452
+		$sql = "PRT_ID TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
453 453
 				  PRT_name VARCHAR(45) NOT NULL,
454 454
 				  PBT_ID TINYINT(3) UNSIGNED NOT NULL DEFAULT '1',
455 455
 				  PRT_is_percent TINYINT(1) NOT NULL DEFAULT '0',
@@ -458,9 +458,9 @@  discard block
 block discarded – undo
458 458
 				  PRT_deleted TINYINT(1) NOT NULL DEFAULT '0',
459 459
 				  UNIQUE KEY PRT_name_UNIQUE (PRT_name),
460 460
 				  PRIMARY KEY  (PRT_ID)";
461
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
462
-        $table_name = "esp_ticket";
463
-        $sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
461
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB ');
462
+		$table_name = "esp_ticket";
463
+		$sql = "TKT_ID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
464 464
 					  TTM_ID INT(10) UNSIGNED NOT NULL,
465 465
 					  TKT_name VARCHAR(245) NOT NULL DEFAULT '',
466 466
 					  TKT_description TEXT NOT NULL,
@@ -481,10 +481,10 @@  discard block
 block discarded – undo
481 481
 					  TKT_parent INT(10) UNSIGNED DEFAULT '0',
482 482
 					  TKT_deleted TINYINT(1) NOT NULL DEFAULT '0',
483 483
 					  PRIMARY KEY  (TKT_ID)";
484
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
485
-        $this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
486
-        $table_name = 'esp_question_group';
487
-        $sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
484
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
485
+		$this->_get_table_manager()->dropIndex('esp_question_group', 'QSG_identifier_UNIQUE');
486
+		$table_name = 'esp_question_group';
487
+		$sql = 'QSG_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
488 488
 					QSG_name VARCHAR(255) NOT NULL,
489 489
 					QSG_identifier VARCHAR(100) NOT NULL,
490 490
 					QSG_desc TEXT NULL,
@@ -496,124 +496,124 @@  discard block
 block discarded – undo
496 496
 					QSG_wp_user BIGINT UNSIGNED NULL,
497 497
 					PRIMARY KEY  (QSG_ID),
498 498
 					UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier ASC)';
499
-        $this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
500
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
501
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
502
-        // (because many need to convert old string states to foreign keys into the states table)
503
-        $script_4_1_defaults->insert_default_states();
504
-        $script_4_1_defaults->insert_default_countries();
505
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
506
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
507
-        $script_4_5_defaults->insert_default_price_types();
508
-        $script_4_5_defaults->insert_default_prices();
509
-        $script_4_5_defaults->insert_default_tickets();
510
-        // setting up the config wp option pretty well counts as a 'schema change', or at least should happen here
511
-        EE_Config::instance()->update_espresso_config(false, true);
512
-        $this->add_default_admin_only_payments();
513
-        $this->insert_default_currencies();
514
-        return true;
515
-    }
499
+		$this->_table_should_exist_previously($table_name, $sql, 'ENGINE=InnoDB');
500
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
501
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
502
+		// (because many need to convert old string states to foreign keys into the states table)
503
+		$script_4_1_defaults->insert_default_states();
504
+		$script_4_1_defaults->insert_default_countries();
505
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
506
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
507
+		$script_4_5_defaults->insert_default_price_types();
508
+		$script_4_5_defaults->insert_default_prices();
509
+		$script_4_5_defaults->insert_default_tickets();
510
+		// setting up the config wp option pretty well counts as a 'schema change', or at least should happen here
511
+		EE_Config::instance()->update_espresso_config(false, true);
512
+		$this->add_default_admin_only_payments();
513
+		$this->insert_default_currencies();
514
+		return true;
515
+	}
516 516
 
517 517
 
518 518
 
519
-    /**
520
-     * @return boolean
521
-     */
522
-    public function schema_changes_after_migration()
523
-    {
524
-        return true;
525
-    }
519
+	/**
520
+	 * @return boolean
521
+	 */
522
+	public function schema_changes_after_migration()
523
+	{
524
+		return true;
525
+	}
526 526
 
527 527
 
528 528
 
529
-    public function migration_page_hooks()
530
-    {
531
-    }
529
+	public function migration_page_hooks()
530
+	{
531
+	}
532 532
 
533 533
 
534 534
 
535
-    public function add_default_admin_only_payments()
536
-    {
537
-        global $wpdb;
538
-        $table_name = $wpdb->prefix . "esp_payment_method";
539
-        $user_id = EEH_Activation::get_default_creator_id();
540
-        if ($this->_get_table_analysis()->tableExists($table_name)) {
541
-            $SQL = "SELECT COUNT( * ) FROM $table_name";
542
-            $existing_payment_methods = $wpdb->get_var($SQL);
543
-            $default_admin_only_payment_methods = apply_filters(
544
-                'FHEE__EEH_Activation__add_default_admin_only_payments__default_admin_only_payment_methods',
545
-                array(
546
-                    (string) __("Bank", 'event_espresso')        => __("Bank Draft", 'event_espresso'),
547
-                    (string) __("Cash", 'event_espresso')        => __("Cash Delivered Physically", 'event_espresso'),
548
-                    (string) __("Check", 'event_espresso')       => __("Paper Check", 'event_espresso'),
549
-                    (string) __("Credit Card", 'event_espresso') => __("Offline Credit Card Payment", 'event_espresso'),
550
-                    (string) __("Debit Card", 'event_espresso')  => __("Offline Debit Payment", 'event_espresso'),
551
-                    (string) __("Invoice", 'event_espresso')     => __(
552
-                        "Invoice received with monies included",
553
-                        'event_espresso'
554
-                    ),
555
-                    (string) __("Money Order", 'event_espresso') => '',
556
-                    (string) __("Paypal", 'event_espresso')      => __("Paypal eCheck, Invoice, etc", 'event_espresso'),
557
-                    (string) __('Other', 'event_espresso')       => __('Other method of payment', 'event_espresso'),
558
-                )
559
-            );
560
-            // make sure we hae payment method records for the following
561
-            // so admins can record payments for them from the admin page
562
-            foreach ($default_admin_only_payment_methods as $nicename => $description) {
563
-                $slug = sanitize_key($nicename);
564
-                // check that such a payment method exists
565
-                $exists = $wpdb->get_var($wpdb->prepare("SELECT count(*) FROM $table_name WHERE PMD_slug = %s", $slug));
566
-                if (! $exists) {
567
-                    $values = array(
568
-                        'PMD_type'       => 'Admin_Only',
569
-                        'PMD_name'       => $nicename,
570
-                        'PMD_admin_name' => $nicename,
571
-                        'PMD_admin_desc' => $description,
572
-                        'PMD_slug'       => $slug,
573
-                        'PMD_wp_user'    => $user_id,
574
-                        'PMD_scope'      => serialize(array('ADMIN')),
575
-                    );
576
-                    $success = $wpdb->insert(
577
-                        $table_name,
578
-                        $values,
579
-                        array(
580
-                            '%s',// PMD_type
581
-                            '%s',// PMD_name
582
-                            '%s',// PMD_admin_name
583
-                            '%s',// PMD_admin_desc
584
-                            '%s',// PMD_slug
585
-                            '%d',// PMD_wp_user
586
-                            '%s',// PMD_scope
587
-                        )
588
-                    );
589
-                    if (! $success) {
590
-                        $this->add_error(sprintf(__(
591
-                            "Could not insert new admin-only payment method with values %s during migration",
592
-                            "event_espresso"
593
-                        ), $this->_json_encode($values)));
594
-                    }
595
-                }
596
-            }
597
-        }
598
-    }
535
+	public function add_default_admin_only_payments()
536
+	{
537
+		global $wpdb;
538
+		$table_name = $wpdb->prefix . "esp_payment_method";
539
+		$user_id = EEH_Activation::get_default_creator_id();
540
+		if ($this->_get_table_analysis()->tableExists($table_name)) {
541
+			$SQL = "SELECT COUNT( * ) FROM $table_name";
542
+			$existing_payment_methods = $wpdb->get_var($SQL);
543
+			$default_admin_only_payment_methods = apply_filters(
544
+				'FHEE__EEH_Activation__add_default_admin_only_payments__default_admin_only_payment_methods',
545
+				array(
546
+					(string) __("Bank", 'event_espresso')        => __("Bank Draft", 'event_espresso'),
547
+					(string) __("Cash", 'event_espresso')        => __("Cash Delivered Physically", 'event_espresso'),
548
+					(string) __("Check", 'event_espresso')       => __("Paper Check", 'event_espresso'),
549
+					(string) __("Credit Card", 'event_espresso') => __("Offline Credit Card Payment", 'event_espresso'),
550
+					(string) __("Debit Card", 'event_espresso')  => __("Offline Debit Payment", 'event_espresso'),
551
+					(string) __("Invoice", 'event_espresso')     => __(
552
+						"Invoice received with monies included",
553
+						'event_espresso'
554
+					),
555
+					(string) __("Money Order", 'event_espresso') => '',
556
+					(string) __("Paypal", 'event_espresso')      => __("Paypal eCheck, Invoice, etc", 'event_espresso'),
557
+					(string) __('Other', 'event_espresso')       => __('Other method of payment', 'event_espresso'),
558
+				)
559
+			);
560
+			// make sure we hae payment method records for the following
561
+			// so admins can record payments for them from the admin page
562
+			foreach ($default_admin_only_payment_methods as $nicename => $description) {
563
+				$slug = sanitize_key($nicename);
564
+				// check that such a payment method exists
565
+				$exists = $wpdb->get_var($wpdb->prepare("SELECT count(*) FROM $table_name WHERE PMD_slug = %s", $slug));
566
+				if (! $exists) {
567
+					$values = array(
568
+						'PMD_type'       => 'Admin_Only',
569
+						'PMD_name'       => $nicename,
570
+						'PMD_admin_name' => $nicename,
571
+						'PMD_admin_desc' => $description,
572
+						'PMD_slug'       => $slug,
573
+						'PMD_wp_user'    => $user_id,
574
+						'PMD_scope'      => serialize(array('ADMIN')),
575
+					);
576
+					$success = $wpdb->insert(
577
+						$table_name,
578
+						$values,
579
+						array(
580
+							'%s',// PMD_type
581
+							'%s',// PMD_name
582
+							'%s',// PMD_admin_name
583
+							'%s',// PMD_admin_desc
584
+							'%s',// PMD_slug
585
+							'%d',// PMD_wp_user
586
+							'%s',// PMD_scope
587
+						)
588
+					);
589
+					if (! $success) {
590
+						$this->add_error(sprintf(__(
591
+							"Could not insert new admin-only payment method with values %s during migration",
592
+							"event_espresso"
593
+						), $this->_json_encode($values)));
594
+					}
595
+				}
596
+			}
597
+		}
598
+	}
599 599
 
600 600
 
601 601
 
602
-    /**
603
-     * insert_default_countries
604
-     *
605
-     * @static
606
-     * @return void
607
-     */
608
-    public function insert_default_currencies()
609
-    {
610
-        global $wpdb;
611
-        $currency_table = $wpdb->prefix . "esp_currency";
612
-        if ($this->_get_table_analysis()->tableExists($currency_table)) {
613
-            $SQL = "SELECT COUNT('CUR_code') FROM $currency_table";
614
-            $countries = $wpdb->get_var($SQL);
615
-            if (! $countries) {
616
-                $SQL = "INSERT INTO $currency_table
602
+	/**
603
+	 * insert_default_countries
604
+	 *
605
+	 * @static
606
+	 * @return void
607
+	 */
608
+	public function insert_default_currencies()
609
+	{
610
+		global $wpdb;
611
+		$currency_table = $wpdb->prefix . "esp_currency";
612
+		if ($this->_get_table_analysis()->tableExists($currency_table)) {
613
+			$SQL = "SELECT COUNT('CUR_code') FROM $currency_table";
614
+			$countries = $wpdb->get_var($SQL);
615
+			if (! $countries) {
616
+				$SQL = "INSERT INTO $currency_table
617 617
 				( CUR_code, CUR_single, CUR_plural, CUR_sign, CUR_dec_plc, CUR_active) VALUES
618 618
 				( 'EUR',  'Euro',  'Euros',  '€',  2,1),
619 619
 				( 'AED',  'Dirham',  'Dirhams', 'د.إ',2,1),
@@ -767,8 +767,8 @@  discard block
 block discarded – undo
767 767
 				( 'ZAR',  'Rand',  'Rands',  'R',  2,1),
768 768
 				( 'ZMK',  'Kwacha',  'Kwachas',  '',  2,1),
769 769
 				( 'ZWD', 'Dollar', 'Dollars', 'Z$', 2,1);";
770
-                $wpdb->query($SQL);
771
-            }
772
-        }
773
-    }
770
+				$wpdb->query($SQL);
771
+			}
772
+		}
773
+	}
774 774
 }
Please login to merge, or discard this patch.
core/libraries/batch/JobHandlers/RegistrationsReport.php 2 patches
Indentation   +504 added lines, -504 removed lines patch added patch discarded remove patch
@@ -31,524 +31,524 @@
 block discarded – undo
31 31
  */
32 32
 class RegistrationsReport extends JobHandlerFile
33 33
 {
34
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
35
-    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
36
-    /**
37
-     * Performs any necessary setup for starting the job. This is also a good
38
-     * place to setup the $job_arguments which will be used for subsequent HTTP requests
39
-     * when continue_job will be called
40
-     *
41
-     * @param JobParameters $job_parameters
42
-     * @throws BatchRequestException
43
-     * @return JobStepResponse
44
-     */
45
-    public function create_job(JobParameters $job_parameters)
46
-    {
47
-        $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
48
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
49
-            throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
50
-        }
51
-        $filepath = $this->create_file_from_job_with_name(
52
-            $job_parameters->job_id(),
53
-            $this->get_filename($event_id)
54
-        );
55
-        $job_parameters->add_extra_data('filepath', $filepath);
56
-        if ($job_parameters->request_datum('use_filters', false)) {
57
-            $query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
58
-        } else {
59
-            $query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
60
-                array(
61
-                    'OR'                 => array(
62
-                        // don't include registrations from failed or abandoned transactions...
63
-                        'Transaction.STS_ID' => array(
64
-                            'NOT IN',
65
-                            array(
66
-                                EEM_Transaction::failed_status_code,
67
-                                EEM_Transaction::abandoned_status_code,
68
-                            ),
69
-                        ),
70
-                        // unless the registration is approved, in which case include it regardless of transaction status
71
-                        'STS_ID'             => \EEM_Registration::status_id_approved,
72
-                    ),
73
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
74
-                ),
75
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
76
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
77
-                'caps'       => \EEM_Base::caps_read_admin,
78
-            ), $event_id);
79
-            if ($event_id) {
80
-                $query_params[0]['EVT_ID'] = $event_id;
81
-            } else {
82
-                $query_params['force_join'][] = 'Event';
83
-            }
84
-        }
85
-        if (! isset($query_params['force_join'])) {
86
-            $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
87
-        }
88
-        $job_parameters->add_extra_data('query_params', $query_params);
89
-        $question_labels = $this->_get_question_labels($query_params);
90
-        $job_parameters->add_extra_data('question_labels', $question_labels);
91
-        $job_parameters->set_job_size(
92
-            \EEM_Registration::instance()->count(
93
-                array_diff_key(
94
-                    $query_params,
95
-                    array_flip(
96
-                        array('limit')
97
-                    )
98
-                )
99
-            )
100
-        );
101
-        // we should also set the header columns
102
-        $csv_data_for_row = $this->get_csv_data_for(
103
-            $event_id,
104
-            0,
105
-            1,
106
-            $job_parameters->extra_datum('question_labels'),
107
-            $job_parameters->extra_datum('query_params')
108
-        );
109
-        EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
110
-        // if we actually processed a row there, record it
111
-        if ($job_parameters->job_size()) {
112
-            $job_parameters->mark_processed(1);
113
-        }
114
-        return new JobStepResponse(
115
-            $job_parameters,
116
-            __('Registrations report started successfully...', 'event_espresso')
117
-        );
118
-    }
34
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
35
+	// phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
36
+	/**
37
+	 * Performs any necessary setup for starting the job. This is also a good
38
+	 * place to setup the $job_arguments which will be used for subsequent HTTP requests
39
+	 * when continue_job will be called
40
+	 *
41
+	 * @param JobParameters $job_parameters
42
+	 * @throws BatchRequestException
43
+	 * @return JobStepResponse
44
+	 */
45
+	public function create_job(JobParameters $job_parameters)
46
+	{
47
+		$event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
48
+		if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
49
+			throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
50
+		}
51
+		$filepath = $this->create_file_from_job_with_name(
52
+			$job_parameters->job_id(),
53
+			$this->get_filename($event_id)
54
+		);
55
+		$job_parameters->add_extra_data('filepath', $filepath);
56
+		if ($job_parameters->request_datum('use_filters', false)) {
57
+			$query_params = maybe_unserialize(stripslashes($job_parameters->request_datum('filters', array())));
58
+		} else {
59
+			$query_params = apply_filters('FHEE__EE_Export__report_registration_for_event', array(
60
+				array(
61
+					'OR'                 => array(
62
+						// don't include registrations from failed or abandoned transactions...
63
+						'Transaction.STS_ID' => array(
64
+							'NOT IN',
65
+							array(
66
+								EEM_Transaction::failed_status_code,
67
+								EEM_Transaction::abandoned_status_code,
68
+							),
69
+						),
70
+						// unless the registration is approved, in which case include it regardless of transaction status
71
+						'STS_ID'             => \EEM_Registration::status_id_approved,
72
+					),
73
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
74
+				),
75
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
76
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
77
+				'caps'       => \EEM_Base::caps_read_admin,
78
+			), $event_id);
79
+			if ($event_id) {
80
+				$query_params[0]['EVT_ID'] = $event_id;
81
+			} else {
82
+				$query_params['force_join'][] = 'Event';
83
+			}
84
+		}
85
+		if (! isset($query_params['force_join'])) {
86
+			$query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
87
+		}
88
+		$job_parameters->add_extra_data('query_params', $query_params);
89
+		$question_labels = $this->_get_question_labels($query_params);
90
+		$job_parameters->add_extra_data('question_labels', $question_labels);
91
+		$job_parameters->set_job_size(
92
+			\EEM_Registration::instance()->count(
93
+				array_diff_key(
94
+					$query_params,
95
+					array_flip(
96
+						array('limit')
97
+					)
98
+				)
99
+			)
100
+		);
101
+		// we should also set the header columns
102
+		$csv_data_for_row = $this->get_csv_data_for(
103
+			$event_id,
104
+			0,
105
+			1,
106
+			$job_parameters->extra_datum('question_labels'),
107
+			$job_parameters->extra_datum('query_params')
108
+		);
109
+		EEH_Export::write_data_array_to_csv($filepath, $csv_data_for_row, true);
110
+		// if we actually processed a row there, record it
111
+		if ($job_parameters->job_size()) {
112
+			$job_parameters->mark_processed(1);
113
+		}
114
+		return new JobStepResponse(
115
+			$job_parameters,
116
+			__('Registrations report started successfully...', 'event_espresso')
117
+		);
118
+	}
119 119
 
120 120
 
121
-    /**
122
-     * Gets the filename
123
-     *
124
-     * @return string
125
-     */
126
-    protected function get_filename()
127
-    {
128
-        return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
129
-    }
121
+	/**
122
+	 * Gets the filename
123
+	 *
124
+	 * @return string
125
+	 */
126
+	protected function get_filename()
127
+	{
128
+		return sprintf("event-espresso-registrations-%s.csv", str_replace(':', '-', current_time('mysql')));
129
+	}
130 130
 
131 131
 
132
-    /**
133
-     * Gets the questions which are to be used for this report, so they
134
-     * can be remembered for later
135
-     *
136
-     * @param array $registration_query_params
137
-     * @return array question admin labels to be used for this report
138
-     */
139
-    protected function _get_question_labels($registration_query_params)
140
-    {
141
-        $where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
142
-        $question_query_params = array();
143
-        if ($where !== null) {
144
-            $question_query_params = array(
145
-                $this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
146
-            );
147
-        }
148
-        $question_query_params[0]['QST_system'] = array(
149
-            'NOT_IN',
150
-            array_keys(EEM_Attendee::instance()->system_question_to_attendee_field_mapping()),
151
-        );
152
-        if (apply_filters(
153
-            'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
154
-            false,
155
-            $registration_query_params
156
-        )) {
157
-            $question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
158
-        }
159
-        $question_query_params['group_by'] = array('QST_ID');
160
-        return array_unique(EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
161
-    }
132
+	/**
133
+	 * Gets the questions which are to be used for this report, so they
134
+	 * can be remembered for later
135
+	 *
136
+	 * @param array $registration_query_params
137
+	 * @return array question admin labels to be used for this report
138
+	 */
139
+	protected function _get_question_labels($registration_query_params)
140
+	{
141
+		$where = isset($registration_query_params[0]) ? $registration_query_params[0] : null;
142
+		$question_query_params = array();
143
+		if ($where !== null) {
144
+			$question_query_params = array(
145
+				$this->_change_registration_where_params_to_question_where_params($registration_query_params[0]),
146
+			);
147
+		}
148
+		$question_query_params[0]['QST_system'] = array(
149
+			'NOT_IN',
150
+			array_keys(EEM_Attendee::instance()->system_question_to_attendee_field_mapping()),
151
+		);
152
+		if (apply_filters(
153
+			'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport___get_question_labels__only_include_answered_questions',
154
+			false,
155
+			$registration_query_params
156
+		)) {
157
+			$question_query_params[0]['Answer.ANS_ID'] = array('IS_NOT_NULL');
158
+		}
159
+		$question_query_params['group_by'] = array('QST_ID');
160
+		return array_unique(EEM_Question::instance()->get_col($question_query_params, 'QST_admin_label'));
161
+	}
162 162
 
163 163
 
164
-    /**
165
-     * Takes where params meant for registrations and changes them to work for questions
166
-     *
167
-     * @param array $reg_where_params
168
-     * @return array
169
-     */
170
-    protected function _change_registration_where_params_to_question_where_params($reg_where_params)
171
-    {
172
-        $question_where_params = array();
173
-        foreach ($reg_where_params as $key => $val) {
174
-            if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
175
-                $question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
176
-            } else {
177
-                // it's a normal where condition
178
-                $question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
179
-            }
180
-        }
181
-        return $question_where_params;
182
-    }
164
+	/**
165
+	 * Takes where params meant for registrations and changes them to work for questions
166
+	 *
167
+	 * @param array $reg_where_params
168
+	 * @return array
169
+	 */
170
+	protected function _change_registration_where_params_to_question_where_params($reg_where_params)
171
+	{
172
+		$question_where_params = array();
173
+		foreach ($reg_where_params as $key => $val) {
174
+			if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
175
+				$question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
176
+			} else {
177
+				// it's a normal where condition
178
+				$question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
179
+			}
180
+		}
181
+		return $question_where_params;
182
+	}
183 183
 
184 184
 
185
-    /**
186
-     * Performs another step of the job
187
-     *
188
-     * @param JobParameters $job_parameters
189
-     * @param int           $batch_size
190
-     * @return JobStepResponse
191
-     * @throws \EE_Error
192
-     */
193
-    public function continue_job(JobParameters $job_parameters, $batch_size = 50)
194
-    {
195
-        if ($job_parameters->units_processed() < $job_parameters->job_size()) {
196
-            $csv_data = $this->get_csv_data_for(
197
-                $job_parameters->request_datum('EVT_ID', '0'),
198
-                $job_parameters->units_processed(),
199
-                $batch_size,
200
-                $job_parameters->extra_datum('question_labels'),
201
-                $job_parameters->extra_datum('query_params')
202
-            );
203
-            EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
204
-            $units_processed = count($csv_data);
205
-        } else {
206
-            $csv_data = array();
207
-            $units_processed = 0;
208
-        }
209
-        $job_parameters->mark_processed($units_processed);
210
-        $extra_response_data = array(
211
-            'file_url' => '',
212
-        );
213
-        if ($units_processed < $batch_size) {
214
-            $job_parameters->set_status(JobParameters::status_complete);
215
-            $extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
216
-        }
185
+	/**
186
+	 * Performs another step of the job
187
+	 *
188
+	 * @param JobParameters $job_parameters
189
+	 * @param int           $batch_size
190
+	 * @return JobStepResponse
191
+	 * @throws \EE_Error
192
+	 */
193
+	public function continue_job(JobParameters $job_parameters, $batch_size = 50)
194
+	{
195
+		if ($job_parameters->units_processed() < $job_parameters->job_size()) {
196
+			$csv_data = $this->get_csv_data_for(
197
+				$job_parameters->request_datum('EVT_ID', '0'),
198
+				$job_parameters->units_processed(),
199
+				$batch_size,
200
+				$job_parameters->extra_datum('question_labels'),
201
+				$job_parameters->extra_datum('query_params')
202
+			);
203
+			EEH_Export::write_data_array_to_csv($job_parameters->extra_datum('filepath'), $csv_data, false);
204
+			$units_processed = count($csv_data);
205
+		} else {
206
+			$csv_data = array();
207
+			$units_processed = 0;
208
+		}
209
+		$job_parameters->mark_processed($units_processed);
210
+		$extra_response_data = array(
211
+			'file_url' => '',
212
+		);
213
+		if ($units_processed < $batch_size) {
214
+			$job_parameters->set_status(JobParameters::status_complete);
215
+			$extra_response_data['file_url'] = $this->get_url_to_file($job_parameters->extra_datum('filepath'));
216
+		}
217 217
 
218
-        return new JobStepResponse(
219
-            $job_parameters,
220
-            sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count((array) $csv_data)),
221
-            $extra_response_data
222
-        );
223
-    }
218
+		return new JobStepResponse(
219
+			$job_parameters,
220
+			sprintf(__('Wrote %1$s rows to report CSV file...', 'event_espresso'), count((array) $csv_data)),
221
+			$extra_response_data
222
+		);
223
+	}
224 224
 
225 225
 
226
-    /**
227
-     * Gets the csv data for a batch of registrations
228
-     *
229
-     * @param int|null $event_id
230
-     * @param int $offset
231
-     * @param int $limit
232
-     * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
233
-     * @param array $query_params for using where querying the model
234
-     * @return array top-level keys are numeric, next-level keys are column headers
235
-     * @throws \EE_Error
236
-     */
237
-    public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
238
-    {
239
-        $reg_fields_to_include = array(
240
-            'TXN_ID',
241
-            'ATT_ID',
242
-            'REG_ID',
243
-            'REG_date',
244
-            'REG_code',
245
-            'REG_count',
246
-            'REG_final_price',
247
-        );
248
-        $att_fields_to_include = array(
249
-            'ATT_fname',
250
-            'ATT_lname',
251
-            'ATT_email',
252
-            'ATT_address',
253
-            'ATT_address2',
254
-            'ATT_city',
255
-            'STA_ID',
256
-            'CNT_ISO',
257
-            'ATT_zip',
258
-            'ATT_phone',
259
-        );
260
-        $registrations_csv_ready_array = array();
261
-        $reg_model = EE_Registry::instance()->load_model('Registration');
262
-        $query_params['limit'] = array($offset, $limit);
263
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
264
-        $registration_ids = array();
265
-        foreach ($registration_rows as $reg_row) {
266
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
267
-        }
268
-        foreach ($registration_rows as $reg_row) {
269
-            if (is_array($reg_row)) {
270
-                $reg_csv_array = array();
271
-                if (! $event_id) {
272
-                    // get the event's name and Id
273
-                    $reg_csv_array[ (string) __('Event', 'event_espresso') ] = sprintf(
274
-                        /* translators: 1: event name, 2: event ID */
275
-                        __('%1$s (%2$s)', 'event_espresso'),
276
-                        EEH_Export::prepare_value_from_db_for_display(
277
-                            EEM_Event::instance(),
278
-                            'EVT_name',
279
-                            $reg_row['Event_CPT.post_title']
280
-                        ),
281
-                        $reg_row['Event_CPT.ID']
282
-                    );
283
-                }
284
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
285
-                /*@var $reg_row EE_Registration */
286
-                foreach ($reg_fields_to_include as $field_name) {
287
-                    $field = $reg_model->field_settings_for($field_name);
288
-                    if ($field_name == 'REG_final_price') {
289
-                        $value = EEH_Export::prepare_value_from_db_for_display(
290
-                            $reg_model,
291
-                            $field_name,
292
-                            $reg_row['Registration.REG_final_price'],
293
-                            'localized_float'
294
-                        );
295
-                    } elseif ($field_name == 'REG_count') {
296
-                        $value = sprintf(
297
-                            /* translators: 1: number of registration in group (REG_count), 2: registration group size (REG_group_size) */
298
-                            __('%1$s of %2$s', 'event_espresso'),
299
-                            EEH_Export::prepare_value_from_db_for_display(
300
-                                $reg_model,
301
-                                'REG_count',
302
-                                $reg_row['Registration.REG_count']
303
-                            ),
304
-                            EEH_Export::prepare_value_from_db_for_display(
305
-                                $reg_model,
306
-                                'REG_group_size',
307
-                                $reg_row['Registration.REG_group_size']
308
-                            )
309
-                        );
310
-                    } elseif ($field_name == 'REG_date') {
311
-                        $value = EEH_Export::prepare_value_from_db_for_display(
312
-                            $reg_model,
313
-                            $field_name,
314
-                            $reg_row['Registration.REG_date'],
315
-                            'no_html'
316
-                        );
317
-                    } else {
318
-                        $value = EEH_Export::prepare_value_from_db_for_display(
319
-                            $reg_model,
320
-                            $field_name,
321
-                            $reg_row[ $field->get_qualified_column() ]
322
-                        );
323
-                    }
324
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = $value;
325
-                    if ($field_name == 'REG_final_price') {
326
-                        // add a column named Currency after the final price
327
-                        $reg_csv_array[ (string) __("Currency", "event_espresso") ] = \EE_Config::instance()->currency->code;
328
-                    }
329
-                }
330
-                // get pretty status
331
-                $stati = EEM_Status::instance()->localized_status(
332
-                    array(
333
-                        $reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
334
-                        $reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
335
-                    ),
336
-                    false,
337
-                    'sentence'
338
-                );
339
-                $reg_csv_array[ (string) __("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
340
-                // get pretty transaction status
341
-                $reg_csv_array[ (string) __("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
342
-                $reg_csv_array[ (string) __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
343
-                    ? EEH_Export::prepare_value_from_db_for_display(
344
-                        EEM_Transaction::instance(),
345
-                        'TXN_total',
346
-                        $reg_row['TransactionTable.TXN_total'],
347
-                        'localized_float'
348
-                    ) : '0.00';
349
-                $reg_csv_array[ (string) __('Amount Paid', 'event_espresso') ] = $is_primary_reg
350
-                    ? EEH_Export::prepare_value_from_db_for_display(
351
-                        EEM_Transaction::instance(),
352
-                        'TXN_paid',
353
-                        $reg_row['TransactionTable.TXN_paid'],
354
-                        'localized_float'
355
-                    ) : '0.00';
356
-                $payment_methods = array();
357
-                $gateway_txn_ids_etc = array();
358
-                $payment_times = array();
359
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
360
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
361
-                        array(
362
-                            array(
363
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
364
-                                'STS_ID' => EEM_Payment::status_id_approved,
365
-                            ),
366
-                            'force_join' => array('Payment_Method'),
367
-                        ),
368
-                        ARRAY_A,
369
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
370
-                    );
371
-                    foreach ($payments_info as $payment_method_and_gateway_txn_id) {
372
-                        $payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
373
-                            ? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
374
-                        $gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
375
-                            ? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
376
-                        $payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
377
-                            ? $payment_method_and_gateway_txn_id['payment_time'] : '';
378
-                    }
379
-                }
380
-                $reg_csv_array[ (string) __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
381
-                $reg_csv_array[ (string) __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
382
-                $reg_csv_array[ (string) __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
383
-                    ',',
384
-                    $gateway_txn_ids_etc
385
-                );
386
-                // get whether or not the user has checked in
387
-                $reg_csv_array[ (string) __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
388
-                    $reg_row['Registration.REG_ID'],
389
-                    'Checkin'
390
-                );
391
-                // get ticket of registration and its price
392
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
393
-                if ($reg_row['Ticket.TKT_ID']) {
394
-                    $ticket_name = EEH_Export::prepare_value_from_db_for_display(
395
-                        $ticket_model,
396
-                        'TKT_name',
397
-                        $reg_row['Ticket.TKT_name']
398
-                    );
399
-                    $datetimes_strings = array();
400
-                    foreach (EEM_Datetime::instance()->get_all_wpdb_results(
401
-                        array(
402
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
403
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
404
-                            'default_where_conditions' => 'none',
405
-                        )
406
-                    ) as $datetime) {
407
-                        $datetimes_strings[] = EEH_Export::prepare_value_from_db_for_display(
408
-                            EEM_Datetime::instance(),
409
-                            'DTT_EVT_start',
410
-                            $datetime['Datetime.DTT_EVT_start']
411
-                        );
412
-                    }
413
-                } else {
414
-                    $ticket_name = __('Unknown', 'event_espresso');
415
-                    $datetimes_strings = array(__('Unknown', 'event_espresso'));
416
-                }
417
-                $reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
418
-                $reg_csv_array[ (string) __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
419
-                // get datetime(s) of registration
420
-                // add attendee columns
421
-                foreach ($att_fields_to_include as $att_field_name) {
422
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
423
-                    if ($reg_row['Attendee_CPT.ID']) {
424
-                        if ($att_field_name == 'STA_ID') {
425
-                            $value = EEM_State::instance()->get_var(
426
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
427
-                                'STA_name'
428
-                            );
429
-                        } elseif ($att_field_name == 'CNT_ISO') {
430
-                            $value = EEM_Country::instance()->get_var(
431
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
432
-                                'CNT_name'
433
-                            );
434
-                        } else {
435
-                            $value = EEH_Export::prepare_value_from_db_for_display(
436
-                                EEM_Attendee::instance(),
437
-                                $att_field_name,
438
-                                $reg_row[ $field_obj->get_qualified_column() ]
439
-                            );
440
-                        }
441
-                    } else {
442
-                        $value = '';
443
-                    }
444
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
445
-                }
446
-                // make sure each registration has the same questions in the same order
447
-                foreach ($question_labels as $question_label) {
448
-                    if (! isset($reg_csv_array[ $question_label ])) {
449
-                        $reg_csv_array[ $question_label ] = null;
450
-                    }
451
-                }
452
-                $answers = EEM_Answer::instance()->get_all_wpdb_results(array(
453
-                    array('REG_ID' => $reg_row['Registration.REG_ID']),
454
-                    'force_join' => array('Question'),
455
-                ));
456
-                // now fill out the questions THEY answered
457
-                foreach ($answers as $answer_row) {
458
-                    if ($answer_row['Question.QST_ID']) {
459
-                        $question_label = EEH_Export::prepare_value_from_db_for_display(
460
-                            EEM_Question::instance(),
461
-                            'QST_admin_label',
462
-                            $answer_row['Question.QST_admin_label']
463
-                        );
464
-                    } else {
465
-                        $question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
466
-                    }
467
-                    if (isset($answer_row['Question.QST_type'])
468
-                        && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
469
-                    ) {
470
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
471
-                            $answer_row['Answer.ANS_value']
472
-                        );
473
-                    } else {
474
-                        // this isn't for html, so don't show html entities
475
-                        $reg_csv_array[ $question_label ] = html_entity_decode(
476
-                            EEH_Export::prepare_value_from_db_for_display(
477
-                                EEM_Answer::instance(),
478
-                                'ANS_value',
479
-                                $answer_row['Answer.ANS_value']
480
-                            )
481
-                        );
482
-                    }
483
-                }
226
+	/**
227
+	 * Gets the csv data for a batch of registrations
228
+	 *
229
+	 * @param int|null $event_id
230
+	 * @param int $offset
231
+	 * @param int $limit
232
+	 * @param array $question_labels the IDs for all the questions which were answered by someone in this selection
233
+	 * @param array $query_params for using where querying the model
234
+	 * @return array top-level keys are numeric, next-level keys are column headers
235
+	 * @throws \EE_Error
236
+	 */
237
+	public function get_csv_data_for($event_id, $offset, $limit, $question_labels, $query_params)
238
+	{
239
+		$reg_fields_to_include = array(
240
+			'TXN_ID',
241
+			'ATT_ID',
242
+			'REG_ID',
243
+			'REG_date',
244
+			'REG_code',
245
+			'REG_count',
246
+			'REG_final_price',
247
+		);
248
+		$att_fields_to_include = array(
249
+			'ATT_fname',
250
+			'ATT_lname',
251
+			'ATT_email',
252
+			'ATT_address',
253
+			'ATT_address2',
254
+			'ATT_city',
255
+			'STA_ID',
256
+			'CNT_ISO',
257
+			'ATT_zip',
258
+			'ATT_phone',
259
+		);
260
+		$registrations_csv_ready_array = array();
261
+		$reg_model = EE_Registry::instance()->load_model('Registration');
262
+		$query_params['limit'] = array($offset, $limit);
263
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
264
+		$registration_ids = array();
265
+		foreach ($registration_rows as $reg_row) {
266
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
267
+		}
268
+		foreach ($registration_rows as $reg_row) {
269
+			if (is_array($reg_row)) {
270
+				$reg_csv_array = array();
271
+				if (! $event_id) {
272
+					// get the event's name and Id
273
+					$reg_csv_array[ (string) __('Event', 'event_espresso') ] = sprintf(
274
+						/* translators: 1: event name, 2: event ID */
275
+						__('%1$s (%2$s)', 'event_espresso'),
276
+						EEH_Export::prepare_value_from_db_for_display(
277
+							EEM_Event::instance(),
278
+							'EVT_name',
279
+							$reg_row['Event_CPT.post_title']
280
+						),
281
+						$reg_row['Event_CPT.ID']
282
+					);
283
+				}
284
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
285
+				/*@var $reg_row EE_Registration */
286
+				foreach ($reg_fields_to_include as $field_name) {
287
+					$field = $reg_model->field_settings_for($field_name);
288
+					if ($field_name == 'REG_final_price') {
289
+						$value = EEH_Export::prepare_value_from_db_for_display(
290
+							$reg_model,
291
+							$field_name,
292
+							$reg_row['Registration.REG_final_price'],
293
+							'localized_float'
294
+						);
295
+					} elseif ($field_name == 'REG_count') {
296
+						$value = sprintf(
297
+							/* translators: 1: number of registration in group (REG_count), 2: registration group size (REG_group_size) */
298
+							__('%1$s of %2$s', 'event_espresso'),
299
+							EEH_Export::prepare_value_from_db_for_display(
300
+								$reg_model,
301
+								'REG_count',
302
+								$reg_row['Registration.REG_count']
303
+							),
304
+							EEH_Export::prepare_value_from_db_for_display(
305
+								$reg_model,
306
+								'REG_group_size',
307
+								$reg_row['Registration.REG_group_size']
308
+							)
309
+						);
310
+					} elseif ($field_name == 'REG_date') {
311
+						$value = EEH_Export::prepare_value_from_db_for_display(
312
+							$reg_model,
313
+							$field_name,
314
+							$reg_row['Registration.REG_date'],
315
+							'no_html'
316
+						);
317
+					} else {
318
+						$value = EEH_Export::prepare_value_from_db_for_display(
319
+							$reg_model,
320
+							$field_name,
321
+							$reg_row[ $field->get_qualified_column() ]
322
+						);
323
+					}
324
+					$reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = $value;
325
+					if ($field_name == 'REG_final_price') {
326
+						// add a column named Currency after the final price
327
+						$reg_csv_array[ (string) __("Currency", "event_espresso") ] = \EE_Config::instance()->currency->code;
328
+					}
329
+				}
330
+				// get pretty status
331
+				$stati = EEM_Status::instance()->localized_status(
332
+					array(
333
+						$reg_row['Registration.STS_ID']     => __('unknown', 'event_espresso'),
334
+						$reg_row['TransactionTable.STS_ID'] => __('unknown', 'event_espresso'),
335
+					),
336
+					false,
337
+					'sentence'
338
+				);
339
+				$reg_csv_array[ (string) __("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
340
+				// get pretty transaction status
341
+				$reg_csv_array[ (string) __("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
342
+				$reg_csv_array[ (string) __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
343
+					? EEH_Export::prepare_value_from_db_for_display(
344
+						EEM_Transaction::instance(),
345
+						'TXN_total',
346
+						$reg_row['TransactionTable.TXN_total'],
347
+						'localized_float'
348
+					) : '0.00';
349
+				$reg_csv_array[ (string) __('Amount Paid', 'event_espresso') ] = $is_primary_reg
350
+					? EEH_Export::prepare_value_from_db_for_display(
351
+						EEM_Transaction::instance(),
352
+						'TXN_paid',
353
+						$reg_row['TransactionTable.TXN_paid'],
354
+						'localized_float'
355
+					) : '0.00';
356
+				$payment_methods = array();
357
+				$gateway_txn_ids_etc = array();
358
+				$payment_times = array();
359
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
360
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
361
+						array(
362
+							array(
363
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
364
+								'STS_ID' => EEM_Payment::status_id_approved,
365
+							),
366
+							'force_join' => array('Payment_Method'),
367
+						),
368
+						ARRAY_A,
369
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
370
+					);
371
+					foreach ($payments_info as $payment_method_and_gateway_txn_id) {
372
+						$payment_methods[] = isset($payment_method_and_gateway_txn_id['name'])
373
+							? $payment_method_and_gateway_txn_id['name'] : __('Unknown', 'event_espresso');
374
+						$gateway_txn_ids_etc[] = isset($payment_method_and_gateway_txn_id['gateway_txn_id'])
375
+							? $payment_method_and_gateway_txn_id['gateway_txn_id'] : '';
376
+						$payment_times[] = isset($payment_method_and_gateway_txn_id['payment_time'])
377
+							? $payment_method_and_gateway_txn_id['payment_time'] : '';
378
+					}
379
+				}
380
+				$reg_csv_array[ (string) __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
381
+				$reg_csv_array[ (string) __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
382
+				$reg_csv_array[ (string) __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
383
+					',',
384
+					$gateway_txn_ids_etc
385
+				);
386
+				// get whether or not the user has checked in
387
+				$reg_csv_array[ (string) __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
388
+					$reg_row['Registration.REG_ID'],
389
+					'Checkin'
390
+				);
391
+				// get ticket of registration and its price
392
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
393
+				if ($reg_row['Ticket.TKT_ID']) {
394
+					$ticket_name = EEH_Export::prepare_value_from_db_for_display(
395
+						$ticket_model,
396
+						'TKT_name',
397
+						$reg_row['Ticket.TKT_name']
398
+					);
399
+					$datetimes_strings = array();
400
+					foreach (EEM_Datetime::instance()->get_all_wpdb_results(
401
+						array(
402
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
403
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
404
+							'default_where_conditions' => 'none',
405
+						)
406
+					) as $datetime) {
407
+						$datetimes_strings[] = EEH_Export::prepare_value_from_db_for_display(
408
+							EEM_Datetime::instance(),
409
+							'DTT_EVT_start',
410
+							$datetime['Datetime.DTT_EVT_start']
411
+						);
412
+					}
413
+				} else {
414
+					$ticket_name = __('Unknown', 'event_espresso');
415
+					$datetimes_strings = array(__('Unknown', 'event_espresso'));
416
+				}
417
+				$reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
418
+				$reg_csv_array[ (string) __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
419
+				// get datetime(s) of registration
420
+				// add attendee columns
421
+				foreach ($att_fields_to_include as $att_field_name) {
422
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
423
+					if ($reg_row['Attendee_CPT.ID']) {
424
+						if ($att_field_name == 'STA_ID') {
425
+							$value = EEM_State::instance()->get_var(
426
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
427
+								'STA_name'
428
+							);
429
+						} elseif ($att_field_name == 'CNT_ISO') {
430
+							$value = EEM_Country::instance()->get_var(
431
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
432
+								'CNT_name'
433
+							);
434
+						} else {
435
+							$value = EEH_Export::prepare_value_from_db_for_display(
436
+								EEM_Attendee::instance(),
437
+								$att_field_name,
438
+								$reg_row[ $field_obj->get_qualified_column() ]
439
+							);
440
+						}
441
+					} else {
442
+						$value = '';
443
+					}
444
+					$reg_csv_array[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
445
+				}
446
+				// make sure each registration has the same questions in the same order
447
+				foreach ($question_labels as $question_label) {
448
+					if (! isset($reg_csv_array[ $question_label ])) {
449
+						$reg_csv_array[ $question_label ] = null;
450
+					}
451
+				}
452
+				$answers = EEM_Answer::instance()->get_all_wpdb_results(array(
453
+					array('REG_ID' => $reg_row['Registration.REG_ID']),
454
+					'force_join' => array('Question'),
455
+				));
456
+				// now fill out the questions THEY answered
457
+				foreach ($answers as $answer_row) {
458
+					if ($answer_row['Question.QST_ID']) {
459
+						$question_label = EEH_Export::prepare_value_from_db_for_display(
460
+							EEM_Question::instance(),
461
+							'QST_admin_label',
462
+							$answer_row['Question.QST_admin_label']
463
+						);
464
+					} else {
465
+						$question_label = sprintf(__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
466
+					}
467
+					if (isset($answer_row['Question.QST_type'])
468
+						&& $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
469
+					) {
470
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
471
+							$answer_row['Answer.ANS_value']
472
+						);
473
+					} else {
474
+						// this isn't for html, so don't show html entities
475
+						$reg_csv_array[ $question_label ] = html_entity_decode(
476
+							EEH_Export::prepare_value_from_db_for_display(
477
+								EEM_Answer::instance(),
478
+								'ANS_value',
479
+								$answer_row['Answer.ANS_value']
480
+							)
481
+						);
482
+					}
483
+				}
484 484
 
485
-                /**
486
-                 * Filter to change the contents of each row of the registrations report CSV file.
487
-                 * This can be used to add or remote columns from the CSV file, or change their values.
488
-                 * Note when using: all rows in the CSV should have the same columns.
489
-                 * @param array $reg_csv_array keys are the column names, values are their cell values
490
-                 * @param array $reg_row one entry from EEM_Registration::get_all_wpdb_results()
491
-                 */
492
-                $registrations_csv_ready_array[] = apply_filters(
493
-                    'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
494
-                    $reg_csv_array,
495
-                    $reg_row
496
-                );
497
-            }
498
-        }
499
-        // if we couldn't export anything, we want to at least show the column headers
500
-        if (empty($registrations_csv_ready_array)) {
501
-            $reg_csv_array = array();
502
-            $model_and_fields_to_include = array(
503
-                'Registration' => $reg_fields_to_include,
504
-                'Attendee'     => $att_fields_to_include,
505
-            );
506
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
507
-                $model = EE_Registry::instance()->load_model($model_name);
508
-                foreach ($field_list as $field_name) {
509
-                    $field = $model->field_settings_for($field_name);
510
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
511
-                }
512
-            }
513
-            $registrations_csv_ready_array[] = $reg_csv_array;
514
-        }
515
-        return $registrations_csv_ready_array;
516
-    }
485
+				/**
486
+				 * Filter to change the contents of each row of the registrations report CSV file.
487
+				 * This can be used to add or remote columns from the CSV file, or change their values.
488
+				 * Note when using: all rows in the CSV should have the same columns.
489
+				 * @param array $reg_csv_array keys are the column names, values are their cell values
490
+				 * @param array $reg_row one entry from EEM_Registration::get_all_wpdb_results()
491
+				 */
492
+				$registrations_csv_ready_array[] = apply_filters(
493
+					'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
494
+					$reg_csv_array,
495
+					$reg_row
496
+				);
497
+			}
498
+		}
499
+		// if we couldn't export anything, we want to at least show the column headers
500
+		if (empty($registrations_csv_ready_array)) {
501
+			$reg_csv_array = array();
502
+			$model_and_fields_to_include = array(
503
+				'Registration' => $reg_fields_to_include,
504
+				'Attendee'     => $att_fields_to_include,
505
+			);
506
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
507
+				$model = EE_Registry::instance()->load_model($model_name);
508
+				foreach ($field_list as $field_name) {
509
+					$field = $model->field_settings_for($field_name);
510
+					$reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
511
+				}
512
+			}
513
+			$registrations_csv_ready_array[] = $reg_csv_array;
514
+		}
515
+		return $registrations_csv_ready_array;
516
+	}
517 517
 
518 518
 
519
-    /**
520
-     * Counts total unit to process
521
-     *
522
-     * @deprecated since 4.9.19
523
-     * @param int|array $event_id
524
-     * @return int
525
-     */
526
-    public function count_units_to_process($event_id)
527
-    {
528
-        // use the legacy filter
529
-        if ($event_id) {
530
-            $query_params[0]['EVT_ID'] = $event_id;
531
-        } else {
532
-            $query_params['force_join'][] = 'Event';
533
-        }
534
-        return \EEM_Registration::instance()->count($query_params);
535
-    }
519
+	/**
520
+	 * Counts total unit to process
521
+	 *
522
+	 * @deprecated since 4.9.19
523
+	 * @param int|array $event_id
524
+	 * @return int
525
+	 */
526
+	public function count_units_to_process($event_id)
527
+	{
528
+		// use the legacy filter
529
+		if ($event_id) {
530
+			$query_params[0]['EVT_ID'] = $event_id;
531
+		} else {
532
+			$query_params['force_join'][] = 'Event';
533
+		}
534
+		return \EEM_Registration::instance()->count($query_params);
535
+	}
536 536
 
537 537
 
538
-    /**
539
-     * Performs any clean-up logic when we know the job is completed.
540
-     * In this case, we delete the temporary file
541
-     *
542
-     * @param JobParameters $job_parameters
543
-     * @return boolean
544
-     */
545
-    public function cleanup_job(JobParameters $job_parameters)
546
-    {
547
-        $this->_file_helper->delete(
548
-            \EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
549
-            true,
550
-            'd'
551
-        );
552
-        return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
553
-    }
538
+	/**
539
+	 * Performs any clean-up logic when we know the job is completed.
540
+	 * In this case, we delete the temporary file
541
+	 *
542
+	 * @param JobParameters $job_parameters
543
+	 * @return boolean
544
+	 */
545
+	public function cleanup_job(JobParameters $job_parameters)
546
+	{
547
+		$this->_file_helper->delete(
548
+			\EEH_File::remove_filename_from_filepath($job_parameters->extra_datum('filepath')),
549
+			true,
550
+			'd'
551
+		);
552
+		return new JobStepResponse($job_parameters, __('Cleaned up temporary file', 'event_espresso'));
553
+	}
554 554
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
     public function create_job(JobParameters $job_parameters)
46 46
     {
47 47
         $event_id = intval($job_parameters->request_datum('EVT_ID', '0'));
48
-        if (! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
48
+        if ( ! \EE_Capabilities::instance()->current_user_can('ee_read_registrations', 'generating_report')) {
49 49
             throw new BatchRequestException(__('You do not have permission to view registrations', 'event_espresso'));
50 50
         }
51 51
         $filepath = $this->create_file_from_job_with_name(
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
                 $query_params['force_join'][] = 'Event';
83 83
             }
84 84
         }
85
-        if (! isset($query_params['force_join'])) {
85
+        if ( ! isset($query_params['force_join'])) {
86 86
             $query_params['force_join'] = array('Event', 'Transaction', 'Ticket', 'Attendee');
87 87
         }
88 88
         $job_parameters->add_extra_data('query_params', $query_params);
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
         $question_where_params = array();
173 173
         foreach ($reg_where_params as $key => $val) {
174 174
             if (\EEM_Registration::instance()->is_logic_query_param_key($key)) {
175
-                $question_where_params[ $key ] = $this->_change_registration_where_params_to_question_where_params($val);
175
+                $question_where_params[$key] = $this->_change_registration_where_params_to_question_where_params($val);
176 176
             } else {
177 177
                 // it's a normal where condition
178
-                $question_where_params[ 'Question_Group.Event.Registration.' . $key ] = $val;
178
+                $question_where_params['Question_Group.Event.Registration.'.$key] = $val;
179 179
             }
180 180
         }
181 181
         return $question_where_params;
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
         foreach ($registration_rows as $reg_row) {
269 269
             if (is_array($reg_row)) {
270 270
                 $reg_csv_array = array();
271
-                if (! $event_id) {
271
+                if ( ! $event_id) {
272 272
                     // get the event's name and Id
273
-                    $reg_csv_array[ (string) __('Event', 'event_espresso') ] = sprintf(
273
+                    $reg_csv_array[(string) __('Event', 'event_espresso')] = sprintf(
274 274
                         /* translators: 1: event name, 2: event ID */
275 275
                         __('%1$s (%2$s)', 'event_espresso'),
276 276
                         EEH_Export::prepare_value_from_db_for_display(
@@ -318,13 +318,13 @@  discard block
 block discarded – undo
318 318
                         $value = EEH_Export::prepare_value_from_db_for_display(
319 319
                             $reg_model,
320 320
                             $field_name,
321
-                            $reg_row[ $field->get_qualified_column() ]
321
+                            $reg_row[$field->get_qualified_column()]
322 322
                         );
323 323
                     }
324
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = $value;
324
+                    $reg_csv_array[EEH_Export::get_column_name_for_field($field)] = $value;
325 325
                     if ($field_name == 'REG_final_price') {
326 326
                         // add a column named Currency after the final price
327
-                        $reg_csv_array[ (string) __("Currency", "event_espresso") ] = \EE_Config::instance()->currency->code;
327
+                        $reg_csv_array[(string) __("Currency", "event_espresso")] = \EE_Config::instance()->currency->code;
328 328
                     }
329 329
                 }
330 330
                 // get pretty status
@@ -336,17 +336,17 @@  discard block
 block discarded – undo
336 336
                     false,
337 337
                     'sentence'
338 338
                 );
339
-                $reg_csv_array[ (string) __("Registration Status", 'event_espresso') ] = $stati[ $reg_row['Registration.STS_ID'] ];
339
+                $reg_csv_array[(string) __("Registration Status", 'event_espresso')] = $stati[$reg_row['Registration.STS_ID']];
340 340
                 // get pretty transaction status
341
-                $reg_csv_array[ (string) __("Transaction Status", 'event_espresso') ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
342
-                $reg_csv_array[ (string) __('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
341
+                $reg_csv_array[(string) __("Transaction Status", 'event_espresso')] = $stati[$reg_row['TransactionTable.STS_ID']];
342
+                $reg_csv_array[(string) __('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
343 343
                     ? EEH_Export::prepare_value_from_db_for_display(
344 344
                         EEM_Transaction::instance(),
345 345
                         'TXN_total',
346 346
                         $reg_row['TransactionTable.TXN_total'],
347 347
                         'localized_float'
348 348
                     ) : '0.00';
349
-                $reg_csv_array[ (string) __('Amount Paid', 'event_espresso') ] = $is_primary_reg
349
+                $reg_csv_array[(string) __('Amount Paid', 'event_espresso')] = $is_primary_reg
350 350
                     ? EEH_Export::prepare_value_from_db_for_display(
351 351
                         EEM_Transaction::instance(),
352 352
                         'TXN_paid',
@@ -377,14 +377,14 @@  discard block
 block discarded – undo
377 377
                             ? $payment_method_and_gateway_txn_id['payment_time'] : '';
378 378
                     }
379 379
                 }
380
-                $reg_csv_array[ (string) __('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
381
-                $reg_csv_array[ (string) __('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
382
-                $reg_csv_array[ (string) __('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
380
+                $reg_csv_array[(string) __('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
381
+                $reg_csv_array[(string) __('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
382
+                $reg_csv_array[(string) __('Gateway Transaction ID(s)', 'event_espresso')] = implode(
383 383
                     ',',
384 384
                     $gateway_txn_ids_etc
385 385
                 );
386 386
                 // get whether or not the user has checked in
387
-                $reg_csv_array[ (string) __("Check-Ins", "event_espresso") ] = $reg_model->count_related(
387
+                $reg_csv_array[(string) __("Check-Ins", "event_espresso")] = $reg_model->count_related(
388 388
                     $reg_row['Registration.REG_ID'],
389 389
                     'Checkin'
390 390
                 );
@@ -414,8 +414,8 @@  discard block
 block discarded – undo
414 414
                     $ticket_name = __('Unknown', 'event_espresso');
415 415
                     $datetimes_strings = array(__('Unknown', 'event_espresso'));
416 416
                 }
417
-                $reg_csv_array[ (string) $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
418
-                $reg_csv_array[ (string) __("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
417
+                $reg_csv_array[(string) $ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
418
+                $reg_csv_array[(string) __("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
419 419
                 // get datetime(s) of registration
420 420
                 // add attendee columns
421 421
                 foreach ($att_fields_to_include as $att_field_name) {
@@ -435,18 +435,18 @@  discard block
 block discarded – undo
435 435
                             $value = EEH_Export::prepare_value_from_db_for_display(
436 436
                                 EEM_Attendee::instance(),
437 437
                                 $att_field_name,
438
-                                $reg_row[ $field_obj->get_qualified_column() ]
438
+                                $reg_row[$field_obj->get_qualified_column()]
439 439
                             );
440 440
                         }
441 441
                     } else {
442 442
                         $value = '';
443 443
                     }
444
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field_obj) ] = $value;
444
+                    $reg_csv_array[EEH_Export::get_column_name_for_field($field_obj)] = $value;
445 445
                 }
446 446
                 // make sure each registration has the same questions in the same order
447 447
                 foreach ($question_labels as $question_label) {
448
-                    if (! isset($reg_csv_array[ $question_label ])) {
449
-                        $reg_csv_array[ $question_label ] = null;
448
+                    if ( ! isset($reg_csv_array[$question_label])) {
449
+                        $reg_csv_array[$question_label] = null;
450 450
                     }
451 451
                 }
452 452
                 $answers = EEM_Answer::instance()->get_all_wpdb_results(array(
@@ -467,12 +467,12 @@  discard block
 block discarded – undo
467 467
                     if (isset($answer_row['Question.QST_type'])
468 468
                         && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state
469 469
                     ) {
470
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
470
+                        $reg_csv_array[$question_label] = EEM_State::instance()->get_state_name_by_ID(
471 471
                             $answer_row['Answer.ANS_value']
472 472
                         );
473 473
                     } else {
474 474
                         // this isn't for html, so don't show html entities
475
-                        $reg_csv_array[ $question_label ] = html_entity_decode(
475
+                        $reg_csv_array[$question_label] = html_entity_decode(
476 476
                             EEH_Export::prepare_value_from_db_for_display(
477 477
                                 EEM_Answer::instance(),
478 478
                                 'ANS_value',
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
                 $model = EE_Registry::instance()->load_model($model_name);
508 508
                 foreach ($field_list as $field_name) {
509 509
                     $field = $model->field_settings_for($field_name);
510
-                    $reg_csv_array[ EEH_Export::get_column_name_for_field($field) ] = null;
510
+                    $reg_csv_array[EEH_Export::get_column_name_for_field($field)] = null;
511 511
                 }
512 512
             }
513 513
             $registrations_csv_ready_array[] = $reg_csv_array;
Please login to merge, or discard this patch.
core/services/assets/BlockAssetManager.php 2 patches
Indentation   +305 added lines, -305 removed lines patch added patch discarded remove patch
@@ -22,310 +22,310 @@
 block discarded – undo
22 22
 abstract class BlockAssetManager extends AssetManager implements BlockAssetManagerInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var string $editor_script_handle
27
-     */
28
-    private $editor_script_handle;
29
-
30
-    /**
31
-     * @var string $editor_style_handle
32
-     */
33
-    private $editor_style_handle;
34
-
35
-    /**
36
-     * @var string $script_handle
37
-     */
38
-    private $script_handle;
39
-
40
-    /**
41
-     * @var string $style_handle
42
-     */
43
-    private $style_handle;
44
-
45
-
46
-    /**
47
-     * @return string
48
-     */
49
-    public function getEditorScriptHandle()
50
-    {
51
-        return $this->editor_script_handle;
52
-    }
53
-
54
-
55
-    /**
56
-     * @param string $editor_script_handle
57
-     */
58
-    public function setEditorScriptHandle($editor_script_handle)
59
-    {
60
-        if(strpos($editor_script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
61
-            $editor_script_handle = BlockInterface::NAME_SPACE . '-' . $editor_script_handle;
62
-        }
63
-        $this->editor_script_handle = $editor_script_handle;
64
-    }
65
-
66
-
67
-    /**
68
-     * @return string
69
-     */
70
-    public function getEditorStyleHandle()
71
-    {
72
-        return $this->editor_style_handle;
73
-    }
74
-
75
-
76
-    /**
77
-     * @param string $editor_style_handle
78
-     */
79
-    public function setEditorStyleHandle($editor_style_handle)
80
-    {
81
-        if (strpos($editor_style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
82
-            $editor_style_handle = BlockInterface::NAME_SPACE . '-' . $editor_style_handle;
83
-        }
84
-        $this->editor_style_handle = $editor_style_handle;
85
-    }
86
-
87
-
88
-    /**
89
-     * @return string
90
-     */
91
-    public function getScriptHandle()
92
-    {
93
-        return $this->script_handle;
94
-    }
95
-
96
-
97
-    /**
98
-     * @param string $script_handle
99
-     */
100
-    public function setScriptHandle($script_handle)
101
-    {
102
-        if (strpos($script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
103
-            $script_handle = BlockInterface::NAME_SPACE . '-' . $script_handle;
104
-        }
105
-        $this->script_handle = $script_handle;
106
-    }
107
-
108
-
109
-    /**
110
-     * @return string
111
-     */
112
-    public function getStyleHandle()
113
-    {
114
-        return $this->style_handle;
115
-    }
116
-
117
-
118
-    /**
119
-     * @param string $style_handle
120
-     */
121
-    public function setStyleHandle($style_handle)
122
-    {
123
-        if (strpos($style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
124
-            $style_handle = BlockInterface::NAME_SPACE . '-' . $style_handle;
125
-        }
126
-        $this->style_handle = $style_handle;
127
-    }
128
-
129
-    /**
130
-     * @since $VID:$
131
-     * @throws InvalidDataTypeException
132
-     * @throws InvalidEntityException
133
-     * @throws DuplicateCollectionIdentifierException
134
-     */
135
-    public function addAssets()
136
-    {
137
-        $this->addEditorScript($this->getEditorScriptHandle());
138
-        $this->addEditorStyle($this->getEditorStyleHandle());
139
-        $this->addScript($this->getScriptHandle());
140
-        $this->addStyle($this->getStyleHandle());
141
-    }
142
-
143
-
144
-    /**
145
-     * @param       $handle
146
-     * @param array $dependencies
147
-     * @since $VID:$
148
-     * @return JavascriptAsset
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidEntityException
151
-     * @throws DuplicateCollectionIdentifierException
152
-     */
153
-    public function addEditorScript($handle, array $dependencies = array())
154
-    {
155
-        if($this->assets->hasJavascriptAsset($handle)){
156
-            return $this->assets->getJavascriptAsset($handle);
157
-        }
158
-        return parent::addJavascript(
159
-            $handle,
160
-            $this->registry->getJsUrl(
161
-                $this->domain->assetNamespace(),
162
-                $handle
163
-            ),
164
-            $this->addDefaultBlockScriptDependencies($dependencies)
165
-        )
166
-        ->setRequiresTranslation();
167
-    }
168
-
169
-
170
-    /**
171
-     * @param        $handle
172
-     * @param array  $dependencies
173
-     * @since $VID:$
174
-     * @return StylesheetAsset
175
-     * @throws InvalidDataTypeException
176
-     * @throws InvalidEntityException
177
-     * @throws DuplicateCollectionIdentifierException
178
-     */
179
-    public function addEditorStyle($handle, array $dependencies = array())
180
-    {
181
-        if ($this->assets->hasStylesheetAsset($handle)) {
182
-            return $this->assets->getStylesheetAsset($handle);
183
-        }
184
-        return parent::addStylesheet(
185
-            $handle,
186
-            $this->registry->getCssUrl(
187
-                $this->domain->assetNamespace(),
188
-                $handle
189
-            ),
190
-            $this->addDefaultBlockStyleDependencies($dependencies)
191
-        );
192
-    }
193
-
194
-
195
-    /**
196
-     * @param       $handle
197
-     * @param array $dependencies
198
-     * @since $VID:$
199
-     * @return JavascriptAsset
200
-     * @throws InvalidDataTypeException
201
-     * @throws InvalidEntityException
202
-     * @throws DuplicateCollectionIdentifierException
203
-     */
204
-    public function addScript($handle, array $dependencies = array())
205
-    {
206
-        if ($this->assets->hasJavascriptAsset($handle)) {
207
-            return $this->assets->getJavascriptAsset($handle);
208
-        }
209
-        return parent::addJavascript(
210
-            $handle,
211
-            $this->registry->getJsUrl(
212
-                $this->domain->assetNamespace(),
213
-                $handle
214
-            ),
215
-            $dependencies + array( CoreAssetManager::JS_HANDLE_COMPONENTS )
216
-        )
217
-        ->setRequiresTranslation();
218
-    }
219
-
220
-
221
-    /**
222
-     * @param        $handle
223
-     * @param array  $dependencies
224
-     * @since $VID:$
225
-     * @return StylesheetAsset
226
-     * @throws InvalidDataTypeException
227
-     * @throws InvalidEntityException
228
-     * @throws DuplicateCollectionIdentifierException
229
-     */
230
-    public function addStyle($handle, array $dependencies = array())
231
-    {
232
-        if ($this->assets->hasStylesheetAsset($handle)) {
233
-            return $this->assets->getStylesheetAsset($handle);
234
-        }
235
-        return parent::addStylesheet(
236
-            $handle,
237
-            $this->registry->getCssUrl(
238
-                $this->domain->assetNamespace(),
239
-                $handle
240
-            ),
241
-            $dependencies + array( CoreAssetManager::CSS_HANDLE_COMPONENTS )
242
-        );
243
-    }
244
-
245
-
246
-    /**
247
-     * @param array $dependencies
248
-     * @return array
249
-     */
250
-    protected function addDefaultBlockScriptDependencies(array $dependencies)
251
-    {
252
-        $dependencies += array(
253
-                'wp-blocks',    // Provides useful functions and components for extending the editor
254
-                'wp-i18n',      // Provides localization functions
255
-                'wp-element',   // Provides React.Component
256
-                'wp-components', // Provides many prebuilt components and controls
257
-                CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
258
-                $this->getScriptHandle(),
259
-            );
260
-        return $dependencies;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param array $dependencies
266
-     * @return array
267
-     */
268
-    protected function addDefaultBlockStyleDependencies(array $dependencies)
269
-    {
270
-        $dependencies += array(
271
-            $this->getStyleHandle()
272
-        );
273
-        return $dependencies;
274
-    }
275
-
276
-
277
-    /**
278
-     * @return JavascriptAsset|null
279
-     */
280
-    public function getEditorScript()
281
-    {
282
-        return $this->assets->getJavascriptAsset($this->editor_script_handle);
283
-    }
284
-
285
-
286
-    /**
287
-     * @return StylesheetAsset|null
288
-     */
289
-    public function getEditorStyle()
290
-    {
291
-        return $this->assets->getStylesheetAsset($this->editor_style_handle);
292
-    }
293
-
294
-
295
-    /**
296
-     * @return JavascriptAsset|null
297
-     */
298
-    public function getScript()
299
-    {
300
-        return $this->assets->getJavascriptAsset($this->script_handle);
301
-    }
302
-
303
-
304
-    /**
305
-     * @return StylesheetAsset|null
306
-     */
307
-    public function getStyle()
308
-    {
309
-        return $this->assets->getStylesheetAsset($this->style_handle);
310
-    }
311
-
312
-
313
-    /**
314
-     * @return  void
315
-     */
316
-    public function enqueueAssets()
317
-    {
318
-        $assets = array(
319
-            $this->getEditorScript(),
320
-            $this->getEditorStyle(),
321
-            $this->getScript(),
322
-            $this->getStyle(),
323
-        );
324
-        foreach ($assets as $asset) {
325
-            if ($asset instanceof BrowserAsset && $asset->isRegistered()) {
326
-                $asset->enqueueAsset();
327
-            }
328
-        }
329
-    }
25
+	/**
26
+	 * @var string $editor_script_handle
27
+	 */
28
+	private $editor_script_handle;
29
+
30
+	/**
31
+	 * @var string $editor_style_handle
32
+	 */
33
+	private $editor_style_handle;
34
+
35
+	/**
36
+	 * @var string $script_handle
37
+	 */
38
+	private $script_handle;
39
+
40
+	/**
41
+	 * @var string $style_handle
42
+	 */
43
+	private $style_handle;
44
+
45
+
46
+	/**
47
+	 * @return string
48
+	 */
49
+	public function getEditorScriptHandle()
50
+	{
51
+		return $this->editor_script_handle;
52
+	}
53
+
54
+
55
+	/**
56
+	 * @param string $editor_script_handle
57
+	 */
58
+	public function setEditorScriptHandle($editor_script_handle)
59
+	{
60
+		if(strpos($editor_script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
61
+			$editor_script_handle = BlockInterface::NAME_SPACE . '-' . $editor_script_handle;
62
+		}
63
+		$this->editor_script_handle = $editor_script_handle;
64
+	}
65
+
66
+
67
+	/**
68
+	 * @return string
69
+	 */
70
+	public function getEditorStyleHandle()
71
+	{
72
+		return $this->editor_style_handle;
73
+	}
74
+
75
+
76
+	/**
77
+	 * @param string $editor_style_handle
78
+	 */
79
+	public function setEditorStyleHandle($editor_style_handle)
80
+	{
81
+		if (strpos($editor_style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
82
+			$editor_style_handle = BlockInterface::NAME_SPACE . '-' . $editor_style_handle;
83
+		}
84
+		$this->editor_style_handle = $editor_style_handle;
85
+	}
86
+
87
+
88
+	/**
89
+	 * @return string
90
+	 */
91
+	public function getScriptHandle()
92
+	{
93
+		return $this->script_handle;
94
+	}
95
+
96
+
97
+	/**
98
+	 * @param string $script_handle
99
+	 */
100
+	public function setScriptHandle($script_handle)
101
+	{
102
+		if (strpos($script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
103
+			$script_handle = BlockInterface::NAME_SPACE . '-' . $script_handle;
104
+		}
105
+		$this->script_handle = $script_handle;
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return string
111
+	 */
112
+	public function getStyleHandle()
113
+	{
114
+		return $this->style_handle;
115
+	}
116
+
117
+
118
+	/**
119
+	 * @param string $style_handle
120
+	 */
121
+	public function setStyleHandle($style_handle)
122
+	{
123
+		if (strpos($style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
124
+			$style_handle = BlockInterface::NAME_SPACE . '-' . $style_handle;
125
+		}
126
+		$this->style_handle = $style_handle;
127
+	}
128
+
129
+	/**
130
+	 * @since $VID:$
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws InvalidEntityException
133
+	 * @throws DuplicateCollectionIdentifierException
134
+	 */
135
+	public function addAssets()
136
+	{
137
+		$this->addEditorScript($this->getEditorScriptHandle());
138
+		$this->addEditorStyle($this->getEditorStyleHandle());
139
+		$this->addScript($this->getScriptHandle());
140
+		$this->addStyle($this->getStyleHandle());
141
+	}
142
+
143
+
144
+	/**
145
+	 * @param       $handle
146
+	 * @param array $dependencies
147
+	 * @since $VID:$
148
+	 * @return JavascriptAsset
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidEntityException
151
+	 * @throws DuplicateCollectionIdentifierException
152
+	 */
153
+	public function addEditorScript($handle, array $dependencies = array())
154
+	{
155
+		if($this->assets->hasJavascriptAsset($handle)){
156
+			return $this->assets->getJavascriptAsset($handle);
157
+		}
158
+		return parent::addJavascript(
159
+			$handle,
160
+			$this->registry->getJsUrl(
161
+				$this->domain->assetNamespace(),
162
+				$handle
163
+			),
164
+			$this->addDefaultBlockScriptDependencies($dependencies)
165
+		)
166
+		->setRequiresTranslation();
167
+	}
168
+
169
+
170
+	/**
171
+	 * @param        $handle
172
+	 * @param array  $dependencies
173
+	 * @since $VID:$
174
+	 * @return StylesheetAsset
175
+	 * @throws InvalidDataTypeException
176
+	 * @throws InvalidEntityException
177
+	 * @throws DuplicateCollectionIdentifierException
178
+	 */
179
+	public function addEditorStyle($handle, array $dependencies = array())
180
+	{
181
+		if ($this->assets->hasStylesheetAsset($handle)) {
182
+			return $this->assets->getStylesheetAsset($handle);
183
+		}
184
+		return parent::addStylesheet(
185
+			$handle,
186
+			$this->registry->getCssUrl(
187
+				$this->domain->assetNamespace(),
188
+				$handle
189
+			),
190
+			$this->addDefaultBlockStyleDependencies($dependencies)
191
+		);
192
+	}
193
+
194
+
195
+	/**
196
+	 * @param       $handle
197
+	 * @param array $dependencies
198
+	 * @since $VID:$
199
+	 * @return JavascriptAsset
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws InvalidEntityException
202
+	 * @throws DuplicateCollectionIdentifierException
203
+	 */
204
+	public function addScript($handle, array $dependencies = array())
205
+	{
206
+		if ($this->assets->hasJavascriptAsset($handle)) {
207
+			return $this->assets->getJavascriptAsset($handle);
208
+		}
209
+		return parent::addJavascript(
210
+			$handle,
211
+			$this->registry->getJsUrl(
212
+				$this->domain->assetNamespace(),
213
+				$handle
214
+			),
215
+			$dependencies + array( CoreAssetManager::JS_HANDLE_COMPONENTS )
216
+		)
217
+		->setRequiresTranslation();
218
+	}
219
+
220
+
221
+	/**
222
+	 * @param        $handle
223
+	 * @param array  $dependencies
224
+	 * @since $VID:$
225
+	 * @return StylesheetAsset
226
+	 * @throws InvalidDataTypeException
227
+	 * @throws InvalidEntityException
228
+	 * @throws DuplicateCollectionIdentifierException
229
+	 */
230
+	public function addStyle($handle, array $dependencies = array())
231
+	{
232
+		if ($this->assets->hasStylesheetAsset($handle)) {
233
+			return $this->assets->getStylesheetAsset($handle);
234
+		}
235
+		return parent::addStylesheet(
236
+			$handle,
237
+			$this->registry->getCssUrl(
238
+				$this->domain->assetNamespace(),
239
+				$handle
240
+			),
241
+			$dependencies + array( CoreAssetManager::CSS_HANDLE_COMPONENTS )
242
+		);
243
+	}
244
+
245
+
246
+	/**
247
+	 * @param array $dependencies
248
+	 * @return array
249
+	 */
250
+	protected function addDefaultBlockScriptDependencies(array $dependencies)
251
+	{
252
+		$dependencies += array(
253
+				'wp-blocks',    // Provides useful functions and components for extending the editor
254
+				'wp-i18n',      // Provides localization functions
255
+				'wp-element',   // Provides React.Component
256
+				'wp-components', // Provides many prebuilt components and controls
257
+				CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
258
+				$this->getScriptHandle(),
259
+			);
260
+		return $dependencies;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param array $dependencies
266
+	 * @return array
267
+	 */
268
+	protected function addDefaultBlockStyleDependencies(array $dependencies)
269
+	{
270
+		$dependencies += array(
271
+			$this->getStyleHandle()
272
+		);
273
+		return $dependencies;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return JavascriptAsset|null
279
+	 */
280
+	public function getEditorScript()
281
+	{
282
+		return $this->assets->getJavascriptAsset($this->editor_script_handle);
283
+	}
284
+
285
+
286
+	/**
287
+	 * @return StylesheetAsset|null
288
+	 */
289
+	public function getEditorStyle()
290
+	{
291
+		return $this->assets->getStylesheetAsset($this->editor_style_handle);
292
+	}
293
+
294
+
295
+	/**
296
+	 * @return JavascriptAsset|null
297
+	 */
298
+	public function getScript()
299
+	{
300
+		return $this->assets->getJavascriptAsset($this->script_handle);
301
+	}
302
+
303
+
304
+	/**
305
+	 * @return StylesheetAsset|null
306
+	 */
307
+	public function getStyle()
308
+	{
309
+		return $this->assets->getStylesheetAsset($this->style_handle);
310
+	}
311
+
312
+
313
+	/**
314
+	 * @return  void
315
+	 */
316
+	public function enqueueAssets()
317
+	{
318
+		$assets = array(
319
+			$this->getEditorScript(),
320
+			$this->getEditorStyle(),
321
+			$this->getScript(),
322
+			$this->getStyle(),
323
+		);
324
+		foreach ($assets as $asset) {
325
+			if ($asset instanceof BrowserAsset && $asset->isRegistered()) {
326
+				$asset->enqueueAsset();
327
+			}
328
+		}
329
+	}
330 330
 
331 331
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -57,8 +57,8 @@  discard block
 block discarded – undo
57 57
      */
58 58
     public function setEditorScriptHandle($editor_script_handle)
59 59
     {
60
-        if(strpos($editor_script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
61
-            $editor_script_handle = BlockInterface::NAME_SPACE . '-' . $editor_script_handle;
60
+        if (strpos($editor_script_handle, BlockInterface::NAME_SPACE.'-') !== 0) {
61
+            $editor_script_handle = BlockInterface::NAME_SPACE.'-'.$editor_script_handle;
62 62
         }
63 63
         $this->editor_script_handle = $editor_script_handle;
64 64
     }
@@ -78,8 +78,8 @@  discard block
 block discarded – undo
78 78
      */
79 79
     public function setEditorStyleHandle($editor_style_handle)
80 80
     {
81
-        if (strpos($editor_style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
82
-            $editor_style_handle = BlockInterface::NAME_SPACE . '-' . $editor_style_handle;
81
+        if (strpos($editor_style_handle, BlockInterface::NAME_SPACE.'-') !== 0) {
82
+            $editor_style_handle = BlockInterface::NAME_SPACE.'-'.$editor_style_handle;
83 83
         }
84 84
         $this->editor_style_handle = $editor_style_handle;
85 85
     }
@@ -99,8 +99,8 @@  discard block
 block discarded – undo
99 99
      */
100 100
     public function setScriptHandle($script_handle)
101 101
     {
102
-        if (strpos($script_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
103
-            $script_handle = BlockInterface::NAME_SPACE . '-' . $script_handle;
102
+        if (strpos($script_handle, BlockInterface::NAME_SPACE.'-') !== 0) {
103
+            $script_handle = BlockInterface::NAME_SPACE.'-'.$script_handle;
104 104
         }
105 105
         $this->script_handle = $script_handle;
106 106
     }
@@ -120,8 +120,8 @@  discard block
 block discarded – undo
120 120
      */
121 121
     public function setStyleHandle($style_handle)
122 122
     {
123
-        if (strpos($style_handle, BlockInterface::NAME_SPACE . '-') !== 0) {
124
-            $style_handle = BlockInterface::NAME_SPACE . '-' . $style_handle;
123
+        if (strpos($style_handle, BlockInterface::NAME_SPACE.'-') !== 0) {
124
+            $style_handle = BlockInterface::NAME_SPACE.'-'.$style_handle;
125 125
         }
126 126
         $this->style_handle = $style_handle;
127 127
     }
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
      */
153 153
     public function addEditorScript($handle, array $dependencies = array())
154 154
     {
155
-        if($this->assets->hasJavascriptAsset($handle)){
155
+        if ($this->assets->hasJavascriptAsset($handle)) {
156 156
             return $this->assets->getJavascriptAsset($handle);
157 157
         }
158 158
         return parent::addJavascript(
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
                 $this->domain->assetNamespace(),
213 213
                 $handle
214 214
             ),
215
-            $dependencies + array( CoreAssetManager::JS_HANDLE_COMPONENTS )
215
+            $dependencies + array(CoreAssetManager::JS_HANDLE_COMPONENTS)
216 216
         )
217 217
         ->setRequiresTranslation();
218 218
     }
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
                 $this->domain->assetNamespace(),
239 239
                 $handle
240 240
             ),
241
-            $dependencies + array( CoreAssetManager::CSS_HANDLE_COMPONENTS )
241
+            $dependencies + array(CoreAssetManager::CSS_HANDLE_COMPONENTS)
242 242
         );
243 243
     }
244 244
 
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
     protected function addDefaultBlockScriptDependencies(array $dependencies)
251 251
     {
252 252
         $dependencies += array(
253
-                'wp-blocks',    // Provides useful functions and components for extending the editor
254
-                'wp-i18n',      // Provides localization functions
255
-                'wp-element',   // Provides React.Component
253
+                'wp-blocks', // Provides useful functions and components for extending the editor
254
+                'wp-i18n', // Provides localization functions
255
+                'wp-element', // Provides React.Component
256 256
                 'wp-components', // Provides many prebuilt components and controls
257 257
                 CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
258 258
                 $this->getScriptHandle(),
Please login to merge, or discard this patch.
core/domain/services/assets/CoreAssetManager.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -330,11 +330,11 @@  discard block
 block discarded – undo
330 330
 
331 331
         $this->addJavascript(
332 332
             CoreAssetManager::JS_HANDLE_CORE,
333
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
333
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
334 334
             array(CoreAssetManager::JS_HANDLE_JQUERY)
335 335
         )
336 336
         ->setInlineDataCallback(
337
-            function () {
337
+            function() {
338 338
                 wp_localize_script(
339 339
                     CoreAssetManager::JS_HANDLE_CORE,
340 340
                     CoreAssetManager::JS_HANDLE_I18N,
@@ -438,16 +438,16 @@  discard block
 block discarded – undo
438 438
         if ($this->template_config->enable_default_style && ! is_admin()) {
439 439
             $this->addStylesheet(
440 440
                 CoreAssetManager::CSS_HANDLE_DEFAULT,
441
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
441
+                is_readable(EVENT_ESPRESSO_UPLOAD_DIR.'css/style.css')
442 442
                     ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
443
+                    : EE_GLOBAL_ASSETS_URL.'css/espresso_default.css',
444 444
                 array('dashicons')
445 445
             );
446 446
             //Load custom style sheet if available
447 447
             if ($this->template_config->custom_style_sheet !== null) {
448 448
                 $this->addStylesheet(
449 449
                     CoreAssetManager::CSS_HANDLE_CUSTOM,
450
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
450
+                    EVENT_ESPRESSO_UPLOAD_URL.'css/'.$this->template_config->custom_style_sheet,
451 451
                     array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452 452
                 );
453 453
             }
@@ -475,14 +475,14 @@  discard block
 block discarded – undo
475 475
     {
476 476
         $this->addJavascript(
477 477
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
478
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
478
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
479 479
             array(CoreAssetManager::JS_HANDLE_JQUERY)
480 480
         )
481 481
         ->setVersion('1.15.0');
482 482
 
483 483
         $this->addJavascript(
484 484
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
485
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
485
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
486 486
             array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
487 487
         )
488 488
         ->setVersion('1.15.0');
@@ -504,18 +504,18 @@  discard block
 block discarded – undo
504 504
         // @link http://josscrowcroft.github.io/accounting.js/
505 505
         $this->addJavascript(
506 506
             CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
507
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
507
+            EE_THIRD_PARTY_URL.'accounting/accounting.js',
508 508
             array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
509 509
         )
510 510
         ->setVersion('0.3.2');
511 511
 
512 512
         $this->addJavascript(
513 513
             CoreAssetManager::JS_HANDLE_ACCOUNTING,
514
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
514
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-accounting-config.js',
515 515
             array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
516 516
         )
517 517
         ->setInlineDataCallback(
518
-            function () {
518
+            function() {
519 519
                  wp_localize_script(
520 520
                      CoreAssetManager::JS_HANDLE_ACCOUNTING,
521 521
                      'EE_ACCOUNTING_CFG',
Please login to merge, or discard this patch.
Indentation   +520 added lines, -520 removed lines patch added patch discarded remove patch
@@ -31,543 +31,543 @@
 block discarded – undo
31 31
 class CoreAssetManager extends AssetManager
32 32
 {
33 33
 
34
-    // WordPress core / Third party JS asset handles
35
-    const JS_HANDLE_JQUERY = 'jquery';
34
+	// WordPress core / Third party JS asset handles
35
+	const JS_HANDLE_JQUERY = 'jquery';
36 36
 
37
-    const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
37
+	const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
38 38
 
39
-    const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
39
+	const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
40 40
 
41
-    const JS_HANDLE_UNDERSCORE = 'underscore';
41
+	const JS_HANDLE_UNDERSCORE = 'underscore';
42 42
 
43
-    const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
43
+	const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
44 44
 
45
-    /**
46
-     * @since $VID:$
47
-     */
48
-    const JS_HANDLE_REACT = 'react';
45
+	/**
46
+	 * @since $VID:$
47
+	 */
48
+	const JS_HANDLE_REACT = 'react';
49 49
 
50
-    /**
51
-     * @since $VID:$
52
-     */
53
-    const JS_HANDLE_REACT_DOM = 'react-dom';
50
+	/**
51
+	 * @since $VID:$
52
+	 */
53
+	const JS_HANDLE_REACT_DOM = 'react-dom';
54 54
 
55
-    /**
56
-     * @since $VID:$
57
-     */
58
-    const JS_HANDLE_LODASH = 'lodash';
55
+	/**
56
+	 * @since $VID:$
57
+	 */
58
+	const JS_HANDLE_LODASH = 'lodash';
59 59
 
60
-    // EE JS assets handles
61
-    const JS_HANDLE_MANIFEST = 'ee-manifest';
60
+	// EE JS assets handles
61
+	const JS_HANDLE_MANIFEST = 'ee-manifest';
62 62
 
63
-    const JS_HANDLE_JS_CORE = 'eejs-core';
63
+	const JS_HANDLE_JS_CORE = 'eejs-core';
64 64
 
65
-    const JS_HANDLE_VENDOR = 'eventespresso-vendor';
65
+	const JS_HANDLE_VENDOR = 'eventespresso-vendor';
66 66
 
67
-    const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
67
+	const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
68 68
 
69
-    const JS_HANDLE_HELPERS = 'eventespresso-helpers';
69
+	const JS_HANDLE_HELPERS = 'eventespresso-helpers';
70 70
 
71
-    const JS_HANDLE_MODEL = 'eventespresso-model';
71
+	const JS_HANDLE_MODEL = 'eventespresso-model';
72 72
 
73
-    const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
73
+	const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
74 74
 
75
-    const JS_HANDLE_HOCS = 'eventespresso-hocs';
75
+	const JS_HANDLE_HOCS = 'eventespresso-hocs';
76 76
 
77
-    const JS_HANDLE_COMPONENTS = 'eventespresso-components';
78
-
79
-    const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
77
+	const JS_HANDLE_COMPONENTS = 'eventespresso-components';
78
+
79
+	const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
80 80
 
81
-    const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
81
+	const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
82 82
 
83
-    const JS_HANDLE_CORE = 'espresso_core';
83
+	const JS_HANDLE_CORE = 'espresso_core';
84 84
 
85
-    const JS_HANDLE_I18N = 'eei18n';
86
-
87
-    const JS_HANDLE_ACCOUNTING = 'ee-accounting';
88
-
89
-    const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
90
-
91
-    // EE CSS assets handles
92
-    const CSS_HANDLE_DEFAULT = 'espresso_default';
93
-
94
-    const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
95
-
96
-    const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
97
-
98
-    /**
99
-     * @var EE_Currency_Config $currency_config
100
-     */
101
-    protected $currency_config;
102
-
103
-    /**
104
-     * @var EE_Template_Config $template_config
105
-     */
106
-    protected $template_config;
107
-
108
-
109
-    /**
110
-     * CoreAssetRegister constructor.
111
-     *
112
-     * @param AssetCollection    $assets
113
-     * @param EE_Currency_Config $currency_config
114
-     * @param EE_Template_Config $template_config
115
-     * @param DomainInterface    $domain
116
-     * @param Registry           $registry
117
-     */
118
-    public function __construct(
119
-        AssetCollection $assets,
120
-        EE_Currency_Config $currency_config,
121
-        EE_Template_Config $template_config,
122
-        DomainInterface $domain,
123
-        Registry $registry
124
-    ) {
125
-        $this->currency_config = $currency_config;
126
-        $this->template_config = $template_config;
127
-        parent::__construct($domain, $assets, $registry);
128
-    }
129
-
130
-
131
-    /**
132
-     * @since 4.9.62.p
133
-     * @throws DomainException
134
-     * @throws DuplicateCollectionIdentifierException
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidDataTypeException
137
-     * @throws InvalidEntityException
138
-     * @throws InvalidInterfaceException
139
-     */
140
-    public function addAssets()
141
-    {
142
-        $this->addJavascriptFiles();
143
-        $this->addStylesheetFiles();
144
-    }
145
-
146
-
147
-    /**
148
-     * @since 4.9.62.p
149
-     * @throws DomainException
150
-     * @throws DuplicateCollectionIdentifierException
151
-     * @throws InvalidArgumentException
152
-     * @throws InvalidDataTypeException
153
-     * @throws InvalidEntityException
154
-     * @throws InvalidInterfaceException
155
-     */
156
-    public function addJavascriptFiles()
157
-    {
158
-        $this->loadCoreJs();
159
-        $this->loadJqueryValidate();
160
-        $this->loadAccountingJs();
161
-        add_action(
162
-            'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
-            array($this, 'loadQtipJs')
164
-        );
165
-        $this->registerAdminAssets();
166
-    }
167
-
168
-
169
-    /**
170
-     * @since 4.9.62.p
171
-     * @throws DuplicateCollectionIdentifierException
172
-     * @throws InvalidDataTypeException
173
-     * @throws InvalidEntityException
174
-     */
175
-    public function addStylesheetFiles()
176
-    {
177
-        $this->loadCoreCss();
178
-    }
179
-
180
-
181
-    /**
182
-     * core default javascript
183
-     *
184
-     * @since 4.9.62.p
185
-     * @throws DomainException
186
-     * @throws DuplicateCollectionIdentifierException
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidEntityException
190
-     * @throws InvalidInterfaceException
191
-     */
192
-    private function loadCoreJs()
193
-    {
194
-        // conditionally load third-party libraries that WP core MIGHT have.
195
-        $this->registerWpAssets();
196
-
197
-        $this->addJavascript(
198
-            CoreAssetManager::JS_HANDLE_MANIFEST,
199
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'manifest')
200
-        );
201
-
202
-        $this->addJavascript(
203
-            CoreAssetManager::JS_HANDLE_JS_CORE,
204
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'eejs'),
205
-            array(CoreAssetManager::JS_HANDLE_MANIFEST)
206
-        )
207
-        ->setHasInlineData();
208
-
209
-        $this->addJavascript(
210
-            CoreAssetManager::JS_HANDLE_VENDOR,
211
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'vendor'),
212
-            array(
213
-                CoreAssetManager::JS_HANDLE_JS_CORE,
214
-                CoreAssetManager::JS_HANDLE_REACT,
215
-                CoreAssetManager::JS_HANDLE_REACT_DOM,
216
-                CoreAssetManager::JS_HANDLE_LODASH,
217
-            )
218
-        );
219
-
220
-        $this->addJavascript(
221
-            CoreAssetManager::JS_HANDLE_VALIDATORS,
222
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'validators')
223
-        )->setRequiresTranslation();
224
-
225
-        $this->addJavascript(
226
-            CoreAssetManager::JS_HANDLE_HELPERS,
227
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'helpers'),
228
-            array(
229
-                CoreAssetManager::JS_HANDLE_VALIDATORS
230
-            )
231
-        )->setRequiresTranslation();
232
-
233
-        $this->addJavascript(
234
-            CoreAssetManager::JS_HANDLE_MODEL,
235
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'model'),
236
-            array(
237
-                CoreAssetManager::JS_HANDLE_HELPERS
238
-            )
239
-        )->setRequiresTranslation();
240
-
241
-        $this->addJavascript(
242
-            CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
243
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'valueObjects'),
244
-            array(
245
-                CoreAssetManager::JS_HANDLE_MODEL
246
-            )
247
-        )->setRequiresTranslation();
248
-
249
-        $this->addJavascript(
250
-            CoreAssetManager::JS_HANDLE_DATA_STORES,
251
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'data-stores'),
252
-            array(
253
-                CoreAssetManager::JS_HANDLE_VENDOR,
254
-                'wp-data',
255
-                'wp-api-request',
256
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS
257
-            )
258
-        )
259
-             ->setRequiresTranslation();
260
-
261
-        $this->addJavascript(
262
-            CoreAssetManager::JS_HANDLE_HOCS,
263
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'hocs'),
264
-            array(
265
-                CoreAssetManager::JS_HANDLE_DATA_STORES,
266
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
267
-                'wp-components',
268
-            )
269
-        )->setRequiresTranslation();
270
-
271
-        $this->addJavascript(
272
-            CoreAssetManager::JS_HANDLE_COMPONENTS,
273
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'components'),
274
-            array(
275
-                CoreAssetManager::JS_HANDLE_DATA_STORES,
276
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
277
-                'wp-components',
278
-            )
279
-        )
280
-        ->setRequiresTranslation();
281
-
282
-        $this->addJavascript(
283
-            CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
284
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'editor-hocs'),
285
-            array(
286
-                CoreAssetManager::JS_HANDLE_COMPONENTS
287
-            )
288
-        )->setRequiresTranslation();
289
-
290
-        $this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
291
-        $this->registry->addData(
292
-            'paths',
293
-            array(
294
-                'rest_route' => rest_url('ee/v4.8.36/'),
295
-                'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
296
-                'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
297
-                'site_url' => site_url('/'),
298
-                'admin_url' => admin_url('/'),
299
-            )
300
-        );
301
-        /** site formatting values **/
302
-        $this->registry->addData(
303
-            'site_formats',
304
-            array(
305
-                'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
306
-            )
307
-        );
308
-        /** currency data **/
309
-        $this->registry->addData(
310
-            'currency_config',
311
-            $this->getCurrencySettings()
312
-        );
313
-        /** site timezone */
314
-        $this->registry->addData(
315
-            'default_timezone',
316
-            array(
317
-                'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
318
-                'string' => get_option('timezone_string'),
319
-                'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
320
-            )
321
-        );
322
-        /** site locale (user locale if user logged in) */
323
-        $this->registry->addData(
324
-            'locale',
325
-            array(
326
-                'user' => get_user_locale(),
327
-                'site' => get_locale()
328
-            )
329
-        );
330
-
331
-        $this->addJavascript(
332
-            CoreAssetManager::JS_HANDLE_CORE,
333
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
334
-            array(CoreAssetManager::JS_HANDLE_JQUERY)
335
-        )
336
-        ->setInlineDataCallback(
337
-            function () {
338
-                wp_localize_script(
339
-                    CoreAssetManager::JS_HANDLE_CORE,
340
-                    CoreAssetManager::JS_HANDLE_I18N,
341
-                    EE_Registry::$i18n_js_strings
342
-                );
343
-            }
344
-        );
345
-    }
346
-
347
-
348
-    /**
349
-     * Registers vendor files that are bundled with a later version WP but might not be for the current version of
350
-     * WordPress in the running environment.
351
-     *
352
-     * @throws DuplicateCollectionIdentifierException
353
-     * @throws InvalidDataTypeException
354
-     * @throws InvalidEntityException
355
-     * @throws DomainException
356
-     * @since $VID:$
357
-     */
358
-    private function registerWpAssets()
359
-    {
360
-        global $wp_version;
361
-        if (version_compare($wp_version, '5.0.beta', '>=')) {
362
-            return;
363
-        }
364
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT)
365
-            ->setVersion('16.6.0');
366
-        $this->addVendorJavascript(
367
-            CoreAssetManager::JS_HANDLE_REACT_DOM,
368
-            array(CoreAssetManager::JS_HANDLE_REACT)
369
-        )->setVersion('16.6.0');
370
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH)
371
-            ->setInlineDataCallback(
372
-                function() {
373
-                    wp_add_inline_script(
374
-                        CoreAssetManager::JS_HANDLE_LODASH,
375
-                        'window.lodash = _.noConflict();'
376
-                    );
377
-                }
378
-            )
379
-            ->setVersion('4.17.11');
380
-    }
381
-
382
-
383
-    /**
384
-     * Returns configuration data for the accounting-js library.
385
-     * @since $VID:$
386
-     * @return array
387
-     */
388
-    private function getAccountingSettings() {
389
-        return array(
390
-            'currency' => array(
391
-                'symbol'    => $this->currency_config->sign,
392
-                'format'    => array(
393
-                    'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
394
-                    'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
395
-                    'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
396
-                ),
397
-                'decimal'   => $this->currency_config->dec_mrk,
398
-                'thousand'  => $this->currency_config->thsnds,
399
-                'precision' => $this->currency_config->dec_plc,
400
-            ),
401
-            'number'   => array(
402
-                'precision' => $this->currency_config->dec_plc,
403
-                'thousand'  => $this->currency_config->thsnds,
404
-                'decimal'   => $this->currency_config->dec_mrk,
405
-            ),
406
-        );
407
-    }
408
-
409
-
410
-    /**
411
-     * Returns configuration data for the js Currency VO.
412
-     * @since $VID:$
413
-     * @return array
414
-     */
415
-    private function getCurrencySettings()
416
-    {
417
-        return array(
418
-            'code' => $this->currency_config->code,
419
-            'singularLabel' => $this->currency_config->name,
420
-            'pluralLabel' => $this->currency_config->plural,
421
-            'sign' => $this->currency_config->sign,
422
-            'signB4' => $this->currency_config->sign_b4,
423
-            'decimalPlaces' => $this->currency_config->dec_plc,
424
-            'decimalMark' => $this->currency_config->dec_mrk,
425
-            'thousandsSeparator' => $this->currency_config->thsnds,
426
-        );
427
-    }
428
-
429
-
430
-    /**
431
-     * @since 4.9.62.p
432
-     * @throws DuplicateCollectionIdentifierException
433
-     * @throws InvalidDataTypeException
434
-     * @throws InvalidEntityException
435
-     */
436
-    private function loadCoreCss()
437
-    {
438
-        if ($this->template_config->enable_default_style && ! is_admin()) {
439
-            $this->addStylesheet(
440
-                CoreAssetManager::CSS_HANDLE_DEFAULT,
441
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
442
-                    ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
444
-                array('dashicons')
445
-            );
446
-            //Load custom style sheet if available
447
-            if ($this->template_config->custom_style_sheet !== null) {
448
-                $this->addStylesheet(
449
-                    CoreAssetManager::CSS_HANDLE_CUSTOM,
450
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
451
-                    array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452
-                );
453
-            }
454
-        }
455
-        $this->addStylesheet(
456
-            CoreAssetManager::CSS_HANDLE_COMPONENTS,
457
-            $this->registry->getCssUrl(
458
-                $this->domain->assetNamespace(),
459
-                'components'
460
-            )
461
-        );
462
-    }
463
-
464
-
465
-    /**
466
-     * jQuery Validate for form validation
467
-     *
468
-     * @since 4.9.62.p
469
-     * @throws DomainException
470
-     * @throws DuplicateCollectionIdentifierException
471
-     * @throws InvalidDataTypeException
472
-     * @throws InvalidEntityException
473
-     */
474
-    private function loadJqueryValidate()
475
-    {
476
-        $this->addJavascript(
477
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
478
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
479
-            array(CoreAssetManager::JS_HANDLE_JQUERY)
480
-        )
481
-        ->setVersion('1.15.0');
482
-
483
-        $this->addJavascript(
484
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
485
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
486
-            array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
487
-        )
488
-        ->setVersion('1.15.0');
489
-    }
490
-
491
-
492
-    /**
493
-     * accounting.js for performing client-side calculations
494
-     *
495
-     * @since 4.9.62.p
496
-     * @throws DomainException
497
-     * @throws DuplicateCollectionIdentifierException
498
-     * @throws InvalidDataTypeException
499
-     * @throws InvalidEntityException
500
-     */
501
-    private function loadAccountingJs()
502
-    {
503
-        //accounting.js library
504
-        // @link http://josscrowcroft.github.io/accounting.js/
505
-        $this->addJavascript(
506
-            CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
507
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
508
-            array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
509
-        )
510
-        ->setVersion('0.3.2');
511
-
512
-        $this->addJavascript(
513
-            CoreAssetManager::JS_HANDLE_ACCOUNTING,
514
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
515
-            array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
516
-        )
517
-        ->setInlineDataCallback(
518
-            function () {
519
-                 wp_localize_script(
520
-                     CoreAssetManager::JS_HANDLE_ACCOUNTING,
521
-                     'EE_ACCOUNTING_CFG',
522
-                     $this->getAccountingSettings()
523
-                 );
524
-            }
525
-        )
526
-        ->setVersion();
527
-    }
528
-
529
-
530
-    /**
531
-     * registers assets for cleaning your ears
532
-     *
533
-     * @param JavascriptAsset $script
534
-     */
535
-    public function loadQtipJs(JavascriptAsset $script)
536
-    {
537
-        // qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
538
-        // can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
539
-        if (
540
-            $script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
541
-            && apply_filters('FHEE_load_qtip', false)
542
-        ) {
543
-            EEH_Qtip_Loader::instance()->register_and_enqueue();
544
-        }
545
-    }
546
-
547
-
548
-    /**
549
-     * assets that are used in the WordPress admin
550
-     *
551
-     * @since 4.9.62.p
552
-     * @throws DuplicateCollectionIdentifierException
553
-     * @throws InvalidDataTypeException
554
-     * @throws InvalidEntityException
555
-     */
556
-    private function registerAdminAssets()
557
-    {
558
-        $this->addJavascript(
559
-            CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
560
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'wp-plugins-page'),
561
-            array(
562
-                CoreAssetManager::JS_HANDLE_JQUERY,
563
-                CoreAssetManager::JS_HANDLE_VENDOR,
564
-            )
565
-        )
566
-        ->setRequiresTranslation();
567
-
568
-        $this->addStylesheet(
569
-            CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
570
-            $this->registry->getCssUrl($this->domain->assetNamespace(), 'wp-plugins-page')
571
-        );
572
-    }
85
+	const JS_HANDLE_I18N = 'eei18n';
86
+
87
+	const JS_HANDLE_ACCOUNTING = 'ee-accounting';
88
+
89
+	const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
90
+
91
+	// EE CSS assets handles
92
+	const CSS_HANDLE_DEFAULT = 'espresso_default';
93
+
94
+	const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
95
+
96
+	const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
97
+
98
+	/**
99
+	 * @var EE_Currency_Config $currency_config
100
+	 */
101
+	protected $currency_config;
102
+
103
+	/**
104
+	 * @var EE_Template_Config $template_config
105
+	 */
106
+	protected $template_config;
107
+
108
+
109
+	/**
110
+	 * CoreAssetRegister constructor.
111
+	 *
112
+	 * @param AssetCollection    $assets
113
+	 * @param EE_Currency_Config $currency_config
114
+	 * @param EE_Template_Config $template_config
115
+	 * @param DomainInterface    $domain
116
+	 * @param Registry           $registry
117
+	 */
118
+	public function __construct(
119
+		AssetCollection $assets,
120
+		EE_Currency_Config $currency_config,
121
+		EE_Template_Config $template_config,
122
+		DomainInterface $domain,
123
+		Registry $registry
124
+	) {
125
+		$this->currency_config = $currency_config;
126
+		$this->template_config = $template_config;
127
+		parent::__construct($domain, $assets, $registry);
128
+	}
129
+
130
+
131
+	/**
132
+	 * @since 4.9.62.p
133
+	 * @throws DomainException
134
+	 * @throws DuplicateCollectionIdentifierException
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws InvalidEntityException
138
+	 * @throws InvalidInterfaceException
139
+	 */
140
+	public function addAssets()
141
+	{
142
+		$this->addJavascriptFiles();
143
+		$this->addStylesheetFiles();
144
+	}
145
+
146
+
147
+	/**
148
+	 * @since 4.9.62.p
149
+	 * @throws DomainException
150
+	 * @throws DuplicateCollectionIdentifierException
151
+	 * @throws InvalidArgumentException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws InvalidEntityException
154
+	 * @throws InvalidInterfaceException
155
+	 */
156
+	public function addJavascriptFiles()
157
+	{
158
+		$this->loadCoreJs();
159
+		$this->loadJqueryValidate();
160
+		$this->loadAccountingJs();
161
+		add_action(
162
+			'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
+			array($this, 'loadQtipJs')
164
+		);
165
+		$this->registerAdminAssets();
166
+	}
167
+
168
+
169
+	/**
170
+	 * @since 4.9.62.p
171
+	 * @throws DuplicateCollectionIdentifierException
172
+	 * @throws InvalidDataTypeException
173
+	 * @throws InvalidEntityException
174
+	 */
175
+	public function addStylesheetFiles()
176
+	{
177
+		$this->loadCoreCss();
178
+	}
179
+
180
+
181
+	/**
182
+	 * core default javascript
183
+	 *
184
+	 * @since 4.9.62.p
185
+	 * @throws DomainException
186
+	 * @throws DuplicateCollectionIdentifierException
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidEntityException
190
+	 * @throws InvalidInterfaceException
191
+	 */
192
+	private function loadCoreJs()
193
+	{
194
+		// conditionally load third-party libraries that WP core MIGHT have.
195
+		$this->registerWpAssets();
196
+
197
+		$this->addJavascript(
198
+			CoreAssetManager::JS_HANDLE_MANIFEST,
199
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'manifest')
200
+		);
201
+
202
+		$this->addJavascript(
203
+			CoreAssetManager::JS_HANDLE_JS_CORE,
204
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'eejs'),
205
+			array(CoreAssetManager::JS_HANDLE_MANIFEST)
206
+		)
207
+		->setHasInlineData();
208
+
209
+		$this->addJavascript(
210
+			CoreAssetManager::JS_HANDLE_VENDOR,
211
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'vendor'),
212
+			array(
213
+				CoreAssetManager::JS_HANDLE_JS_CORE,
214
+				CoreAssetManager::JS_HANDLE_REACT,
215
+				CoreAssetManager::JS_HANDLE_REACT_DOM,
216
+				CoreAssetManager::JS_HANDLE_LODASH,
217
+			)
218
+		);
219
+
220
+		$this->addJavascript(
221
+			CoreAssetManager::JS_HANDLE_VALIDATORS,
222
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'validators')
223
+		)->setRequiresTranslation();
224
+
225
+		$this->addJavascript(
226
+			CoreAssetManager::JS_HANDLE_HELPERS,
227
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'helpers'),
228
+			array(
229
+				CoreAssetManager::JS_HANDLE_VALIDATORS
230
+			)
231
+		)->setRequiresTranslation();
232
+
233
+		$this->addJavascript(
234
+			CoreAssetManager::JS_HANDLE_MODEL,
235
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'model'),
236
+			array(
237
+				CoreAssetManager::JS_HANDLE_HELPERS
238
+			)
239
+		)->setRequiresTranslation();
240
+
241
+		$this->addJavascript(
242
+			CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
243
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'valueObjects'),
244
+			array(
245
+				CoreAssetManager::JS_HANDLE_MODEL
246
+			)
247
+		)->setRequiresTranslation();
248
+
249
+		$this->addJavascript(
250
+			CoreAssetManager::JS_HANDLE_DATA_STORES,
251
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'data-stores'),
252
+			array(
253
+				CoreAssetManager::JS_HANDLE_VENDOR,
254
+				'wp-data',
255
+				'wp-api-request',
256
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS
257
+			)
258
+		)
259
+			 ->setRequiresTranslation();
260
+
261
+		$this->addJavascript(
262
+			CoreAssetManager::JS_HANDLE_HOCS,
263
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'hocs'),
264
+			array(
265
+				CoreAssetManager::JS_HANDLE_DATA_STORES,
266
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
267
+				'wp-components',
268
+			)
269
+		)->setRequiresTranslation();
270
+
271
+		$this->addJavascript(
272
+			CoreAssetManager::JS_HANDLE_COMPONENTS,
273
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'components'),
274
+			array(
275
+				CoreAssetManager::JS_HANDLE_DATA_STORES,
276
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
277
+				'wp-components',
278
+			)
279
+		)
280
+		->setRequiresTranslation();
281
+
282
+		$this->addJavascript(
283
+			CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
284
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'editor-hocs'),
285
+			array(
286
+				CoreAssetManager::JS_HANDLE_COMPONENTS
287
+			)
288
+		)->setRequiresTranslation();
289
+
290
+		$this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
291
+		$this->registry->addData(
292
+			'paths',
293
+			array(
294
+				'rest_route' => rest_url('ee/v4.8.36/'),
295
+				'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
296
+				'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
297
+				'site_url' => site_url('/'),
298
+				'admin_url' => admin_url('/'),
299
+			)
300
+		);
301
+		/** site formatting values **/
302
+		$this->registry->addData(
303
+			'site_formats',
304
+			array(
305
+				'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
306
+			)
307
+		);
308
+		/** currency data **/
309
+		$this->registry->addData(
310
+			'currency_config',
311
+			$this->getCurrencySettings()
312
+		);
313
+		/** site timezone */
314
+		$this->registry->addData(
315
+			'default_timezone',
316
+			array(
317
+				'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
318
+				'string' => get_option('timezone_string'),
319
+				'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
320
+			)
321
+		);
322
+		/** site locale (user locale if user logged in) */
323
+		$this->registry->addData(
324
+			'locale',
325
+			array(
326
+				'user' => get_user_locale(),
327
+				'site' => get_locale()
328
+			)
329
+		);
330
+
331
+		$this->addJavascript(
332
+			CoreAssetManager::JS_HANDLE_CORE,
333
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
334
+			array(CoreAssetManager::JS_HANDLE_JQUERY)
335
+		)
336
+		->setInlineDataCallback(
337
+			function () {
338
+				wp_localize_script(
339
+					CoreAssetManager::JS_HANDLE_CORE,
340
+					CoreAssetManager::JS_HANDLE_I18N,
341
+					EE_Registry::$i18n_js_strings
342
+				);
343
+			}
344
+		);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Registers vendor files that are bundled with a later version WP but might not be for the current version of
350
+	 * WordPress in the running environment.
351
+	 *
352
+	 * @throws DuplicateCollectionIdentifierException
353
+	 * @throws InvalidDataTypeException
354
+	 * @throws InvalidEntityException
355
+	 * @throws DomainException
356
+	 * @since $VID:$
357
+	 */
358
+	private function registerWpAssets()
359
+	{
360
+		global $wp_version;
361
+		if (version_compare($wp_version, '5.0.beta', '>=')) {
362
+			return;
363
+		}
364
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT)
365
+			->setVersion('16.6.0');
366
+		$this->addVendorJavascript(
367
+			CoreAssetManager::JS_HANDLE_REACT_DOM,
368
+			array(CoreAssetManager::JS_HANDLE_REACT)
369
+		)->setVersion('16.6.0');
370
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH)
371
+			->setInlineDataCallback(
372
+				function() {
373
+					wp_add_inline_script(
374
+						CoreAssetManager::JS_HANDLE_LODASH,
375
+						'window.lodash = _.noConflict();'
376
+					);
377
+				}
378
+			)
379
+			->setVersion('4.17.11');
380
+	}
381
+
382
+
383
+	/**
384
+	 * Returns configuration data for the accounting-js library.
385
+	 * @since $VID:$
386
+	 * @return array
387
+	 */
388
+	private function getAccountingSettings() {
389
+		return array(
390
+			'currency' => array(
391
+				'symbol'    => $this->currency_config->sign,
392
+				'format'    => array(
393
+					'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
394
+					'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
395
+					'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
396
+				),
397
+				'decimal'   => $this->currency_config->dec_mrk,
398
+				'thousand'  => $this->currency_config->thsnds,
399
+				'precision' => $this->currency_config->dec_plc,
400
+			),
401
+			'number'   => array(
402
+				'precision' => $this->currency_config->dec_plc,
403
+				'thousand'  => $this->currency_config->thsnds,
404
+				'decimal'   => $this->currency_config->dec_mrk,
405
+			),
406
+		);
407
+	}
408
+
409
+
410
+	/**
411
+	 * Returns configuration data for the js Currency VO.
412
+	 * @since $VID:$
413
+	 * @return array
414
+	 */
415
+	private function getCurrencySettings()
416
+	{
417
+		return array(
418
+			'code' => $this->currency_config->code,
419
+			'singularLabel' => $this->currency_config->name,
420
+			'pluralLabel' => $this->currency_config->plural,
421
+			'sign' => $this->currency_config->sign,
422
+			'signB4' => $this->currency_config->sign_b4,
423
+			'decimalPlaces' => $this->currency_config->dec_plc,
424
+			'decimalMark' => $this->currency_config->dec_mrk,
425
+			'thousandsSeparator' => $this->currency_config->thsnds,
426
+		);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @since 4.9.62.p
432
+	 * @throws DuplicateCollectionIdentifierException
433
+	 * @throws InvalidDataTypeException
434
+	 * @throws InvalidEntityException
435
+	 */
436
+	private function loadCoreCss()
437
+	{
438
+		if ($this->template_config->enable_default_style && ! is_admin()) {
439
+			$this->addStylesheet(
440
+				CoreAssetManager::CSS_HANDLE_DEFAULT,
441
+				is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
442
+					? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
+					: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
444
+				array('dashicons')
445
+			);
446
+			//Load custom style sheet if available
447
+			if ($this->template_config->custom_style_sheet !== null) {
448
+				$this->addStylesheet(
449
+					CoreAssetManager::CSS_HANDLE_CUSTOM,
450
+					EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
451
+					array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452
+				);
453
+			}
454
+		}
455
+		$this->addStylesheet(
456
+			CoreAssetManager::CSS_HANDLE_COMPONENTS,
457
+			$this->registry->getCssUrl(
458
+				$this->domain->assetNamespace(),
459
+				'components'
460
+			)
461
+		);
462
+	}
463
+
464
+
465
+	/**
466
+	 * jQuery Validate for form validation
467
+	 *
468
+	 * @since 4.9.62.p
469
+	 * @throws DomainException
470
+	 * @throws DuplicateCollectionIdentifierException
471
+	 * @throws InvalidDataTypeException
472
+	 * @throws InvalidEntityException
473
+	 */
474
+	private function loadJqueryValidate()
475
+	{
476
+		$this->addJavascript(
477
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
478
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
479
+			array(CoreAssetManager::JS_HANDLE_JQUERY)
480
+		)
481
+		->setVersion('1.15.0');
482
+
483
+		$this->addJavascript(
484
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
485
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
486
+			array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
487
+		)
488
+		->setVersion('1.15.0');
489
+	}
490
+
491
+
492
+	/**
493
+	 * accounting.js for performing client-side calculations
494
+	 *
495
+	 * @since 4.9.62.p
496
+	 * @throws DomainException
497
+	 * @throws DuplicateCollectionIdentifierException
498
+	 * @throws InvalidDataTypeException
499
+	 * @throws InvalidEntityException
500
+	 */
501
+	private function loadAccountingJs()
502
+	{
503
+		//accounting.js library
504
+		// @link http://josscrowcroft.github.io/accounting.js/
505
+		$this->addJavascript(
506
+			CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
507
+			EE_THIRD_PARTY_URL . 'accounting/accounting.js',
508
+			array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
509
+		)
510
+		->setVersion('0.3.2');
511
+
512
+		$this->addJavascript(
513
+			CoreAssetManager::JS_HANDLE_ACCOUNTING,
514
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
515
+			array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
516
+		)
517
+		->setInlineDataCallback(
518
+			function () {
519
+				 wp_localize_script(
520
+					 CoreAssetManager::JS_HANDLE_ACCOUNTING,
521
+					 'EE_ACCOUNTING_CFG',
522
+					 $this->getAccountingSettings()
523
+				 );
524
+			}
525
+		)
526
+		->setVersion();
527
+	}
528
+
529
+
530
+	/**
531
+	 * registers assets for cleaning your ears
532
+	 *
533
+	 * @param JavascriptAsset $script
534
+	 */
535
+	public function loadQtipJs(JavascriptAsset $script)
536
+	{
537
+		// qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
538
+		// can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
539
+		if (
540
+			$script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
541
+			&& apply_filters('FHEE_load_qtip', false)
542
+		) {
543
+			EEH_Qtip_Loader::instance()->register_and_enqueue();
544
+		}
545
+	}
546
+
547
+
548
+	/**
549
+	 * assets that are used in the WordPress admin
550
+	 *
551
+	 * @since 4.9.62.p
552
+	 * @throws DuplicateCollectionIdentifierException
553
+	 * @throws InvalidDataTypeException
554
+	 * @throws InvalidEntityException
555
+	 */
556
+	private function registerAdminAssets()
557
+	{
558
+		$this->addJavascript(
559
+			CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
560
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'wp-plugins-page'),
561
+			array(
562
+				CoreAssetManager::JS_HANDLE_JQUERY,
563
+				CoreAssetManager::JS_HANDLE_VENDOR,
564
+			)
565
+		)
566
+		->setRequiresTranslation();
567
+
568
+		$this->addStylesheet(
569
+			CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
570
+			$this->registry->getCssUrl($this->domain->assetNamespace(), 'wp-plugins-page')
571
+		);
572
+	}
573 573
 }
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4484 added lines, -4484 removed lines patch added patch discarded remove patch
@@ -19,2588 +19,2588 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
565
-                'require_nonce' => false,
566
-            ),
567
-            'custom_mtps'              => array(
568
-                'nav'           => array(
569
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
-                    'order' => 30,
571
-                ),
572
-                'help_tabs'     => array(),
573
-                'help_tour'     => array(),
574
-                'require_nonce' => false,
575
-            ),
576
-            'add_new_message_template' => array(
577
-                'nav'           => array(
578
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
-                    'order'      => 5,
580
-                    'persistent' => false,
581
-                ),
582
-                'require_nonce' => false,
583
-            ),
584
-            'edit_message_template'    => array(
585
-                'labels'        => array(
586
-                    'buttons'    => array(
587
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
-                    ),
589
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
-                ),
591
-                'nav'           => array(
592
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
-                    'order'      => 5,
594
-                    'persistent' => false,
595
-                    'url'        => '',
596
-                ),
597
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
-                'has_metaboxes' => true,
599
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
-                'help_tabs'     => array(
601
-                    'edit_message_template'            => array(
602
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
-                        'callback' => 'edit_message_template_help_tab',
604
-                    ),
605
-                    'message_templates_help_tab'       => array(
606
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
607
-                        'filename' => 'messages_templates',
608
-                    ),
609
-                    'message_template_shortcodes'      => array(
610
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
-                        'callback' => 'message_template_shortcodes_help_tab',
612
-                    ),
613
-                    'message_preview_help_tab'         => array(
614
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
615
-                        'filename' => 'messages_preview',
616
-                    ),
617
-                    'messages_overview_other_help_tab' => array(
618
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
619
-                        'filename' => 'messages_overview_other',
620
-                    ),
621
-                ),
622
-                'require_nonce' => false,
623
-            ),
624
-            'display_preview_message'  => array(
625
-                'nav'           => array(
626
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
627
-                    'order'      => 5,
628
-                    'url'        => '',
629
-                    'persistent' => false,
630
-                ),
631
-                'help_tabs'     => array(
632
-                    'preview_message' => array(
633
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
634
-                        'callback' => 'preview_message_help_tab',
635
-                    ),
636
-                ),
637
-                'require_nonce' => false,
638
-            ),
639
-            'settings'                 => array(
640
-                'nav'           => array(
641
-                    'label' => esc_html__('Settings', 'event_espresso'),
642
-                    'order' => 40,
643
-                ),
644
-                'metaboxes'     => array('_messages_settings_metaboxes'),
645
-                'help_tabs'     => array(
646
-                    'messages_settings_help_tab'               => array(
647
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
-                        'filename' => 'messages_settings',
649
-                    ),
650
-                    'messages_settings_message_types_help_tab' => array(
651
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
-                        'filename' => 'messages_settings_message_types',
653
-                    ),
654
-                    'messages_settings_messengers_help_tab'    => array(
655
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
-                        'filename' => 'messages_settings_messengers',
657
-                    ),
658
-                ),
659
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
660
-                'require_nonce' => false,
661
-            ),
662
-        );
663
-    }
664
-
665
-
666
-    protected function _add_screen_options()
667
-    {
668
-        // todo
669
-    }
670
-
671
-
672
-    protected function _add_screen_options_global_mtps()
673
-    {
674
-        /**
675
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
677
-         */
678
-        $page_title = $this->_admin_page_title;
679
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
-        $this->_per_page_screen_option();
681
-        $this->_admin_page_title = $page_title;
682
-    }
683
-
684
-
685
-    protected function _add_screen_options_default()
686
-    {
687
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
-        $this->_per_page_screen_option();
689
-    }
690
-
691
-
692
-    // none of the below group are currently used for Messages
693
-    protected function _add_feature_pointers()
694
-    {
695
-    }
696
-
697
-    public function admin_init()
698
-    {
699
-    }
700
-
701
-    public function admin_notices()
702
-    {
703
-    }
704
-
705
-    public function admin_footer_scripts()
706
-    {
707
-    }
708
-
709
-
710
-    public function messages_help_tab()
711
-    {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
-    }
714
-
715
-
716
-    public function messengers_help_tab()
717
-    {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
-    }
720
-
721
-
722
-    public function message_types_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messages_overview_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_templates_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function edit_message_template_help_tab()
741
-    {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
-                        . esc_attr__('Editor Title', 'event_espresso')
744
-                        . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
747
-                        . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
750
-                        . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
753
-                        . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
-                        . esc_attr__('Publish Metabox', 'event_espresso')
756
-                        . '" />';
757
-        EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
-            $args
760
-        );
761
-    }
762
-
763
-
764
-    public function message_template_shortcodes_help_tab()
765
-    {
766
-        $this->_set_shortcodes();
767
-        $args['shortcodes'] = $this->_shortcodes;
768
-        EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
-            $args
771
-        );
772
-    }
773
-
774
-
775
-    public function preview_message_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function settings_help_tab()
782
-    {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
-        $args['img3'] = '<div class="switch">'
788
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
-                        . ' type="checkbox" checked="checked">'
790
-                        . '<label for="ee-on-off-toggle-on"></label>'
791
-                        . '</div>';
792
-        $args['img4'] = '<div class="switch">'
793
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
-                        . ' type="checkbox">'
795
-                        . '<label for="ee-on-off-toggle-on"></label>'
796
-                        . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
-    }
799
-
800
-
801
-    public function load_scripts_styles()
802
-    {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
-        wp_enqueue_style('espresso_ee_msg');
805
-
806
-        wp_register_script(
807
-            'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
-            EVENT_ESPRESSO_VERSION,
811
-            true
812
-        );
813
-        wp_register_script(
814
-            'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
-            array('ee-dialog'),
817
-            EVENT_ESPRESSO_VERSION
818
-        );
819
-    }
820
-
821
-
822
-    public function load_scripts_styles_default()
823
-    {
824
-        wp_enqueue_script('ee-msg-list-table-js');
825
-    }
826
-
827
-
828
-    public function wp_editor_css($mce_css)
829
-    {
830
-        // if we're on the edit_message_template route
831
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
-            $message_type_name = $this->_active_message_type_name;
833
-
834
-            // we're going to REPLACE the existing mce css
835
-            // we need to get the css file location from the active messenger
836
-            $mce_css = $this->_active_messenger->get_variation(
837
-                $this->_template_pack,
838
-                $message_type_name,
839
-                true,
840
-                'wpeditor',
841
-                $this->_variation
842
-            );
843
-        }
844
-
845
-        return $mce_css;
846
-    }
847
-
848
-
849
-    public function load_scripts_styles_edit_message_template()
850
-    {
851
-
852
-        $this->_set_shortcodes();
853
-
854
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
-            esc_html__(
856
-                '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.',
857
-                'event_espresso'
858
-            ),
859
-            $this->_message_template_group->messenger_obj()->label['singular'],
860
-            $this->_message_template_group->message_type_obj()->label['singular']
861
-        );
862
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
-            '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?',
864
-            'event_espresso'
865
-        );
866
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
-            'event_espresso'
869
-        );
870
-
871
-        wp_register_script(
872
-            'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
-            array('jquery'),
875
-            EVENT_ESPRESSO_VERSION
876
-        );
877
-
878
-        wp_enqueue_script('ee_admin_js');
879
-        wp_enqueue_script('ee_msgs_edit_js');
880
-
881
-        // add in special css for tiny_mce
882
-        add_filter('mce_css', array($this, 'wp_editor_css'));
883
-    }
884
-
885
-
886
-    public function load_scripts_styles_display_preview_message()
887
-    {
888
-
889
-        $this->_set_message_template_group();
890
-
891
-        if (isset($this->_req_data['messenger'])) {
892
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
-                $this->_req_data['messenger']
894
-            );
895
-        }
896
-
897
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
-
899
-
900
-        wp_enqueue_style(
901
-            'espresso_preview_css',
902
-            $this->_active_messenger->get_variation(
903
-                $this->_template_pack,
904
-                $message_type_name,
905
-                true,
906
-                'preview',
907
-                $this->_variation
908
-            )
909
-        );
910
-    }
911
-
912
-
913
-    public function load_scripts_styles_settings()
914
-    {
915
-        wp_register_style(
916
-            'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
-            array(),
919
-            EVENT_ESPRESSO_VERSION
920
-        );
921
-        wp_enqueue_style('ee-text-links');
922
-        wp_enqueue_style('ee-message-settings');
923
-        wp_enqueue_script('ee-messages-settings');
924
-    }
925
-
926
-
927
-    /**
928
-     * set views array for List Table
929
-     */
930
-    public function _set_list_table_views_global_mtps()
931
-    {
932
-        $this->_views = array(
933
-            'in_use' => array(
934
-                'slug'  => 'in_use',
935
-                'label' => esc_html__('In Use', 'event_espresso'),
936
-                'count' => 0,
937
-            ),
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * Set views array for the Custom Template List Table
944
-     */
945
-    public function _set_list_table_views_custom_mtps()
946
-    {
947
-        $this->_set_list_table_views_global_mtps();
948
-        $this->_views['in_use']['bulk_action'] = array(
949
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
-        );
951
-    }
952
-
953
-
954
-    /**
955
-     * set views array for message queue list table
956
-     *
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidArgumentException
960
-     * @throws EE_Error
961
-     * @throws ReflectionException
962
-     */
963
-    public function _set_list_table_views_default()
964
-    {
965
-        EE_Registry::instance()->load_helper('Template');
966
-
967
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
-            'ee_send_message',
969
-            'message_list_table_bulk_actions'
970
-        )
971
-            ? array(
972
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
-            )
977
-            : array();
978
-
979
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
-            'ee_delete_messages',
981
-            'message_list_table_bulk_actions'
982
-        )
983
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
-            : array();
985
-
986
-
987
-        $this->_views = array(
988
-            'all' => array(
989
-                'slug'        => 'all',
990
-                'label'       => esc_html__('All', 'event_espresso'),
991
-                'count'       => 0,
992
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
-            ),
994
-        );
995
-
996
-
997
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
998
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
-                continue;
1000
-            }
1001
-            $status_bulk_actions = $common_bulk_actions;
1002
-            // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1004
-                switch ($status) {
1005
-                    case EEM_Message::status_idle:
1006
-                    case EEM_Message::status_resend:
1007
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
-                        break;
1009
-
1010
-                    case EEM_Message::status_failed:
1011
-                    case EEM_Message::status_debug_only:
1012
-                    case EEM_Message::status_messenger_executing:
1013
-                        $status_bulk_actions = array();
1014
-                        break;
1015
-
1016
-                    case EEM_Message::status_incomplete:
1017
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_retry:
1021
-                    case EEM_Message::status_sent:
1022
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
-                        break;
1024
-                }
1025
-            }
1026
-
1027
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1028
-            if ($status === EEM_Message::status_messenger_executing) {
1029
-                continue;
1030
-            }
1031
-
1032
-            $this->_views[ strtolower($status) ] = array(
1033
-                'slug'        => strtolower($status),
1034
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
-                'count'       => 0,
1036
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
-            );
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    protected function _ee_default_messages_overview_list_table()
1043
-    {
1044
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
-        $this->display_admin_list_table_page_with_no_sidebar();
1046
-    }
1047
-
1048
-
1049
-    protected function _message_queue_list_table()
1050
-    {
1051
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
-        $this->_template_args['per_column'] = 6;
1053
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
-        $this->_template_args['before_list_table'] = '<h3>'
1055
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1056
-                                                     . '</h3>';
1057
-        $this->display_admin_list_table_page_with_no_sidebar();
1058
-    }
1059
-
1060
-
1061
-    protected function _message_legend_items()
1062
-    {
1063
-
1064
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
-        $action_items = array();
1066
-
1067
-        foreach ($action_css_classes as $action_item => $action_details) {
1068
-            if ($action_item === 'see_notifications_for') {
1069
-                continue;
1070
-            }
1071
-            $action_items[ $action_item ] = array(
1072
-                'class' => $action_details['css_class'],
1073
-                'desc'  => $action_details['label'],
1074
-            );
1075
-        }
1076
-
1077
-        /** @type array $status_items status legend setup */
1078
-        $status_items = array(
1079
-            'sent_status'                => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
-            ),
1083
-            'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
-            ),
1087
-            'failed_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
-            ),
1091
-            'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
-            ),
1095
-            'resend_status'              => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
-            ),
1099
-            'incomplete_status'          => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
-            ),
1103
-            'retry_status'               => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
-            ),
1107
-        );
1108
-        if (EEM_Message::debug()) {
1109
-            $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
-            );
1113
-        }
1114
-
1115
-        return array_merge($action_items, $status_items);
1116
-    }
1117
-
1118
-
1119
-    protected function _custom_mtps_preview()
1120
-    {
1121
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1124
-                                                   'Preview Custom Message Templates screenshot',
1125
-                                                   'event_espresso'
1126
-                                               ) . '" />';
1127
-        $this->_template_args['preview_text'] = '<strong>'
1128
-                                                . esc_html__(
1129
-                                                    '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.',
1130
-                                                    'event_espresso'
1131
-                                                )
1132
-                                                . '</strong>';
1133
-
1134
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * get_message_templates
1140
-     * This gets all the message templates for listing on the overview list.
1141
-     *
1142
-     * @access public
1143
-     * @param int    $perpage the amount of templates groups to show per page
1144
-     * @param string $type    the current _view we're getting templates for
1145
-     * @param bool   $count   return count?
1146
-     * @param bool   $all     disregard any paging info (get all data);
1147
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
-     * @return array
1149
-     * @throws EE_Error
1150
-     * @throws InvalidArgumentException
1151
-     * @throws InvalidDataTypeException
1152
-     * @throws InvalidInterfaceException
1153
-     */
1154
-    public function get_message_templates(
1155
-        $perpage = 10,
1156
-        $type = 'in_use',
1157
-        $count = false,
1158
-        $all = false,
1159
-        $global = true
1160
-    ) {
1161
-
1162
-        $MTP = EEM_Message_Template_Group::instance();
1163
-
1164
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
-        $orderby = $this->_req_data['orderby'];
1166
-
1167
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
-            ? $this->_req_data['order']
1169
-            : 'ASC';
1170
-
1171
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
-            ? $this->_req_data['paged']
1173
-            : 1;
1174
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
-            ? $this->_req_data['perpage']
1176
-            : $perpage;
1177
-
1178
-        $offset = ($current_page - 1) * $per_page;
1179
-        $limit = $all ? null : array($offset, $per_page);
1180
-
1181
-
1182
-        // options will match what is in the _views array property
1183
-        switch ($type) {
1184
-            case 'in_use':
1185
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
-                break;
1187
-            default:
1188
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
-        }
1190
-
1191
-        return $templates;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * filters etc might need a list of installed message_types
1197
-     *
1198
-     * @return array an array of message type objects
1199
-     */
1200
-    public function get_installed_message_types()
1201
-    {
1202
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
-        $installed = array();
1204
-
1205
-        foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1207
-        }
1208
-
1209
-        return $installed;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * _add_message_template
1215
-     *
1216
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1217
-     *
1218
-     * @param string $message_type
1219
-     * @param string $messenger
1220
-     * @param string $GRP_ID
1221
-     *
1222
-     * @throws EE_error
1223
-     */
1224
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
-    {
1226
-        // set values override any request data
1227
-        $message_type = ! empty($message_type) ? $message_type : '';
1228
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
-            ? $this->_req_data['message_type']
1230
-            : $message_type;
1231
-
1232
-        $messenger = ! empty($messenger) ? $messenger : '';
1233
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
-            ? $this->_req_data['messenger']
1235
-            : $messenger;
1236
-
1237
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
-
1240
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
-        if (empty($message_type) || empty($messenger)) {
1242
-            throw new EE_Error(
1243
-                esc_html__(
1244
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
-                    'event_espresso'
1246
-                )
1247
-            );
1248
-        }
1249
-
1250
-        // we need the GRP_ID for the template being used as the base for the new template
1251
-        if (empty($GRP_ID)) {
1252
-            throw new EE_Error(
1253
-                esc_html__(
1254
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
-                    'event_espresso'
1256
-                )
1257
-            );
1258
-        }
1259
-
1260
-        // let's just make sure the template gets generated!
1261
-
1262
-        // we need to reassign some variables for what the insert is expecting
1263
-        $this->_req_data['MTP_messenger'] = $messenger;
1264
-        $this->_req_data['MTP_message_type'] = $message_type;
1265
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1266
-        $this->_insert_or_update_message_template(true);
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * public wrapper for the _add_message_template method
1272
-     *
1273
-     * @param string $message_type     message type slug
1274
-     * @param string $messenger        messenger slug
1275
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
-     *                                 off of.
1277
-     * @throws EE_error
1278
-     */
1279
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1280
-    {
1281
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * _edit_message_template
1287
-     *
1288
-     * @access protected
1289
-     * @return void
1290
-     * @throws InvalidIdentifierException
1291
-     * @throws DomainException
1292
-     * @throws EE_Error
1293
-     * @throws InvalidArgumentException
1294
-     * @throws ReflectionException
1295
-     * @throws InvalidDataTypeException
1296
-     * @throws InvalidInterfaceException
1297
-     */
1298
-    protected function _edit_message_template()
1299
-    {
1300
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
-        $template_fields = '';
1302
-        $sidebar_fields = '';
1303
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
-        // valid html in the templates.
1305
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
-
1307
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
-            ? absint($this->_req_data['id'])
1309
-            : false;
1310
-
1311
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1312
-        $message_template_group = $this->_message_template_group;
1313
-        $c_label = $message_template_group->context_label();
1314
-        $c_config = $message_template_group->contexts_config();
1315
-
1316
-        reset($c_config);
1317
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
-            ? strtolower($this->_req_data['context'])
1319
-            : key($c_config);
1320
-
1321
-
1322
-        if (empty($GRP_ID)) {
1323
-            $action = 'insert_message_template';
1324
-            $edit_message_template_form_url = add_query_arg(
1325
-                array('action' => $action, 'noheader' => true),
1326
-                EE_MSG_ADMIN_URL
1327
-            );
1328
-        } else {
1329
-            $action = 'update_message_template';
1330
-            $edit_message_template_form_url = add_query_arg(
1331
-                array('action' => $action, 'noheader' => true),
1332
-                EE_MSG_ADMIN_URL
1333
-            );
1334
-        }
1335
-
1336
-        // set active messenger for this view
1337
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
-            $message_template_group->messenger()
1339
-        );
1340
-        $this->_active_message_type_name = $message_template_group->message_type();
1341
-
1342
-
1343
-        // Do we have any validation errors?
1344
-        $validators = $this->_get_transient();
1345
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
-
1347
-
1348
-        // we need to assemble the title from Various details
1349
-        $context_label = sprintf(
1350
-            esc_html__('(%s %s)', 'event_espresso'),
1351
-            $c_config[ $context ]['label'],
1352
-            ucwords($c_label['label'])
1353
-        );
1354
-
1355
-        $title = sprintf(
1356
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1357
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1358
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1359
-            $context_label
1360
-        );
1361
-
1362
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1363
-        $this->_template_args['message_template'] = $message_template_group;
1364
-        $this->_template_args['is_extra_fields'] = false;
1365
-
1366
-
1367
-        // let's get EEH_MSG_Template so we can get template form fields
1368
-        $template_field_structure = EEH_MSG_Template::get_fields(
1369
-            $message_template_group->messenger(),
1370
-            $message_template_group->message_type()
1371
-        );
1372
-
1373
-        if (! $template_field_structure) {
1374
-            $template_field_structure = false;
1375
-            $template_fields = esc_html__(
1376
-                'There was an error in assembling the fields for this display (you should see an error message)',
1377
-                'event_espresso'
1378
-            );
1379
-        }
1380
-
1381
-
1382
-        $message_templates = $message_template_group->context_templates();
1383
-
1384
-
1385
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
-        // will get handled in the "extra" array.
1387
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
-                unset($template_field_structure[ $context ][ $reference_field ]);
1390
-            }
1391
-        }
1392
-
1393
-        // let's loop through the template_field_structure and actually assemble the input fields!
1394
-        if (! empty($template_field_structure)) {
1395
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
-                // the extra array and reset them.
1398
-                if ($template_field === 'extra') {
1399
-                    $this->_template_args['is_extra_fields'] = true;
1400
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1402
-                        $content = $message_template instanceof EE_Message_Template
1403
-                            ? $message_template->get('MTP_content')
1404
-                            : '';
1405
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1406
-                            // let's verify if we need this extra field via the shortcodes parameter.
1407
-                            $continue = false;
1408
-                            if (isset($extra_array['shortcodes_required'])) {
1409
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
-                                        $continue = true;
1412
-                                    }
1413
-                                }
1414
-                                if ($continue) {
1415
-                                    continue;
1416
-                                }
1417
-                            }
1418
-
1419
-                            $field_id = $reference_field
1420
-                                        . '-'
1421
-                                        . $extra_field
1422
-                                        . '-content';
1423
-                            $template_form_fields[ $field_id ] = $extra_array;
1424
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
-                                                                         . $reference_field
1426
-                                                                         . '][content]['
1427
-                                                                         . $extra_field . ']';
1428
-                            $css_class = isset($extra_array['css_class'])
1429
-                                ? $extra_array['css_class']
1430
-                                : '';
1431
-
1432
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
-                                                                              && in_array($extra_field, $v_fields, true)
1434
-                                                                              &&
1435
-                                                                              (
1436
-                                                                                  is_array($validators[ $extra_field ])
1437
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1438
-                                                                              )
1439
-                                ? 'validate-error ' . $css_class
1440
-                                : $css_class;
1441
-
1442
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
-                                                                          && isset($content[ $extra_field ])
1444
-                                ? $content[ $extra_field ]
1445
-                                : '';
1446
-
1447
-                            // do we have a validation error?  if we do then let's use that value instead
1448
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
-                                ? $validators[ $extra_field ]['value']
1450
-                                : $template_form_fields[ $field_id ]['value'];
1451
-
1452
-
1453
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
-
1455
-                            // shortcode selector
1456
-                            $field_name_to_use = $extra_field === 'main'
1457
-                                ? 'content'
1458
-                                : $extra_field;
1459
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
-                                $field_name_to_use,
1461
-                                $field_id
1462
-                            );
1463
-
1464
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
-                                // we want to decode the entities
1466
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
-                            }/**/
1468
-                        }
1469
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
-                        $templatefield_templatename_id = $reference_field . '-name';
1471
-
1472
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1473
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
-                            'label'      => null,
1475
-                            'input'      => 'hidden',
1476
-                            'type'       => 'int',
1477
-                            'required'   => false,
1478
-                            'validation' => false,
1479
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
-                            'css_class'  => '',
1481
-                            'format'     => '%d',
1482
-                            'db-col'     => 'MTP_ID',
1483
-                        );
1484
-
1485
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1486
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
-                            'label'      => null,
1488
-                            'input'      => 'hidden',
1489
-                            'type'       => 'string',
1490
-                            'required'   => false,
1491
-                            'validation' => true,
1492
-                            'value'      => $reference_field,
1493
-                            'css_class'  => '',
1494
-                            'format'     => '%s',
1495
-                            'db-col'     => 'MTP_template_field',
1496
-                        );
1497
-                    }
1498
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
-                } else {
1500
-                    $field_id = $template_field . '-content';
1501
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1502
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1504
-                        ? $message_templates[ $context ][ $template_field ]
1505
-                        : null;
1506
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
-                                                                  && is_array($message_templates[ $context ])
1508
-                                                                  && $message_template instanceof EE_Message_Template
1509
-                        ? $message_template->get('MTP_content')
1510
-                        : '';
1511
-
1512
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1513
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
-                        ? $validators[ $template_field ]['value']
1515
-                        : $template_form_fields[ $field_id ]['value'];
1516
-
1517
-
1518
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
-                    $css_class = isset($field_setup_array['css_class'])
1520
-                        ? $field_setup_array['css_class']
1521
-                        : '';
1522
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
-                                                                      && in_array($template_field, $v_fields, true)
1524
-                                                                      && isset($validators[ $template_field ]['msg'])
1525
-                        ? 'validate-error ' . $css_class
1526
-                        : $css_class;
1527
-
1528
-                    // shortcode selector
1529
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
-                        $template_field,
1531
-                        $field_id
1532
-                    );
1533
-                }
1534
-
1535
-                // k took care of content field(s) now let's take care of others.
1536
-
1537
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1538
-                $templatefield_field_templatename_id = $template_field . '-name';
1539
-
1540
-                // foreach template field there are actually two form fields created
1541
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1542
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
-                    'label'      => null,
1544
-                    'input'      => 'hidden',
1545
-                    'type'       => 'int',
1546
-                    'required'   => false,
1547
-                    'validation' => true,
1548
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
-                    'css_class'  => '',
1550
-                    'format'     => '%d',
1551
-                    'db-col'     => 'MTP_ID',
1552
-                );
1553
-
1554
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
-                    'label'      => null,
1557
-                    'input'      => 'hidden',
1558
-                    'type'       => 'string',
1559
-                    'required'   => false,
1560
-                    'validation' => true,
1561
-                    'value'      => $template_field,
1562
-                    'css_class'  => '',
1563
-                    'format'     => '%s',
1564
-                    'db-col'     => 'MTP_template_field',
1565
-                );
1566
-            }
1567
-
1568
-            // add other fields
1569
-            $template_form_fields['ee-msg-current-context'] = array(
1570
-                'name'       => 'MTP_context',
1571
-                'label'      => null,
1572
-                'input'      => 'hidden',
1573
-                'type'       => 'string',
1574
-                'required'   => false,
1575
-                'validation' => true,
1576
-                'value'      => $context,
1577
-                'css_class'  => '',
1578
-                'format'     => '%s',
1579
-                'db-col'     => 'MTP_context',
1580
-            );
1581
-
1582
-            $template_form_fields['ee-msg-grp-id'] = array(
1583
-                'name'       => 'GRP_ID',
1584
-                'label'      => null,
1585
-                'input'      => 'hidden',
1586
-                'type'       => 'int',
1587
-                'required'   => false,
1588
-                'validation' => true,
1589
-                'value'      => $GRP_ID,
1590
-                'css_class'  => '',
1591
-                'format'     => '%d',
1592
-                'db-col'     => 'GRP_ID',
1593
-            );
1594
-
1595
-            $template_form_fields['ee-msg-messenger'] = array(
1596
-                'name'       => 'MTP_messenger',
1597
-                'label'      => null,
1598
-                'input'      => 'hidden',
1599
-                'type'       => 'string',
1600
-                'required'   => false,
1601
-                'validation' => true,
1602
-                'value'      => $message_template_group->messenger(),
1603
-                'css_class'  => '',
1604
-                'format'     => '%s',
1605
-                'db-col'     => 'MTP_messenger',
1606
-            );
1607
-
1608
-            $template_form_fields['ee-msg-message-type'] = array(
1609
-                'name'       => 'MTP_message_type',
1610
-                'label'      => null,
1611
-                'input'      => 'hidden',
1612
-                'type'       => 'string',
1613
-                'required'   => false,
1614
-                'validation' => true,
1615
-                'value'      => $message_template_group->message_type(),
1616
-                'css_class'  => '',
1617
-                'format'     => '%s',
1618
-                'db-col'     => 'MTP_message_type',
1619
-            );
1620
-
1621
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1622
-                'name'       => 'MTP_is_global',
1623
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1624
-                'input'      => 'hidden',
1625
-                'type'       => 'int',
1626
-                'required'   => false,
1627
-                'validation' => true,
1628
-                'value'      => $message_template_group->get('MTP_is_global'),
1629
-                'css_class'  => '',
1630
-                'format'     => '%d',
1631
-                'db-col'     => 'MTP_is_global',
1632
-            );
1633
-
1634
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1635
-                'name'       => 'MTP_is_override',
1636
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
-                'type'       => 'int',
1639
-                'required'   => false,
1640
-                'validation' => true,
1641
-                'value'      => $message_template_group->get('MTP_is_override'),
1642
-                'css_class'  => '',
1643
-                'format'     => '%d',
1644
-                'db-col'     => 'MTP_is_override',
1645
-            );
1646
-
1647
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1648
-                'name'       => 'MTP_is_active',
1649
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1650
-                'input'      => 'hidden',
1651
-                'type'       => 'int',
1652
-                'required'   => false,
1653
-                'validation' => true,
1654
-                'value'      => $message_template_group->is_active(),
1655
-                'css_class'  => '',
1656
-                'format'     => '%d',
1657
-                'db-col'     => 'MTP_is_active',
1658
-            );
1659
-
1660
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1661
-                'name'       => 'MTP_deleted',
1662
-                'label'      => null,
1663
-                'input'      => 'hidden',
1664
-                'type'       => 'int',
1665
-                'required'   => false,
1666
-                'validation' => true,
1667
-                'value'      => $message_template_group->get('MTP_deleted'),
1668
-                'css_class'  => '',
1669
-                'format'     => '%d',
1670
-                'db-col'     => 'MTP_deleted',
1671
-            );
1672
-            $sidebar_form_fields['ee-msg-author'] = array(
1673
-                'name'       => 'MTP_user_id',
1674
-                'label'      => esc_html__('Author', 'event_espresso'),
1675
-                'input'      => 'hidden',
1676
-                'type'       => 'int',
1677
-                'required'   => false,
1678
-                'validation' => false,
1679
-                'value'      => $message_template_group->user(),
1680
-                'format'     => '%d',
1681
-                'db-col'     => 'MTP_user_id',
1682
-            );
1683
-
1684
-            $sidebar_form_fields['ee-msg-route'] = array(
1685
-                'name'  => 'action',
1686
-                'input' => 'hidden',
1687
-                'type'  => 'string',
1688
-                'value' => $action,
1689
-            );
1690
-
1691
-            $sidebar_form_fields['ee-msg-id'] = array(
1692
-                'name'  => 'id',
1693
-                'input' => 'hidden',
1694
-                'type'  => 'int',
1695
-                'value' => $GRP_ID,
1696
-            );
1697
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
-                'name'  => $action . '_nonce',
1699
-                'input' => 'hidden',
1700
-                'type'  => 'string',
1701
-                'value' => wp_create_nonce($action . '_nonce'),
1702
-            );
1703
-
1704
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1706
-                    'name'  => 'template_switch',
1707
-                    'input' => 'hidden',
1708
-                    'type'  => 'int',
1709
-                    'value' => 1,
1710
-                );
1711
-            }
1712
-
1713
-
1714
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
-        } //end if ( !empty($template_field_structure) )
1717
-
1718
-        // set extra content for publish box
1719
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
-        $this->_set_publish_post_box_vars(
1721
-            'id',
1722
-            $GRP_ID,
1723
-            false,
1724
-            add_query_arg(
1725
-                array('action' => 'global_mtps'),
1726
-                $this->_admin_base_url
1727
-            )
1728
-        );
1729
-
1730
-        // add preview button
1731
-        $preview_url = parent::add_query_args_and_nonce(
1732
-            array(
1733
-                'message_type' => $message_template_group->message_type(),
1734
-                'messenger'    => $message_template_group->messenger(),
1735
-                'context'      => $context,
1736
-                'GRP_ID'       => $GRP_ID,
1737
-                'action'       => 'preview_message',
1738
-            ),
1739
-            $this->_admin_base_url
1740
-        );
1741
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
-                          . esc_html__('Preview', 'event_espresso')
1743
-                          . '</a>';
1744
-
1745
-
1746
-        // setup context switcher
1747
-        $context_switcher_args = array(
1748
-            'page'    => 'espresso_messages',
1749
-            'action'  => 'edit_message_template',
1750
-            'id'      => $GRP_ID,
1751
-            'context' => $context,
1752
-            'extra'   => $preview_button,
1753
-        );
1754
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
-
1756
-
1757
-        // main box
1758
-        $this->_template_args['template_fields'] = $template_fields;
1759
-        $this->_template_args['sidebar_box_id'] = 'details';
1760
-        $this->_template_args['action'] = $action;
1761
-        $this->_template_args['context'] = $context;
1762
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
-        $this->_template_args['learn_more_about_message_templates_link'] =
1764
-            $this->_learn_more_about_message_templates_link();
1765
-
1766
-
1767
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
-            $message_template_group,
1770
-            $context,
1771
-            $context_label
1772
-        );
1773
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
-
1776
-        $this->_template_path = $this->_template_args['GRP_ID']
1777
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
-
1780
-        // send along EE_Message_Template_Group object for further template use.
1781
-        $this->_template_args['MTP'] = $message_template_group;
1782
-
1783
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
-            $this->_template_path,
1785
-            $this->_template_args,
1786
-            true
1787
-        );
1788
-
1789
-
1790
-        // finally, let's set the admin_page title
1791
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
-
1793
-
1794
-        // we need to take care of setting the shortcodes property for use elsewhere.
1795
-        $this->_set_shortcodes();
1796
-
1797
-
1798
-        // final template wrapper
1799
-        $this->display_admin_page_with_sidebar();
1800
-    }
1801
-
1802
-
1803
-    public function filter_tinymce_init($mceInit, $editor_id)
1804
-    {
1805
-        return $mceInit;
1806
-    }
1807
-
1808
-
1809
-    public function add_context_switcher()
1810
-    {
1811
-        return $this->_context_switcher;
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Adds the activation/deactivation toggle for the message template context.
1817
-     *
1818
-     * @param EE_Message_Template_Group $message_template_group
1819
-     * @param string                    $context
1820
-     * @param string                    $context_label
1821
-     * @return string
1822
-     * @throws DomainException
1823
-     * @throws EE_Error
1824
-     * @throws InvalidIdentifierException
1825
-     */
1826
-    protected function add_active_context_element(
1827
-        EE_Message_Template_Group $message_template_group,
1828
-        $context,
1829
-        $context_label
1830
-    ) {
1831
-        $template_args = array(
1832
-            'context'                   => $context,
1833
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
-            'is_active'                 => $message_template_group->is_context_active($context),
1835
-            'on_off_action'             => $message_template_group->is_context_active($context)
1836
-                ? 'context-off'
1837
-                : 'context-on',
1838
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
-            'message_template_group_id' => $message_template_group->ID(),
1840
-        );
1841
-        return EEH_Template::display_template(
1842
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
-            $template_args,
1844
-            true
1845
-        );
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * Ajax callback for `toggle_context_template` ajax action.
1851
-     * Handles toggling the message context on or off.
1852
-     *
1853
-     * @throws EE_Error
1854
-     * @throws InvalidArgumentException
1855
-     * @throws InvalidDataTypeException
1856
-     * @throws InvalidIdentifierException
1857
-     * @throws InvalidInterfaceException
1858
-     */
1859
-    public function toggle_context_template()
1860
-    {
1861
-        $success = true;
1862
-        // check for required data
1863
-        if (! isset(
1864
-            $this->_req_data['message_template_group_id'],
1865
-            $this->_req_data['context'],
1866
-            $this->_req_data['status']
1867
-        )) {
1868
-            EE_Error::add_error(
1869
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
-                __FILE__,
1871
-                __FUNCTION__,
1872
-                __LINE__
1873
-            );
1874
-            $success = false;
1875
-        }
1876
-
1877
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1878
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
-            : '';
1880
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
-        $this->_verify_nonce($nonce, $nonce_ref);
1882
-        $status = $this->_req_data['status'];
1883
-        if ($status !== 'off' && $status !== 'on') {
1884
-            EE_Error::add_error(
1885
-                sprintf(
1886
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
-                    $this->_req_data['status']
1888
-                ),
1889
-                __FILE__,
1890
-                __FUNCTION__,
1891
-                __LINE__
1892
-            );
1893
-            $success = false;
1894
-        }
1895
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
-            $this->_req_data['message_template_group_id']
1897
-        );
1898
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
-            EE_Error::add_error(
1900
-                sprintf(
1901
-                    esc_html__(
1902
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
-                        'event_espresso'
1904
-                    ),
1905
-                    $this->_req_data['message_template_group_id'],
1906
-                    'EE_Message_Template_Group'
1907
-                ),
1908
-                __FILE__,
1909
-                __FUNCTION__,
1910
-                __LINE__
1911
-            );
1912
-            $success = false;
1913
-        }
1914
-        if ($success) {
1915
-            $success = $status === 'off'
1916
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1917
-                : $message_template_group->activate_context($this->_req_data['context']);
1918
-        }
1919
-        $this->_template_args['success'] = $success;
1920
-        $this->_return_json();
1921
-    }
1922
-
1923
-
1924
-    public function _add_form_element_before()
1925
-    {
1926
-        return '<form method="post" action="'
1927
-               . $this->_template_args["edit_message_template_form_url"]
1928
-               . '" id="ee-msg-edit-frm">';
1929
-    }
1930
-
1931
-    public function _add_form_element_after()
1932
-    {
1933
-        return '</form>';
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * This executes switching the template pack for a message template.
1939
-     *
1940
-     * @since 4.5.0
1941
-     * @throws EE_Error
1942
-     * @throws InvalidDataTypeException
1943
-     * @throws InvalidInterfaceException
1944
-     * @throws InvalidArgumentException
1945
-     * @throws ReflectionException
1946
-     */
1947
-    public function switch_template_pack()
1948
-    {
1949
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
-
1952
-        // verify we have needed values.
1953
-        if (empty($GRP_ID) || empty($template_pack)) {
1954
-            $this->_template_args['error'] = true;
1955
-            EE_Error::add_error(
1956
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
-                __FILE__,
1958
-                __FUNCTION__,
1959
-                __LINE__
1960
-            );
1961
-        } else {
1962
-            // get template, set the new template_pack and then reset to default
1963
-            /** @type EE_Message_Template_Group $message_template_group */
1964
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
-
1966
-            $message_template_group->set_template_pack_name($template_pack);
1967
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1968
-            $this->_req_data['mt'] = $message_template_group->message_type();
1969
-
1970
-            $query_args = $this->_reset_to_default_template();
1971
-
1972
-            if (empty($query_args['id'])) {
1973
-                EE_Error::add_error(
1974
-                    esc_html__(
1975
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
-                        'event_espresso'
1977
-                    ),
1978
-                    __FILE__,
1979
-                    __FUNCTION__,
1980
-                    __LINE__
1981
-                );
1982
-                $this->_template_args['error'] = true;
1983
-            } else {
1984
-                $template_label = $message_template_group->get_template_pack()->label;
1985
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
-                EE_Error::add_success(
1987
-                    sprintf(
1988
-                        esc_html__(
1989
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
-                            'event_espresso'
1991
-                        ),
1992
-                        $template_label,
1993
-                        $template_pack_labels->template_pack
1994
-                    )
1995
-                );
1996
-                // generate the redirect url for js.
1997
-                $url = self::add_query_args_and_nonce(
1998
-                    $query_args,
1999
-                    $this->_admin_base_url
2000
-                );
2001
-                $this->_template_args['data']['redirect_url'] = $url;
2002
-                $this->_template_args['success'] = true;
2003
-            }
2004
-
2005
-            $this->_return_json();
2006
-        }
2007
-    }
2008
-
2009
-
2010
-    /**
2011
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
-     * they want.
2013
-     *
2014
-     * @access protected
2015
-     * @return array|null
2016
-     * @throws EE_Error
2017
-     * @throws InvalidArgumentException
2018
-     * @throws InvalidDataTypeException
2019
-     * @throws InvalidInterfaceException
2020
-     */
2021
-    protected function _reset_to_default_template()
2022
-    {
2023
-
2024
-        $templates = array();
2025
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
-        // we need to make sure we've got the info we need.
2027
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
-            EE_Error::add_error(
2029
-                esc_html__(
2030
-                    '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.',
2031
-                    'event_espresso'
2032
-                ),
2033
-                __FILE__,
2034
-                __FUNCTION__,
2035
-                __LINE__
2036
-            );
2037
-        }
2038
-
2039
-        // all templates will be reset to whatever the defaults are
2040
-        // for the global template matching the messenger and message type.
2041
-        $success = ! empty($GRP_ID) ? true : false;
2042
-
2043
-        if ($success) {
2044
-            // let's first determine if the incoming template is a global template,
2045
-            // if it isn't then we need to get the global template matching messenger and message type.
2046
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
-
2048
-
2049
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
-
2052
-            if ($success) {
2053
-                // if successfully deleted, lets generate the new ones.
2054
-                // Note. We set GLOBAL to true, because resets on ANY template
2055
-                // will use the related global template defaults for regeneration.
2056
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2057
-                // HOWEVER, we DO keep the template pack and template variation set
2058
-                // for the current custom template when resetting.
2059
-                $templates = $this->_generate_new_templates(
2060
-                    $this->_req_data['msgr'],
2061
-                    $this->_req_data['mt'],
2062
-                    $GRP_ID,
2063
-                    true
2064
-                );
2065
-            }
2066
-        }
2067
-
2068
-        // any error messages?
2069
-        if (! $success) {
2070
-            EE_Error::add_error(
2071
-                esc_html__(
2072
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2073
-                    'event_espresso'
2074
-                ),
2075
-                __FILE__,
2076
-                __FUNCTION__,
2077
-                __LINE__
2078
-            );
2079
-        }
2080
-
2081
-        // all good, let's add a success message!
2082
-        if ($success && ! empty($templates)) {
2083
-            // the info for the template we generated is the first element in the returned array
2084
-            // $templates = $templates[0];
2085
-            EE_Error::overwrite_success();
2086
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
-        }
2088
-
2089
-
2090
-        $query_args = array(
2091
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
-        );
2095
-
2096
-        // if called via ajax then we return query args otherwise redirect
2097
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2098
-            return $query_args;
2099
-        } else {
2100
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2101
-
2102
-            return null;
2103
-        }
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Retrieve and set the message preview for display.
2109
-     *
2110
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
-     * @return string
2112
-     * @throws ReflectionException
2113
-     * @throws EE_Error
2114
-     * @throws InvalidArgumentException
2115
-     * @throws InvalidDataTypeException
2116
-     * @throws InvalidInterfaceException
2117
-     */
2118
-    public function _preview_message($send = false)
2119
-    {
2120
-        // first make sure we've got the necessary parameters
2121
-        if (! isset(
2122
-            $this->_req_data['message_type'],
2123
-            $this->_req_data['messenger'],
2124
-            $this->_req_data['messenger'],
2125
-            $this->_req_data['GRP_ID']
2126
-        )) {
2127
-            EE_Error::add_error(
2128
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-
2135
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
-
2137
-
2138
-        // get the preview!
2139
-        $preview = EED_Messages::preview_message(
2140
-            $this->_req_data['message_type'],
2141
-            $this->_req_data['context'],
2142
-            $this->_req_data['messenger'],
2143
-            $send
2144
-        );
2145
-
2146
-        if ($send) {
2147
-            return $preview;
2148
-        }
2149
-
2150
-        // let's add a button to go back to the edit view
2151
-        $query_args = array(
2152
-            'id'      => $this->_req_data['GRP_ID'],
2153
-            'context' => $this->_req_data['context'],
2154
-            'action'  => 'edit_message_template',
2155
-        );
2156
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
-        $preview_button = '<a href="'
2158
-                          . $go_back_url
2159
-                          . '" class="button-secondary messages-preview-go-back-button">'
2160
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2161
-                          . '</a>';
2162
-        $message_types = $this->get_installed_message_types();
2163
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
-            $this->_req_data['messenger']
2165
-        );
2166
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2167
-            ? ucwords($active_messenger->label['singular'])
2168
-            : esc_html__('Unknown Messenger', 'event_espresso');
2169
-        // let's provide a helpful title for context
2170
-        $preview_title = sprintf(
2171
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
-            $active_messenger_label,
2173
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
-        );
2175
-        // setup display of preview.
2176
-        $this->_admin_page_title = $preview_title;
2177
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2178
-        $this->_template_args['data']['force_json'] = true;
2179
-
2180
-        return '';
2181
-    }
2182
-
2183
-
2184
-    /**
2185
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2186
-     * gets called automatically.
2187
-     *
2188
-     * @since 4.5.0
2189
-     *
2190
-     * @return string
2191
-     */
2192
-    protected function _display_preview_message()
2193
-    {
2194
-        $this->display_admin_page_with_no_sidebar();
2195
-    }
2196
-
2197
-
2198
-    /**
2199
-     * registers metaboxes that should show up on the "edit_message_template" page
2200
-     *
2201
-     * @access protected
2202
-     * @return void
2203
-     */
2204
-    protected function _register_edit_meta_boxes()
2205
-    {
2206
-        add_meta_box(
2207
-            'mtp_valid_shortcodes',
2208
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2209
-            array($this, 'shortcode_meta_box'),
2210
-            $this->_current_screen->id,
2211
-            'side',
2212
-            'default'
2213
-        );
2214
-        add_meta_box(
2215
-            'mtp_extra_actions',
2216
-            esc_html__('Extra Actions', 'event_espresso'),
2217
-            array($this, 'extra_actions_meta_box'),
2218
-            $this->_current_screen->id,
2219
-            'side',
2220
-            'high'
2221
-        );
2222
-        add_meta_box(
2223
-            'mtp_templates',
2224
-            esc_html__('Template Styles', 'event_espresso'),
2225
-            array($this, 'template_pack_meta_box'),
2226
-            $this->_current_screen->id,
2227
-            'side',
2228
-            'high'
2229
-        );
2230
-    }
2231
-
2232
-
2233
-    /**
2234
-     * metabox content for all template pack and variation selection.
2235
-     *
2236
-     * @since 4.5.0
2237
-     * @return string
2238
-     * @throws DomainException
2239
-     * @throws EE_Error
2240
-     * @throws InvalidArgumentException
2241
-     * @throws ReflectionException
2242
-     * @throws InvalidDataTypeException
2243
-     * @throws InvalidInterfaceException
2244
-     */
2245
-    public function template_pack_meta_box()
2246
-    {
2247
-        $this->_set_message_template_group();
2248
-
2249
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2250
-
2251
-        $tp_select_values = array();
2252
-
2253
-        foreach ($tp_collection as $tp) {
2254
-            // only include template packs that support this messenger and message type!
2255
-            $supports = $tp->get_supports();
2256
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2257
-                || ! in_array(
2258
-                    $this->_message_template_group->message_type(),
2259
-                    $supports[ $this->_message_template_group->messenger() ],
2260
-                    true
2261
-                )
2262
-            ) {
2263
-                // not supported
2264
-                continue;
2265
-            }
2266
-
2267
-            $tp_select_values[] = array(
2268
-                'text' => $tp->label,
2269
-                'id'   => $tp->dbref,
2270
-            );
2271
-        }
2272
-
2273
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2274
-        // the default template pack.  This still allows for the odd template pack to override.
2275
-        if (empty($tp_select_values)) {
2276
-            $tp_select_values[] = array(
2277
-                'text' => esc_html__('Default', 'event_espresso'),
2278
-                'id'   => 'default',
2279
-            );
2280
-        }
2281
-
2282
-        // setup variation select values for the currently selected template.
2283
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2284
-            $this->_message_template_group->messenger(),
2285
-            $this->_message_template_group->message_type()
2286
-        );
2287
-        $variations_select_values = array();
2288
-        foreach ($variations as $variation => $label) {
2289
-            $variations_select_values[] = array(
2290
-                'text' => $label,
2291
-                'id'   => $variation,
2292
-            );
2293
-        }
2294
-
2295
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2296
-
2297
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2298
-            'MTP_template_pack',
2299
-            $tp_select_values,
2300
-            $this->_message_template_group->get_template_pack_name()
2301
-        );
2302
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2303
-            'MTP_template_variation',
2304
-            $variations_select_values,
2305
-            $this->_message_template_group->get_template_pack_variation()
2306
-        );
2307
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2308
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2309
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2310
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2311
-
2312
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2313
-
2314
-        EEH_Template::display_template($template, $template_args);
2315
-    }
2316
-
2317
-
2318
-    /**
2319
-     * This meta box holds any extra actions related to Message Templates
2320
-     * For now, this includes Resetting templates to defaults and sending a test email.
2321
-     *
2322
-     * @access  public
2323
-     * @return void
2324
-     * @throws EE_Error
2325
-     */
2326
-    public function extra_actions_meta_box()
2327
-    {
2328
-        $template_form_fields = array();
2329
-
2330
-        $extra_args = array(
2331
-            'msgr'   => $this->_message_template_group->messenger(),
2332
-            'mt'     => $this->_message_template_group->message_type(),
2333
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2334
-        );
2335
-        // first we need to see if there are any fields
2336
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2337
-
2338
-        if (! empty($fields)) {
2339
-            // yup there be fields
2340
-            foreach ($fields as $field => $config) {
2341
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2342
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2343
-                $default = isset($config['default']) ? $config['default'] : '';
2344
-                $default = isset($config['value']) ? $config['value'] : $default;
2345
-
2346
-                // if type is hidden and the value is empty
2347
-                // something may have gone wrong so let's correct with the defaults
2348
-                $fix = $config['input'] === 'hidden'
2349
-                       && isset($existing[ $field ])
2350
-                       && empty($existing[ $field ])
2351
-                    ? $default
2352
-                    : '';
2353
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2354
-                    ? $existing[ $field ]
2355
-                    : $fix;
2356
-
2357
-                $template_form_fields[ $field_id ] = array(
2358
-                    'name'       => 'test_settings_fld[' . $field . ']',
2359
-                    'label'      => $config['label'],
2360
-                    'input'      => $config['input'],
2361
-                    'type'       => $config['type'],
2362
-                    'required'   => $config['required'],
2363
-                    'validation' => $config['validation'],
2364
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2365
-                    'css_class'  => $config['css_class'],
2366
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2367
-                    'default'    => $default,
2368
-                    'format'     => $config['format'],
2369
-                );
2370
-            }
2371
-        }
2372
-
2373
-        $test_settings_fields = ! empty($template_form_fields)
2374
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2375
-            : '';
2376
-
2377
-        $test_settings_html = '';
2378
-        // print out $test_settings_fields
2379
-        if (! empty($test_settings_fields)) {
2380
-            echo $test_settings_fields;
2381
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2382
-            $test_settings_html .= 'name="test_button" value="';
2383
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2384
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2385
-        }
2386
-
2387
-        // and button
2388
-        $test_settings_html .= '<p>'
2389
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2390
-                               . '</p>';
2391
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2392
-        $test_settings_html .= $this->get_action_link_or_button(
2393
-            'reset_to_default',
2394
-            'reset',
2395
-            $extra_args,
2396
-            'button-primary reset-default-button'
2397
-        );
2398
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2399
-        echo $test_settings_html;
2400
-    }
2401
-
2402
-
2403
-    /**
2404
-     * This returns the shortcode selector skeleton for a given context and field.
2405
-     *
2406
-     * @since 4.9.rc.000
2407
-     * @param string $field           The name of the field retrieving shortcodes for.
2408
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2409
-     * @return string
2410
-     * @throws DomainException
2411
-     * @throws EE_Error
2412
-     * @throws InvalidArgumentException
2413
-     * @throws ReflectionException
2414
-     * @throws InvalidDataTypeException
2415
-     * @throws InvalidInterfaceException
2416
-     */
2417
-    protected function _get_shortcode_selector($field, $linked_input_id)
2418
-    {
2419
-        $template_args = array(
2420
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2421
-            'fieldname'       => $field,
2422
-            'linked_input_id' => $linked_input_id,
2423
-        );
2424
-
2425
-        return EEH_Template::display_template(
2426
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2427
-            $template_args,
2428
-            true
2429
-        );
2430
-    }
2431
-
2432
-
2433
-    /**
2434
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2435
-     * page)
2436
-     *
2437
-     * @access public
2438
-     * @return void
2439
-     * @throws EE_Error
2440
-     * @throws InvalidArgumentException
2441
-     * @throws ReflectionException
2442
-     * @throws InvalidDataTypeException
2443
-     * @throws InvalidInterfaceException
2444
-     */
2445
-    public function shortcode_meta_box()
2446
-    {
2447
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2448
-        // $messenger = $this->_message_template_group->messenger_obj();
2449
-        // now let's set the content depending on the status of the shortcodes array
2450
-        if (empty($shortcodes)) {
2451
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2452
-            echo $content;
2453
-        } else {
2454
-            // $alt = 0;
2455
-            ?>
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
565
+				'require_nonce' => false,
566
+			),
567
+			'custom_mtps'              => array(
568
+				'nav'           => array(
569
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
+					'order' => 30,
571
+				),
572
+				'help_tabs'     => array(),
573
+				'help_tour'     => array(),
574
+				'require_nonce' => false,
575
+			),
576
+			'add_new_message_template' => array(
577
+				'nav'           => array(
578
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
+					'order'      => 5,
580
+					'persistent' => false,
581
+				),
582
+				'require_nonce' => false,
583
+			),
584
+			'edit_message_template'    => array(
585
+				'labels'        => array(
586
+					'buttons'    => array(
587
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
+					),
589
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
+				),
591
+				'nav'           => array(
592
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
+					'order'      => 5,
594
+					'persistent' => false,
595
+					'url'        => '',
596
+				),
597
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
+				'has_metaboxes' => true,
599
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
+				'help_tabs'     => array(
601
+					'edit_message_template'            => array(
602
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
+						'callback' => 'edit_message_template_help_tab',
604
+					),
605
+					'message_templates_help_tab'       => array(
606
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
607
+						'filename' => 'messages_templates',
608
+					),
609
+					'message_template_shortcodes'      => array(
610
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
+						'callback' => 'message_template_shortcodes_help_tab',
612
+					),
613
+					'message_preview_help_tab'         => array(
614
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
615
+						'filename' => 'messages_preview',
616
+					),
617
+					'messages_overview_other_help_tab' => array(
618
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
619
+						'filename' => 'messages_overview_other',
620
+					),
621
+				),
622
+				'require_nonce' => false,
623
+			),
624
+			'display_preview_message'  => array(
625
+				'nav'           => array(
626
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
627
+					'order'      => 5,
628
+					'url'        => '',
629
+					'persistent' => false,
630
+				),
631
+				'help_tabs'     => array(
632
+					'preview_message' => array(
633
+						'title'    => esc_html__('About Previews', 'event_espresso'),
634
+						'callback' => 'preview_message_help_tab',
635
+					),
636
+				),
637
+				'require_nonce' => false,
638
+			),
639
+			'settings'                 => array(
640
+				'nav'           => array(
641
+					'label' => esc_html__('Settings', 'event_espresso'),
642
+					'order' => 40,
643
+				),
644
+				'metaboxes'     => array('_messages_settings_metaboxes'),
645
+				'help_tabs'     => array(
646
+					'messages_settings_help_tab'               => array(
647
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
+						'filename' => 'messages_settings',
649
+					),
650
+					'messages_settings_message_types_help_tab' => array(
651
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
+						'filename' => 'messages_settings_message_types',
653
+					),
654
+					'messages_settings_messengers_help_tab'    => array(
655
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
+						'filename' => 'messages_settings_messengers',
657
+					),
658
+				),
659
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
660
+				'require_nonce' => false,
661
+			),
662
+		);
663
+	}
664
+
665
+
666
+	protected function _add_screen_options()
667
+	{
668
+		// todo
669
+	}
670
+
671
+
672
+	protected function _add_screen_options_global_mtps()
673
+	{
674
+		/**
675
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
677
+		 */
678
+		$page_title = $this->_admin_page_title;
679
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
+		$this->_per_page_screen_option();
681
+		$this->_admin_page_title = $page_title;
682
+	}
683
+
684
+
685
+	protected function _add_screen_options_default()
686
+	{
687
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
+		$this->_per_page_screen_option();
689
+	}
690
+
691
+
692
+	// none of the below group are currently used for Messages
693
+	protected function _add_feature_pointers()
694
+	{
695
+	}
696
+
697
+	public function admin_init()
698
+	{
699
+	}
700
+
701
+	public function admin_notices()
702
+	{
703
+	}
704
+
705
+	public function admin_footer_scripts()
706
+	{
707
+	}
708
+
709
+
710
+	public function messages_help_tab()
711
+	{
712
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
+	}
714
+
715
+
716
+	public function messengers_help_tab()
717
+	{
718
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
+	}
720
+
721
+
722
+	public function message_types_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messages_overview_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_templates_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function edit_message_template_help_tab()
741
+	{
742
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
+						. esc_attr__('Editor Title', 'event_espresso')
744
+						. '" />';
745
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
747
+						. '" />';
748
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
750
+						. '" />';
751
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
753
+						. '" />';
754
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
+						. esc_attr__('Publish Metabox', 'event_espresso')
756
+						. '" />';
757
+		EEH_Template::display_template(
758
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
+			$args
760
+		);
761
+	}
762
+
763
+
764
+	public function message_template_shortcodes_help_tab()
765
+	{
766
+		$this->_set_shortcodes();
767
+		$args['shortcodes'] = $this->_shortcodes;
768
+		EEH_Template::display_template(
769
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
+			$args
771
+		);
772
+	}
773
+
774
+
775
+	public function preview_message_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function settings_help_tab()
782
+	{
783
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
+		$args['img3'] = '<div class="switch">'
788
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
+						. ' type="checkbox" checked="checked">'
790
+						. '<label for="ee-on-off-toggle-on"></label>'
791
+						. '</div>';
792
+		$args['img4'] = '<div class="switch">'
793
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
+						. ' type="checkbox">'
795
+						. '<label for="ee-on-off-toggle-on"></label>'
796
+						. '</div>';
797
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
+	}
799
+
800
+
801
+	public function load_scripts_styles()
802
+	{
803
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
+		wp_enqueue_style('espresso_ee_msg');
805
+
806
+		wp_register_script(
807
+			'ee-messages-settings',
808
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
+			EVENT_ESPRESSO_VERSION,
811
+			true
812
+		);
813
+		wp_register_script(
814
+			'ee-msg-list-table-js',
815
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
+			array('ee-dialog'),
817
+			EVENT_ESPRESSO_VERSION
818
+		);
819
+	}
820
+
821
+
822
+	public function load_scripts_styles_default()
823
+	{
824
+		wp_enqueue_script('ee-msg-list-table-js');
825
+	}
826
+
827
+
828
+	public function wp_editor_css($mce_css)
829
+	{
830
+		// if we're on the edit_message_template route
831
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
+			$message_type_name = $this->_active_message_type_name;
833
+
834
+			// we're going to REPLACE the existing mce css
835
+			// we need to get the css file location from the active messenger
836
+			$mce_css = $this->_active_messenger->get_variation(
837
+				$this->_template_pack,
838
+				$message_type_name,
839
+				true,
840
+				'wpeditor',
841
+				$this->_variation
842
+			);
843
+		}
844
+
845
+		return $mce_css;
846
+	}
847
+
848
+
849
+	public function load_scripts_styles_edit_message_template()
850
+	{
851
+
852
+		$this->_set_shortcodes();
853
+
854
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
+			esc_html__(
856
+				'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.',
857
+				'event_espresso'
858
+			),
859
+			$this->_message_template_group->messenger_obj()->label['singular'],
860
+			$this->_message_template_group->message_type_obj()->label['singular']
861
+		);
862
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
+			'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?',
864
+			'event_espresso'
865
+		);
866
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
+			'event_espresso'
869
+		);
870
+
871
+		wp_register_script(
872
+			'ee_msgs_edit_js',
873
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
+			array('jquery'),
875
+			EVENT_ESPRESSO_VERSION
876
+		);
877
+
878
+		wp_enqueue_script('ee_admin_js');
879
+		wp_enqueue_script('ee_msgs_edit_js');
880
+
881
+		// add in special css for tiny_mce
882
+		add_filter('mce_css', array($this, 'wp_editor_css'));
883
+	}
884
+
885
+
886
+	public function load_scripts_styles_display_preview_message()
887
+	{
888
+
889
+		$this->_set_message_template_group();
890
+
891
+		if (isset($this->_req_data['messenger'])) {
892
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
+				$this->_req_data['messenger']
894
+			);
895
+		}
896
+
897
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
+
899
+
900
+		wp_enqueue_style(
901
+			'espresso_preview_css',
902
+			$this->_active_messenger->get_variation(
903
+				$this->_template_pack,
904
+				$message_type_name,
905
+				true,
906
+				'preview',
907
+				$this->_variation
908
+			)
909
+		);
910
+	}
911
+
912
+
913
+	public function load_scripts_styles_settings()
914
+	{
915
+		wp_register_style(
916
+			'ee-message-settings',
917
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
+			array(),
919
+			EVENT_ESPRESSO_VERSION
920
+		);
921
+		wp_enqueue_style('ee-text-links');
922
+		wp_enqueue_style('ee-message-settings');
923
+		wp_enqueue_script('ee-messages-settings');
924
+	}
925
+
926
+
927
+	/**
928
+	 * set views array for List Table
929
+	 */
930
+	public function _set_list_table_views_global_mtps()
931
+	{
932
+		$this->_views = array(
933
+			'in_use' => array(
934
+				'slug'  => 'in_use',
935
+				'label' => esc_html__('In Use', 'event_espresso'),
936
+				'count' => 0,
937
+			),
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * Set views array for the Custom Template List Table
944
+	 */
945
+	public function _set_list_table_views_custom_mtps()
946
+	{
947
+		$this->_set_list_table_views_global_mtps();
948
+		$this->_views['in_use']['bulk_action'] = array(
949
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
+		);
951
+	}
952
+
953
+
954
+	/**
955
+	 * set views array for message queue list table
956
+	 *
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidArgumentException
960
+	 * @throws EE_Error
961
+	 * @throws ReflectionException
962
+	 */
963
+	public function _set_list_table_views_default()
964
+	{
965
+		EE_Registry::instance()->load_helper('Template');
966
+
967
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
+			'ee_send_message',
969
+			'message_list_table_bulk_actions'
970
+		)
971
+			? array(
972
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
+			)
977
+			: array();
978
+
979
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
+			'ee_delete_messages',
981
+			'message_list_table_bulk_actions'
982
+		)
983
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
+			: array();
985
+
986
+
987
+		$this->_views = array(
988
+			'all' => array(
989
+				'slug'        => 'all',
990
+				'label'       => esc_html__('All', 'event_espresso'),
991
+				'count'       => 0,
992
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
+			),
994
+		);
995
+
996
+
997
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
998
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
+				continue;
1000
+			}
1001
+			$status_bulk_actions = $common_bulk_actions;
1002
+			// unset bulk actions not applying to status
1003
+			if (! empty($status_bulk_actions)) {
1004
+				switch ($status) {
1005
+					case EEM_Message::status_idle:
1006
+					case EEM_Message::status_resend:
1007
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
+						break;
1009
+
1010
+					case EEM_Message::status_failed:
1011
+					case EEM_Message::status_debug_only:
1012
+					case EEM_Message::status_messenger_executing:
1013
+						$status_bulk_actions = array();
1014
+						break;
1015
+
1016
+					case EEM_Message::status_incomplete:
1017
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
+						break;
1019
+
1020
+					case EEM_Message::status_retry:
1021
+					case EEM_Message::status_sent:
1022
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
+						break;
1024
+				}
1025
+			}
1026
+
1027
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1028
+			if ($status === EEM_Message::status_messenger_executing) {
1029
+				continue;
1030
+			}
1031
+
1032
+			$this->_views[ strtolower($status) ] = array(
1033
+				'slug'        => strtolower($status),
1034
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
+				'count'       => 0,
1036
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
+			);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	protected function _ee_default_messages_overview_list_table()
1043
+	{
1044
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
+		$this->display_admin_list_table_page_with_no_sidebar();
1046
+	}
1047
+
1048
+
1049
+	protected function _message_queue_list_table()
1050
+	{
1051
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
+		$this->_template_args['per_column'] = 6;
1053
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
+		$this->_template_args['before_list_table'] = '<h3>'
1055
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1056
+													 . '</h3>';
1057
+		$this->display_admin_list_table_page_with_no_sidebar();
1058
+	}
1059
+
1060
+
1061
+	protected function _message_legend_items()
1062
+	{
1063
+
1064
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
+		$action_items = array();
1066
+
1067
+		foreach ($action_css_classes as $action_item => $action_details) {
1068
+			if ($action_item === 'see_notifications_for') {
1069
+				continue;
1070
+			}
1071
+			$action_items[ $action_item ] = array(
1072
+				'class' => $action_details['css_class'],
1073
+				'desc'  => $action_details['label'],
1074
+			);
1075
+		}
1076
+
1077
+		/** @type array $status_items status legend setup */
1078
+		$status_items = array(
1079
+			'sent_status'                => array(
1080
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
+			),
1083
+			'idle_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
+			),
1087
+			'failed_status'              => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
+			),
1091
+			'messenger_executing_status' => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
+			),
1095
+			'resend_status'              => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
+			),
1099
+			'incomplete_status'          => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
+			),
1103
+			'retry_status'               => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
+			),
1107
+		);
1108
+		if (EEM_Message::debug()) {
1109
+			$status_items['debug_only_status'] = array(
1110
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
+			);
1113
+		}
1114
+
1115
+		return array_merge($action_items, $status_items);
1116
+	}
1117
+
1118
+
1119
+	protected function _custom_mtps_preview()
1120
+	{
1121
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
+											   . ' alt="' . esc_attr__(
1124
+												   'Preview Custom Message Templates screenshot',
1125
+												   'event_espresso'
1126
+											   ) . '" />';
1127
+		$this->_template_args['preview_text'] = '<strong>'
1128
+												. esc_html__(
1129
+													'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.',
1130
+													'event_espresso'
1131
+												)
1132
+												. '</strong>';
1133
+
1134
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * get_message_templates
1140
+	 * This gets all the message templates for listing on the overview list.
1141
+	 *
1142
+	 * @access public
1143
+	 * @param int    $perpage the amount of templates groups to show per page
1144
+	 * @param string $type    the current _view we're getting templates for
1145
+	 * @param bool   $count   return count?
1146
+	 * @param bool   $all     disregard any paging info (get all data);
1147
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
+	 * @return array
1149
+	 * @throws EE_Error
1150
+	 * @throws InvalidArgumentException
1151
+	 * @throws InvalidDataTypeException
1152
+	 * @throws InvalidInterfaceException
1153
+	 */
1154
+	public function get_message_templates(
1155
+		$perpage = 10,
1156
+		$type = 'in_use',
1157
+		$count = false,
1158
+		$all = false,
1159
+		$global = true
1160
+	) {
1161
+
1162
+		$MTP = EEM_Message_Template_Group::instance();
1163
+
1164
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
+		$orderby = $this->_req_data['orderby'];
1166
+
1167
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
+			? $this->_req_data['order']
1169
+			: 'ASC';
1170
+
1171
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
+			? $this->_req_data['paged']
1173
+			: 1;
1174
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
+			? $this->_req_data['perpage']
1176
+			: $perpage;
1177
+
1178
+		$offset = ($current_page - 1) * $per_page;
1179
+		$limit = $all ? null : array($offset, $per_page);
1180
+
1181
+
1182
+		// options will match what is in the _views array property
1183
+		switch ($type) {
1184
+			case 'in_use':
1185
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
+				break;
1187
+			default:
1188
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
+		}
1190
+
1191
+		return $templates;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * filters etc might need a list of installed message_types
1197
+	 *
1198
+	 * @return array an array of message type objects
1199
+	 */
1200
+	public function get_installed_message_types()
1201
+	{
1202
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
+		$installed = array();
1204
+
1205
+		foreach ($installed_message_types as $message_type) {
1206
+			$installed[ $message_type->name ] = $message_type;
1207
+		}
1208
+
1209
+		return $installed;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * _add_message_template
1215
+	 *
1216
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1217
+	 *
1218
+	 * @param string $message_type
1219
+	 * @param string $messenger
1220
+	 * @param string $GRP_ID
1221
+	 *
1222
+	 * @throws EE_error
1223
+	 */
1224
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
+	{
1226
+		// set values override any request data
1227
+		$message_type = ! empty($message_type) ? $message_type : '';
1228
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
+			? $this->_req_data['message_type']
1230
+			: $message_type;
1231
+
1232
+		$messenger = ! empty($messenger) ? $messenger : '';
1233
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
+			? $this->_req_data['messenger']
1235
+			: $messenger;
1236
+
1237
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
+
1240
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
+		if (empty($message_type) || empty($messenger)) {
1242
+			throw new EE_Error(
1243
+				esc_html__(
1244
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
+					'event_espresso'
1246
+				)
1247
+			);
1248
+		}
1249
+
1250
+		// we need the GRP_ID for the template being used as the base for the new template
1251
+		if (empty($GRP_ID)) {
1252
+			throw new EE_Error(
1253
+				esc_html__(
1254
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
+					'event_espresso'
1256
+				)
1257
+			);
1258
+		}
1259
+
1260
+		// let's just make sure the template gets generated!
1261
+
1262
+		// we need to reassign some variables for what the insert is expecting
1263
+		$this->_req_data['MTP_messenger'] = $messenger;
1264
+		$this->_req_data['MTP_message_type'] = $message_type;
1265
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1266
+		$this->_insert_or_update_message_template(true);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * public wrapper for the _add_message_template method
1272
+	 *
1273
+	 * @param string $message_type     message type slug
1274
+	 * @param string $messenger        messenger slug
1275
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
+	 *                                 off of.
1277
+	 * @throws EE_error
1278
+	 */
1279
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1280
+	{
1281
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * _edit_message_template
1287
+	 *
1288
+	 * @access protected
1289
+	 * @return void
1290
+	 * @throws InvalidIdentifierException
1291
+	 * @throws DomainException
1292
+	 * @throws EE_Error
1293
+	 * @throws InvalidArgumentException
1294
+	 * @throws ReflectionException
1295
+	 * @throws InvalidDataTypeException
1296
+	 * @throws InvalidInterfaceException
1297
+	 */
1298
+	protected function _edit_message_template()
1299
+	{
1300
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
+		$template_fields = '';
1302
+		$sidebar_fields = '';
1303
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
+		// valid html in the templates.
1305
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
+
1307
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
+			? absint($this->_req_data['id'])
1309
+			: false;
1310
+
1311
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1312
+		$message_template_group = $this->_message_template_group;
1313
+		$c_label = $message_template_group->context_label();
1314
+		$c_config = $message_template_group->contexts_config();
1315
+
1316
+		reset($c_config);
1317
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
+			? strtolower($this->_req_data['context'])
1319
+			: key($c_config);
1320
+
1321
+
1322
+		if (empty($GRP_ID)) {
1323
+			$action = 'insert_message_template';
1324
+			$edit_message_template_form_url = add_query_arg(
1325
+				array('action' => $action, 'noheader' => true),
1326
+				EE_MSG_ADMIN_URL
1327
+			);
1328
+		} else {
1329
+			$action = 'update_message_template';
1330
+			$edit_message_template_form_url = add_query_arg(
1331
+				array('action' => $action, 'noheader' => true),
1332
+				EE_MSG_ADMIN_URL
1333
+			);
1334
+		}
1335
+
1336
+		// set active messenger for this view
1337
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
+			$message_template_group->messenger()
1339
+		);
1340
+		$this->_active_message_type_name = $message_template_group->message_type();
1341
+
1342
+
1343
+		// Do we have any validation errors?
1344
+		$validators = $this->_get_transient();
1345
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
+
1347
+
1348
+		// we need to assemble the title from Various details
1349
+		$context_label = sprintf(
1350
+			esc_html__('(%s %s)', 'event_espresso'),
1351
+			$c_config[ $context ]['label'],
1352
+			ucwords($c_label['label'])
1353
+		);
1354
+
1355
+		$title = sprintf(
1356
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1357
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1358
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1359
+			$context_label
1360
+		);
1361
+
1362
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1363
+		$this->_template_args['message_template'] = $message_template_group;
1364
+		$this->_template_args['is_extra_fields'] = false;
1365
+
1366
+
1367
+		// let's get EEH_MSG_Template so we can get template form fields
1368
+		$template_field_structure = EEH_MSG_Template::get_fields(
1369
+			$message_template_group->messenger(),
1370
+			$message_template_group->message_type()
1371
+		);
1372
+
1373
+		if (! $template_field_structure) {
1374
+			$template_field_structure = false;
1375
+			$template_fields = esc_html__(
1376
+				'There was an error in assembling the fields for this display (you should see an error message)',
1377
+				'event_espresso'
1378
+			);
1379
+		}
1380
+
1381
+
1382
+		$message_templates = $message_template_group->context_templates();
1383
+
1384
+
1385
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
+		// will get handled in the "extra" array.
1387
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
+				unset($template_field_structure[ $context ][ $reference_field ]);
1390
+			}
1391
+		}
1392
+
1393
+		// let's loop through the template_field_structure and actually assemble the input fields!
1394
+		if (! empty($template_field_structure)) {
1395
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
+				// the extra array and reset them.
1398
+				if ($template_field === 'extra') {
1399
+					$this->_template_args['is_extra_fields'] = true;
1400
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
+						$message_template = $message_templates[ $context ][ $reference_field ];
1402
+						$content = $message_template instanceof EE_Message_Template
1403
+							? $message_template->get('MTP_content')
1404
+							: '';
1405
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1406
+							// let's verify if we need this extra field via the shortcodes parameter.
1407
+							$continue = false;
1408
+							if (isset($extra_array['shortcodes_required'])) {
1409
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
+										$continue = true;
1412
+									}
1413
+								}
1414
+								if ($continue) {
1415
+									continue;
1416
+								}
1417
+							}
1418
+
1419
+							$field_id = $reference_field
1420
+										. '-'
1421
+										. $extra_field
1422
+										. '-content';
1423
+							$template_form_fields[ $field_id ] = $extra_array;
1424
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
+																		 . $reference_field
1426
+																		 . '][content]['
1427
+																		 . $extra_field . ']';
1428
+							$css_class = isset($extra_array['css_class'])
1429
+								? $extra_array['css_class']
1430
+								: '';
1431
+
1432
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
+																			  && in_array($extra_field, $v_fields, true)
1434
+																			  &&
1435
+																			  (
1436
+																				  is_array($validators[ $extra_field ])
1437
+																				  && isset($validators[ $extra_field ]['msg'])
1438
+																			  )
1439
+								? 'validate-error ' . $css_class
1440
+								: $css_class;
1441
+
1442
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
+																		  && isset($content[ $extra_field ])
1444
+								? $content[ $extra_field ]
1445
+								: '';
1446
+
1447
+							// do we have a validation error?  if we do then let's use that value instead
1448
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
+								? $validators[ $extra_field ]['value']
1450
+								: $template_form_fields[ $field_id ]['value'];
1451
+
1452
+
1453
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
+
1455
+							// shortcode selector
1456
+							$field_name_to_use = $extra_field === 'main'
1457
+								? 'content'
1458
+								: $extra_field;
1459
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
+								$field_name_to_use,
1461
+								$field_id
1462
+							);
1463
+
1464
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
+								// we want to decode the entities
1466
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
+							}/**/
1468
+						}
1469
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
+						$templatefield_templatename_id = $reference_field . '-name';
1471
+
1472
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1473
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
+							'label'      => null,
1475
+							'input'      => 'hidden',
1476
+							'type'       => 'int',
1477
+							'required'   => false,
1478
+							'validation' => false,
1479
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
+							'css_class'  => '',
1481
+							'format'     => '%d',
1482
+							'db-col'     => 'MTP_ID',
1483
+						);
1484
+
1485
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1486
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
+							'label'      => null,
1488
+							'input'      => 'hidden',
1489
+							'type'       => 'string',
1490
+							'required'   => false,
1491
+							'validation' => true,
1492
+							'value'      => $reference_field,
1493
+							'css_class'  => '',
1494
+							'format'     => '%s',
1495
+							'db-col'     => 'MTP_template_field',
1496
+						);
1497
+					}
1498
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
+				} else {
1500
+					$field_id = $template_field . '-content';
1501
+					$template_form_fields[ $field_id ] = $field_setup_array;
1502
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1504
+						? $message_templates[ $context ][ $template_field ]
1505
+						: null;
1506
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
+																  && is_array($message_templates[ $context ])
1508
+																  && $message_template instanceof EE_Message_Template
1509
+						? $message_template->get('MTP_content')
1510
+						: '';
1511
+
1512
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1513
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
+						? $validators[ $template_field ]['value']
1515
+						: $template_form_fields[ $field_id ]['value'];
1516
+
1517
+
1518
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
+					$css_class = isset($field_setup_array['css_class'])
1520
+						? $field_setup_array['css_class']
1521
+						: '';
1522
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
+																	  && in_array($template_field, $v_fields, true)
1524
+																	  && isset($validators[ $template_field ]['msg'])
1525
+						? 'validate-error ' . $css_class
1526
+						: $css_class;
1527
+
1528
+					// shortcode selector
1529
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
+						$template_field,
1531
+						$field_id
1532
+					);
1533
+				}
1534
+
1535
+				// k took care of content field(s) now let's take care of others.
1536
+
1537
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1538
+				$templatefield_field_templatename_id = $template_field . '-name';
1539
+
1540
+				// foreach template field there are actually two form fields created
1541
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1542
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
+					'label'      => null,
1544
+					'input'      => 'hidden',
1545
+					'type'       => 'int',
1546
+					'required'   => false,
1547
+					'validation' => true,
1548
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
+					'css_class'  => '',
1550
+					'format'     => '%d',
1551
+					'db-col'     => 'MTP_ID',
1552
+				);
1553
+
1554
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
+					'label'      => null,
1557
+					'input'      => 'hidden',
1558
+					'type'       => 'string',
1559
+					'required'   => false,
1560
+					'validation' => true,
1561
+					'value'      => $template_field,
1562
+					'css_class'  => '',
1563
+					'format'     => '%s',
1564
+					'db-col'     => 'MTP_template_field',
1565
+				);
1566
+			}
1567
+
1568
+			// add other fields
1569
+			$template_form_fields['ee-msg-current-context'] = array(
1570
+				'name'       => 'MTP_context',
1571
+				'label'      => null,
1572
+				'input'      => 'hidden',
1573
+				'type'       => 'string',
1574
+				'required'   => false,
1575
+				'validation' => true,
1576
+				'value'      => $context,
1577
+				'css_class'  => '',
1578
+				'format'     => '%s',
1579
+				'db-col'     => 'MTP_context',
1580
+			);
1581
+
1582
+			$template_form_fields['ee-msg-grp-id'] = array(
1583
+				'name'       => 'GRP_ID',
1584
+				'label'      => null,
1585
+				'input'      => 'hidden',
1586
+				'type'       => 'int',
1587
+				'required'   => false,
1588
+				'validation' => true,
1589
+				'value'      => $GRP_ID,
1590
+				'css_class'  => '',
1591
+				'format'     => '%d',
1592
+				'db-col'     => 'GRP_ID',
1593
+			);
1594
+
1595
+			$template_form_fields['ee-msg-messenger'] = array(
1596
+				'name'       => 'MTP_messenger',
1597
+				'label'      => null,
1598
+				'input'      => 'hidden',
1599
+				'type'       => 'string',
1600
+				'required'   => false,
1601
+				'validation' => true,
1602
+				'value'      => $message_template_group->messenger(),
1603
+				'css_class'  => '',
1604
+				'format'     => '%s',
1605
+				'db-col'     => 'MTP_messenger',
1606
+			);
1607
+
1608
+			$template_form_fields['ee-msg-message-type'] = array(
1609
+				'name'       => 'MTP_message_type',
1610
+				'label'      => null,
1611
+				'input'      => 'hidden',
1612
+				'type'       => 'string',
1613
+				'required'   => false,
1614
+				'validation' => true,
1615
+				'value'      => $message_template_group->message_type(),
1616
+				'css_class'  => '',
1617
+				'format'     => '%s',
1618
+				'db-col'     => 'MTP_message_type',
1619
+			);
1620
+
1621
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1622
+				'name'       => 'MTP_is_global',
1623
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1624
+				'input'      => 'hidden',
1625
+				'type'       => 'int',
1626
+				'required'   => false,
1627
+				'validation' => true,
1628
+				'value'      => $message_template_group->get('MTP_is_global'),
1629
+				'css_class'  => '',
1630
+				'format'     => '%d',
1631
+				'db-col'     => 'MTP_is_global',
1632
+			);
1633
+
1634
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1635
+				'name'       => 'MTP_is_override',
1636
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
+				'type'       => 'int',
1639
+				'required'   => false,
1640
+				'validation' => true,
1641
+				'value'      => $message_template_group->get('MTP_is_override'),
1642
+				'css_class'  => '',
1643
+				'format'     => '%d',
1644
+				'db-col'     => 'MTP_is_override',
1645
+			);
1646
+
1647
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1648
+				'name'       => 'MTP_is_active',
1649
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1650
+				'input'      => 'hidden',
1651
+				'type'       => 'int',
1652
+				'required'   => false,
1653
+				'validation' => true,
1654
+				'value'      => $message_template_group->is_active(),
1655
+				'css_class'  => '',
1656
+				'format'     => '%d',
1657
+				'db-col'     => 'MTP_is_active',
1658
+			);
1659
+
1660
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1661
+				'name'       => 'MTP_deleted',
1662
+				'label'      => null,
1663
+				'input'      => 'hidden',
1664
+				'type'       => 'int',
1665
+				'required'   => false,
1666
+				'validation' => true,
1667
+				'value'      => $message_template_group->get('MTP_deleted'),
1668
+				'css_class'  => '',
1669
+				'format'     => '%d',
1670
+				'db-col'     => 'MTP_deleted',
1671
+			);
1672
+			$sidebar_form_fields['ee-msg-author'] = array(
1673
+				'name'       => 'MTP_user_id',
1674
+				'label'      => esc_html__('Author', 'event_espresso'),
1675
+				'input'      => 'hidden',
1676
+				'type'       => 'int',
1677
+				'required'   => false,
1678
+				'validation' => false,
1679
+				'value'      => $message_template_group->user(),
1680
+				'format'     => '%d',
1681
+				'db-col'     => 'MTP_user_id',
1682
+			);
1683
+
1684
+			$sidebar_form_fields['ee-msg-route'] = array(
1685
+				'name'  => 'action',
1686
+				'input' => 'hidden',
1687
+				'type'  => 'string',
1688
+				'value' => $action,
1689
+			);
1690
+
1691
+			$sidebar_form_fields['ee-msg-id'] = array(
1692
+				'name'  => 'id',
1693
+				'input' => 'hidden',
1694
+				'type'  => 'int',
1695
+				'value' => $GRP_ID,
1696
+			);
1697
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
+				'name'  => $action . '_nonce',
1699
+				'input' => 'hidden',
1700
+				'type'  => 'string',
1701
+				'value' => wp_create_nonce($action . '_nonce'),
1702
+			);
1703
+
1704
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1706
+					'name'  => 'template_switch',
1707
+					'input' => 'hidden',
1708
+					'type'  => 'int',
1709
+					'value' => 1,
1710
+				);
1711
+			}
1712
+
1713
+
1714
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
+		} //end if ( !empty($template_field_structure) )
1717
+
1718
+		// set extra content for publish box
1719
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
+		$this->_set_publish_post_box_vars(
1721
+			'id',
1722
+			$GRP_ID,
1723
+			false,
1724
+			add_query_arg(
1725
+				array('action' => 'global_mtps'),
1726
+				$this->_admin_base_url
1727
+			)
1728
+		);
1729
+
1730
+		// add preview button
1731
+		$preview_url = parent::add_query_args_and_nonce(
1732
+			array(
1733
+				'message_type' => $message_template_group->message_type(),
1734
+				'messenger'    => $message_template_group->messenger(),
1735
+				'context'      => $context,
1736
+				'GRP_ID'       => $GRP_ID,
1737
+				'action'       => 'preview_message',
1738
+			),
1739
+			$this->_admin_base_url
1740
+		);
1741
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
+						  . esc_html__('Preview', 'event_espresso')
1743
+						  . '</a>';
1744
+
1745
+
1746
+		// setup context switcher
1747
+		$context_switcher_args = array(
1748
+			'page'    => 'espresso_messages',
1749
+			'action'  => 'edit_message_template',
1750
+			'id'      => $GRP_ID,
1751
+			'context' => $context,
1752
+			'extra'   => $preview_button,
1753
+		);
1754
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
+
1756
+
1757
+		// main box
1758
+		$this->_template_args['template_fields'] = $template_fields;
1759
+		$this->_template_args['sidebar_box_id'] = 'details';
1760
+		$this->_template_args['action'] = $action;
1761
+		$this->_template_args['context'] = $context;
1762
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
+		$this->_template_args['learn_more_about_message_templates_link'] =
1764
+			$this->_learn_more_about_message_templates_link();
1765
+
1766
+
1767
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
+			$message_template_group,
1770
+			$context,
1771
+			$context_label
1772
+		);
1773
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
+
1776
+		$this->_template_path = $this->_template_args['GRP_ID']
1777
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
+
1780
+		// send along EE_Message_Template_Group object for further template use.
1781
+		$this->_template_args['MTP'] = $message_template_group;
1782
+
1783
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
+			$this->_template_path,
1785
+			$this->_template_args,
1786
+			true
1787
+		);
1788
+
1789
+
1790
+		// finally, let's set the admin_page title
1791
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
+
1793
+
1794
+		// we need to take care of setting the shortcodes property for use elsewhere.
1795
+		$this->_set_shortcodes();
1796
+
1797
+
1798
+		// final template wrapper
1799
+		$this->display_admin_page_with_sidebar();
1800
+	}
1801
+
1802
+
1803
+	public function filter_tinymce_init($mceInit, $editor_id)
1804
+	{
1805
+		return $mceInit;
1806
+	}
1807
+
1808
+
1809
+	public function add_context_switcher()
1810
+	{
1811
+		return $this->_context_switcher;
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Adds the activation/deactivation toggle for the message template context.
1817
+	 *
1818
+	 * @param EE_Message_Template_Group $message_template_group
1819
+	 * @param string                    $context
1820
+	 * @param string                    $context_label
1821
+	 * @return string
1822
+	 * @throws DomainException
1823
+	 * @throws EE_Error
1824
+	 * @throws InvalidIdentifierException
1825
+	 */
1826
+	protected function add_active_context_element(
1827
+		EE_Message_Template_Group $message_template_group,
1828
+		$context,
1829
+		$context_label
1830
+	) {
1831
+		$template_args = array(
1832
+			'context'                   => $context,
1833
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
+			'is_active'                 => $message_template_group->is_context_active($context),
1835
+			'on_off_action'             => $message_template_group->is_context_active($context)
1836
+				? 'context-off'
1837
+				: 'context-on',
1838
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
+			'message_template_group_id' => $message_template_group->ID(),
1840
+		);
1841
+		return EEH_Template::display_template(
1842
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
+			$template_args,
1844
+			true
1845
+		);
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * Ajax callback for `toggle_context_template` ajax action.
1851
+	 * Handles toggling the message context on or off.
1852
+	 *
1853
+	 * @throws EE_Error
1854
+	 * @throws InvalidArgumentException
1855
+	 * @throws InvalidDataTypeException
1856
+	 * @throws InvalidIdentifierException
1857
+	 * @throws InvalidInterfaceException
1858
+	 */
1859
+	public function toggle_context_template()
1860
+	{
1861
+		$success = true;
1862
+		// check for required data
1863
+		if (! isset(
1864
+			$this->_req_data['message_template_group_id'],
1865
+			$this->_req_data['context'],
1866
+			$this->_req_data['status']
1867
+		)) {
1868
+			EE_Error::add_error(
1869
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
+				__FILE__,
1871
+				__FUNCTION__,
1872
+				__LINE__
1873
+			);
1874
+			$success = false;
1875
+		}
1876
+
1877
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1878
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
+			: '';
1880
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
+		$this->_verify_nonce($nonce, $nonce_ref);
1882
+		$status = $this->_req_data['status'];
1883
+		if ($status !== 'off' && $status !== 'on') {
1884
+			EE_Error::add_error(
1885
+				sprintf(
1886
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
+					$this->_req_data['status']
1888
+				),
1889
+				__FILE__,
1890
+				__FUNCTION__,
1891
+				__LINE__
1892
+			);
1893
+			$success = false;
1894
+		}
1895
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
+			$this->_req_data['message_template_group_id']
1897
+		);
1898
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
+			EE_Error::add_error(
1900
+				sprintf(
1901
+					esc_html__(
1902
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
+						'event_espresso'
1904
+					),
1905
+					$this->_req_data['message_template_group_id'],
1906
+					'EE_Message_Template_Group'
1907
+				),
1908
+				__FILE__,
1909
+				__FUNCTION__,
1910
+				__LINE__
1911
+			);
1912
+			$success = false;
1913
+		}
1914
+		if ($success) {
1915
+			$success = $status === 'off'
1916
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1917
+				: $message_template_group->activate_context($this->_req_data['context']);
1918
+		}
1919
+		$this->_template_args['success'] = $success;
1920
+		$this->_return_json();
1921
+	}
1922
+
1923
+
1924
+	public function _add_form_element_before()
1925
+	{
1926
+		return '<form method="post" action="'
1927
+			   . $this->_template_args["edit_message_template_form_url"]
1928
+			   . '" id="ee-msg-edit-frm">';
1929
+	}
1930
+
1931
+	public function _add_form_element_after()
1932
+	{
1933
+		return '</form>';
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * This executes switching the template pack for a message template.
1939
+	 *
1940
+	 * @since 4.5.0
1941
+	 * @throws EE_Error
1942
+	 * @throws InvalidDataTypeException
1943
+	 * @throws InvalidInterfaceException
1944
+	 * @throws InvalidArgumentException
1945
+	 * @throws ReflectionException
1946
+	 */
1947
+	public function switch_template_pack()
1948
+	{
1949
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
+
1952
+		// verify we have needed values.
1953
+		if (empty($GRP_ID) || empty($template_pack)) {
1954
+			$this->_template_args['error'] = true;
1955
+			EE_Error::add_error(
1956
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
+				__FILE__,
1958
+				__FUNCTION__,
1959
+				__LINE__
1960
+			);
1961
+		} else {
1962
+			// get template, set the new template_pack and then reset to default
1963
+			/** @type EE_Message_Template_Group $message_template_group */
1964
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
+
1966
+			$message_template_group->set_template_pack_name($template_pack);
1967
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1968
+			$this->_req_data['mt'] = $message_template_group->message_type();
1969
+
1970
+			$query_args = $this->_reset_to_default_template();
1971
+
1972
+			if (empty($query_args['id'])) {
1973
+				EE_Error::add_error(
1974
+					esc_html__(
1975
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
+						'event_espresso'
1977
+					),
1978
+					__FILE__,
1979
+					__FUNCTION__,
1980
+					__LINE__
1981
+				);
1982
+				$this->_template_args['error'] = true;
1983
+			} else {
1984
+				$template_label = $message_template_group->get_template_pack()->label;
1985
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
+				EE_Error::add_success(
1987
+					sprintf(
1988
+						esc_html__(
1989
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
+							'event_espresso'
1991
+						),
1992
+						$template_label,
1993
+						$template_pack_labels->template_pack
1994
+					)
1995
+				);
1996
+				// generate the redirect url for js.
1997
+				$url = self::add_query_args_and_nonce(
1998
+					$query_args,
1999
+					$this->_admin_base_url
2000
+				);
2001
+				$this->_template_args['data']['redirect_url'] = $url;
2002
+				$this->_template_args['success'] = true;
2003
+			}
2004
+
2005
+			$this->_return_json();
2006
+		}
2007
+	}
2008
+
2009
+
2010
+	/**
2011
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
+	 * they want.
2013
+	 *
2014
+	 * @access protected
2015
+	 * @return array|null
2016
+	 * @throws EE_Error
2017
+	 * @throws InvalidArgumentException
2018
+	 * @throws InvalidDataTypeException
2019
+	 * @throws InvalidInterfaceException
2020
+	 */
2021
+	protected function _reset_to_default_template()
2022
+	{
2023
+
2024
+		$templates = array();
2025
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
+		// we need to make sure we've got the info we need.
2027
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
+			EE_Error::add_error(
2029
+				esc_html__(
2030
+					'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.',
2031
+					'event_espresso'
2032
+				),
2033
+				__FILE__,
2034
+				__FUNCTION__,
2035
+				__LINE__
2036
+			);
2037
+		}
2038
+
2039
+		// all templates will be reset to whatever the defaults are
2040
+		// for the global template matching the messenger and message type.
2041
+		$success = ! empty($GRP_ID) ? true : false;
2042
+
2043
+		if ($success) {
2044
+			// let's first determine if the incoming template is a global template,
2045
+			// if it isn't then we need to get the global template matching messenger and message type.
2046
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
+
2048
+
2049
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
+
2052
+			if ($success) {
2053
+				// if successfully deleted, lets generate the new ones.
2054
+				// Note. We set GLOBAL to true, because resets on ANY template
2055
+				// will use the related global template defaults for regeneration.
2056
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2057
+				// HOWEVER, we DO keep the template pack and template variation set
2058
+				// for the current custom template when resetting.
2059
+				$templates = $this->_generate_new_templates(
2060
+					$this->_req_data['msgr'],
2061
+					$this->_req_data['mt'],
2062
+					$GRP_ID,
2063
+					true
2064
+				);
2065
+			}
2066
+		}
2067
+
2068
+		// any error messages?
2069
+		if (! $success) {
2070
+			EE_Error::add_error(
2071
+				esc_html__(
2072
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2073
+					'event_espresso'
2074
+				),
2075
+				__FILE__,
2076
+				__FUNCTION__,
2077
+				__LINE__
2078
+			);
2079
+		}
2080
+
2081
+		// all good, let's add a success message!
2082
+		if ($success && ! empty($templates)) {
2083
+			// the info for the template we generated is the first element in the returned array
2084
+			// $templates = $templates[0];
2085
+			EE_Error::overwrite_success();
2086
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
+		}
2088
+
2089
+
2090
+		$query_args = array(
2091
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
+		);
2095
+
2096
+		// if called via ajax then we return query args otherwise redirect
2097
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2098
+			return $query_args;
2099
+		} else {
2100
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2101
+
2102
+			return null;
2103
+		}
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Retrieve and set the message preview for display.
2109
+	 *
2110
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
+	 * @return string
2112
+	 * @throws ReflectionException
2113
+	 * @throws EE_Error
2114
+	 * @throws InvalidArgumentException
2115
+	 * @throws InvalidDataTypeException
2116
+	 * @throws InvalidInterfaceException
2117
+	 */
2118
+	public function _preview_message($send = false)
2119
+	{
2120
+		// first make sure we've got the necessary parameters
2121
+		if (! isset(
2122
+			$this->_req_data['message_type'],
2123
+			$this->_req_data['messenger'],
2124
+			$this->_req_data['messenger'],
2125
+			$this->_req_data['GRP_ID']
2126
+		)) {
2127
+			EE_Error::add_error(
2128
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+
2135
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
+
2137
+
2138
+		// get the preview!
2139
+		$preview = EED_Messages::preview_message(
2140
+			$this->_req_data['message_type'],
2141
+			$this->_req_data['context'],
2142
+			$this->_req_data['messenger'],
2143
+			$send
2144
+		);
2145
+
2146
+		if ($send) {
2147
+			return $preview;
2148
+		}
2149
+
2150
+		// let's add a button to go back to the edit view
2151
+		$query_args = array(
2152
+			'id'      => $this->_req_data['GRP_ID'],
2153
+			'context' => $this->_req_data['context'],
2154
+			'action'  => 'edit_message_template',
2155
+		);
2156
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
+		$preview_button = '<a href="'
2158
+						  . $go_back_url
2159
+						  . '" class="button-secondary messages-preview-go-back-button">'
2160
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2161
+						  . '</a>';
2162
+		$message_types = $this->get_installed_message_types();
2163
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
+			$this->_req_data['messenger']
2165
+		);
2166
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2167
+			? ucwords($active_messenger->label['singular'])
2168
+			: esc_html__('Unknown Messenger', 'event_espresso');
2169
+		// let's provide a helpful title for context
2170
+		$preview_title = sprintf(
2171
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
+			$active_messenger_label,
2173
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
+		);
2175
+		// setup display of preview.
2176
+		$this->_admin_page_title = $preview_title;
2177
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2178
+		$this->_template_args['data']['force_json'] = true;
2179
+
2180
+		return '';
2181
+	}
2182
+
2183
+
2184
+	/**
2185
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2186
+	 * gets called automatically.
2187
+	 *
2188
+	 * @since 4.5.0
2189
+	 *
2190
+	 * @return string
2191
+	 */
2192
+	protected function _display_preview_message()
2193
+	{
2194
+		$this->display_admin_page_with_no_sidebar();
2195
+	}
2196
+
2197
+
2198
+	/**
2199
+	 * registers metaboxes that should show up on the "edit_message_template" page
2200
+	 *
2201
+	 * @access protected
2202
+	 * @return void
2203
+	 */
2204
+	protected function _register_edit_meta_boxes()
2205
+	{
2206
+		add_meta_box(
2207
+			'mtp_valid_shortcodes',
2208
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2209
+			array($this, 'shortcode_meta_box'),
2210
+			$this->_current_screen->id,
2211
+			'side',
2212
+			'default'
2213
+		);
2214
+		add_meta_box(
2215
+			'mtp_extra_actions',
2216
+			esc_html__('Extra Actions', 'event_espresso'),
2217
+			array($this, 'extra_actions_meta_box'),
2218
+			$this->_current_screen->id,
2219
+			'side',
2220
+			'high'
2221
+		);
2222
+		add_meta_box(
2223
+			'mtp_templates',
2224
+			esc_html__('Template Styles', 'event_espresso'),
2225
+			array($this, 'template_pack_meta_box'),
2226
+			$this->_current_screen->id,
2227
+			'side',
2228
+			'high'
2229
+		);
2230
+	}
2231
+
2232
+
2233
+	/**
2234
+	 * metabox content for all template pack and variation selection.
2235
+	 *
2236
+	 * @since 4.5.0
2237
+	 * @return string
2238
+	 * @throws DomainException
2239
+	 * @throws EE_Error
2240
+	 * @throws InvalidArgumentException
2241
+	 * @throws ReflectionException
2242
+	 * @throws InvalidDataTypeException
2243
+	 * @throws InvalidInterfaceException
2244
+	 */
2245
+	public function template_pack_meta_box()
2246
+	{
2247
+		$this->_set_message_template_group();
2248
+
2249
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2250
+
2251
+		$tp_select_values = array();
2252
+
2253
+		foreach ($tp_collection as $tp) {
2254
+			// only include template packs that support this messenger and message type!
2255
+			$supports = $tp->get_supports();
2256
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2257
+				|| ! in_array(
2258
+					$this->_message_template_group->message_type(),
2259
+					$supports[ $this->_message_template_group->messenger() ],
2260
+					true
2261
+				)
2262
+			) {
2263
+				// not supported
2264
+				continue;
2265
+			}
2266
+
2267
+			$tp_select_values[] = array(
2268
+				'text' => $tp->label,
2269
+				'id'   => $tp->dbref,
2270
+			);
2271
+		}
2272
+
2273
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2274
+		// the default template pack.  This still allows for the odd template pack to override.
2275
+		if (empty($tp_select_values)) {
2276
+			$tp_select_values[] = array(
2277
+				'text' => esc_html__('Default', 'event_espresso'),
2278
+				'id'   => 'default',
2279
+			);
2280
+		}
2281
+
2282
+		// setup variation select values for the currently selected template.
2283
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2284
+			$this->_message_template_group->messenger(),
2285
+			$this->_message_template_group->message_type()
2286
+		);
2287
+		$variations_select_values = array();
2288
+		foreach ($variations as $variation => $label) {
2289
+			$variations_select_values[] = array(
2290
+				'text' => $label,
2291
+				'id'   => $variation,
2292
+			);
2293
+		}
2294
+
2295
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2296
+
2297
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2298
+			'MTP_template_pack',
2299
+			$tp_select_values,
2300
+			$this->_message_template_group->get_template_pack_name()
2301
+		);
2302
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2303
+			'MTP_template_variation',
2304
+			$variations_select_values,
2305
+			$this->_message_template_group->get_template_pack_variation()
2306
+		);
2307
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2308
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2309
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2310
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2311
+
2312
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2313
+
2314
+		EEH_Template::display_template($template, $template_args);
2315
+	}
2316
+
2317
+
2318
+	/**
2319
+	 * This meta box holds any extra actions related to Message Templates
2320
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2321
+	 *
2322
+	 * @access  public
2323
+	 * @return void
2324
+	 * @throws EE_Error
2325
+	 */
2326
+	public function extra_actions_meta_box()
2327
+	{
2328
+		$template_form_fields = array();
2329
+
2330
+		$extra_args = array(
2331
+			'msgr'   => $this->_message_template_group->messenger(),
2332
+			'mt'     => $this->_message_template_group->message_type(),
2333
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2334
+		);
2335
+		// first we need to see if there are any fields
2336
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2337
+
2338
+		if (! empty($fields)) {
2339
+			// yup there be fields
2340
+			foreach ($fields as $field => $config) {
2341
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2342
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2343
+				$default = isset($config['default']) ? $config['default'] : '';
2344
+				$default = isset($config['value']) ? $config['value'] : $default;
2345
+
2346
+				// if type is hidden and the value is empty
2347
+				// something may have gone wrong so let's correct with the defaults
2348
+				$fix = $config['input'] === 'hidden'
2349
+					   && isset($existing[ $field ])
2350
+					   && empty($existing[ $field ])
2351
+					? $default
2352
+					: '';
2353
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2354
+					? $existing[ $field ]
2355
+					: $fix;
2356
+
2357
+				$template_form_fields[ $field_id ] = array(
2358
+					'name'       => 'test_settings_fld[' . $field . ']',
2359
+					'label'      => $config['label'],
2360
+					'input'      => $config['input'],
2361
+					'type'       => $config['type'],
2362
+					'required'   => $config['required'],
2363
+					'validation' => $config['validation'],
2364
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2365
+					'css_class'  => $config['css_class'],
2366
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2367
+					'default'    => $default,
2368
+					'format'     => $config['format'],
2369
+				);
2370
+			}
2371
+		}
2372
+
2373
+		$test_settings_fields = ! empty($template_form_fields)
2374
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2375
+			: '';
2376
+
2377
+		$test_settings_html = '';
2378
+		// print out $test_settings_fields
2379
+		if (! empty($test_settings_fields)) {
2380
+			echo $test_settings_fields;
2381
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2382
+			$test_settings_html .= 'name="test_button" value="';
2383
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2384
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2385
+		}
2386
+
2387
+		// and button
2388
+		$test_settings_html .= '<p>'
2389
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2390
+							   . '</p>';
2391
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2392
+		$test_settings_html .= $this->get_action_link_or_button(
2393
+			'reset_to_default',
2394
+			'reset',
2395
+			$extra_args,
2396
+			'button-primary reset-default-button'
2397
+		);
2398
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2399
+		echo $test_settings_html;
2400
+	}
2401
+
2402
+
2403
+	/**
2404
+	 * This returns the shortcode selector skeleton for a given context and field.
2405
+	 *
2406
+	 * @since 4.9.rc.000
2407
+	 * @param string $field           The name of the field retrieving shortcodes for.
2408
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2409
+	 * @return string
2410
+	 * @throws DomainException
2411
+	 * @throws EE_Error
2412
+	 * @throws InvalidArgumentException
2413
+	 * @throws ReflectionException
2414
+	 * @throws InvalidDataTypeException
2415
+	 * @throws InvalidInterfaceException
2416
+	 */
2417
+	protected function _get_shortcode_selector($field, $linked_input_id)
2418
+	{
2419
+		$template_args = array(
2420
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2421
+			'fieldname'       => $field,
2422
+			'linked_input_id' => $linked_input_id,
2423
+		);
2424
+
2425
+		return EEH_Template::display_template(
2426
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2427
+			$template_args,
2428
+			true
2429
+		);
2430
+	}
2431
+
2432
+
2433
+	/**
2434
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2435
+	 * page)
2436
+	 *
2437
+	 * @access public
2438
+	 * @return void
2439
+	 * @throws EE_Error
2440
+	 * @throws InvalidArgumentException
2441
+	 * @throws ReflectionException
2442
+	 * @throws InvalidDataTypeException
2443
+	 * @throws InvalidInterfaceException
2444
+	 */
2445
+	public function shortcode_meta_box()
2446
+	{
2447
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2448
+		// $messenger = $this->_message_template_group->messenger_obj();
2449
+		// now let's set the content depending on the status of the shortcodes array
2450
+		if (empty($shortcodes)) {
2451
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2452
+			echo $content;
2453
+		} else {
2454
+			// $alt = 0;
2455
+			?>
2456 2456
             <div style="float:right; margin-top:10px"><?php
2457
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2458
-                            ?></div>
2457
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2458
+							?></div>
2459 2459
             <p class="small-text"><?php
2460
-                                  printf(
2461
-                                      esc_html__(
2462
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2463
-                                          'event_espresso'
2464
-                                      ),
2465
-                                      '<span class="dashicons dashicons-menu"></span>'
2466
-                                  );
2467
-                                ?>
2460
+								  printf(
2461
+									  esc_html__(
2462
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2463
+										  'event_espresso'
2464
+									  ),
2465
+									  '<span class="dashicons dashicons-menu"></span>'
2466
+								  );
2467
+								?>
2468 2468
             </p>
2469 2469
             <?php
2470
-        }
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * used to set the $_shortcodes property for when its needed elsewhere.
2476
-     *
2477
-     * @access protected
2478
-     * @return void
2479
-     * @throws EE_Error
2480
-     * @throws InvalidArgumentException
2481
-     * @throws ReflectionException
2482
-     * @throws InvalidDataTypeException
2483
-     * @throws InvalidInterfaceException
2484
-     */
2485
-    protected function _set_shortcodes()
2486
-    {
2487
-
2488
-        // no need to run this if the property is already set
2489
-        if (! empty($this->_shortcodes)) {
2490
-            return;
2491
-        }
2492
-
2493
-        $this->_shortcodes = $this->_get_shortcodes();
2494
-    }
2495
-
2496
-
2497
-    /**
2498
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2499
-     * property)
2500
-     *
2501
-     * @access  protected
2502
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2503
-     *                         for. Defaults to all (for the given context)
2504
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2505
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2506
-     *                         true just an array of shortcode/label pairs.
2507
-     * @throws EE_Error
2508
-     * @throws InvalidArgumentException
2509
-     * @throws ReflectionException
2510
-     * @throws InvalidDataTypeException
2511
-     * @throws InvalidInterfaceException
2512
-     */
2513
-    protected function _get_shortcodes($fields = array(), $merged = true)
2514
-    {
2515
-        $this->_set_message_template_group();
2516
-
2517
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2518
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2519
-            ? absint($this->_req_data['id'])
2520
-            : false;
2521
-        $context = isset($this->_req_data['context'])
2522
-            ? $this->_req_data['context']
2523
-            : key($this->_message_template_group->contexts_config());
2524
-
2525
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2526
-    }
2527
-
2528
-
2529
-    /**
2530
-     * This sets the _message_template property (containing the called message_template object)
2531
-     *
2532
-     * @access protected
2533
-     * @return void
2534
-     * @throws EE_Error
2535
-     * @throws InvalidArgumentException
2536
-     * @throws ReflectionException
2537
-     * @throws InvalidDataTypeException
2538
-     * @throws InvalidInterfaceException
2539
-     */
2540
-    protected function _set_message_template_group()
2541
-    {
2542
-
2543
-        if (! empty($this->_message_template_group)) {
2544
-            return;
2545
-        } //get out if this is already set.
2546
-
2547
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2548
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2549
-
2550
-        // let's get the message templates
2551
-        $MTP = EEM_Message_Template_Group::instance();
2552
-
2553
-        if (empty($GRP_ID)) {
2554
-            $this->_message_template_group = $MTP->create_default_object();
2555
-        } else {
2556
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2557
-        }
2558
-
2559
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2560
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2561
-    }
2562
-
2563
-
2564
-    /**
2565
-     * sets up a context switcher for edit forms
2566
-     *
2567
-     * @access  protected
2568
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2569
-     * @param array                      $args                  various things the context switcher needs.
2570
-     * @throws EE_Error
2571
-     */
2572
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2573
-    {
2574
-        $context_details = $template_group_object->contexts_config();
2575
-        $context_label = $template_group_object->context_label();
2576
-        ob_start();
2577
-        ?>
2470
+		}
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2476
+	 *
2477
+	 * @access protected
2478
+	 * @return void
2479
+	 * @throws EE_Error
2480
+	 * @throws InvalidArgumentException
2481
+	 * @throws ReflectionException
2482
+	 * @throws InvalidDataTypeException
2483
+	 * @throws InvalidInterfaceException
2484
+	 */
2485
+	protected function _set_shortcodes()
2486
+	{
2487
+
2488
+		// no need to run this if the property is already set
2489
+		if (! empty($this->_shortcodes)) {
2490
+			return;
2491
+		}
2492
+
2493
+		$this->_shortcodes = $this->_get_shortcodes();
2494
+	}
2495
+
2496
+
2497
+	/**
2498
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2499
+	 * property)
2500
+	 *
2501
+	 * @access  protected
2502
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2503
+	 *                         for. Defaults to all (for the given context)
2504
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2505
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2506
+	 *                         true just an array of shortcode/label pairs.
2507
+	 * @throws EE_Error
2508
+	 * @throws InvalidArgumentException
2509
+	 * @throws ReflectionException
2510
+	 * @throws InvalidDataTypeException
2511
+	 * @throws InvalidInterfaceException
2512
+	 */
2513
+	protected function _get_shortcodes($fields = array(), $merged = true)
2514
+	{
2515
+		$this->_set_message_template_group();
2516
+
2517
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2518
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2519
+			? absint($this->_req_data['id'])
2520
+			: false;
2521
+		$context = isset($this->_req_data['context'])
2522
+			? $this->_req_data['context']
2523
+			: key($this->_message_template_group->contexts_config());
2524
+
2525
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2526
+	}
2527
+
2528
+
2529
+	/**
2530
+	 * This sets the _message_template property (containing the called message_template object)
2531
+	 *
2532
+	 * @access protected
2533
+	 * @return void
2534
+	 * @throws EE_Error
2535
+	 * @throws InvalidArgumentException
2536
+	 * @throws ReflectionException
2537
+	 * @throws InvalidDataTypeException
2538
+	 * @throws InvalidInterfaceException
2539
+	 */
2540
+	protected function _set_message_template_group()
2541
+	{
2542
+
2543
+		if (! empty($this->_message_template_group)) {
2544
+			return;
2545
+		} //get out if this is already set.
2546
+
2547
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2548
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2549
+
2550
+		// let's get the message templates
2551
+		$MTP = EEM_Message_Template_Group::instance();
2552
+
2553
+		if (empty($GRP_ID)) {
2554
+			$this->_message_template_group = $MTP->create_default_object();
2555
+		} else {
2556
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2557
+		}
2558
+
2559
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2560
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2561
+	}
2562
+
2563
+
2564
+	/**
2565
+	 * sets up a context switcher for edit forms
2566
+	 *
2567
+	 * @access  protected
2568
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2569
+	 * @param array                      $args                  various things the context switcher needs.
2570
+	 * @throws EE_Error
2571
+	 */
2572
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2573
+	{
2574
+		$context_details = $template_group_object->contexts_config();
2575
+		$context_label = $template_group_object->context_label();
2576
+		ob_start();
2577
+		?>
2578 2578
         <div class="ee-msg-switcher-container">
2579 2579
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2580 2580
                 <?php
2581
-                foreach ($args as $name => $value) {
2582
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2583
-                        continue;
2584
-                    }
2585
-                    ?>
2581
+				foreach ($args as $name => $value) {
2582
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2583
+						continue;
2584
+					}
2585
+					?>
2586 2586
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2587 2587
                     <?php
2588
-                }
2589
-                // setup nonce_url
2590
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2591
-                ?>
2588
+				}
2589
+				// setup nonce_url
2590
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2591
+				?>
2592 2592
                 <select name="context">
2593 2593
                     <?php
2594
-                    $context_templates = $template_group_object->context_templates();
2595
-                    if (is_array($context_templates)) :
2596
-                        foreach ($context_templates as $context => $template_fields) :
2597
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2598
-                            ?>
2594
+					$context_templates = $template_group_object->context_templates();
2595
+					if (is_array($context_templates)) :
2596
+						foreach ($context_templates as $context => $template_fields) :
2597
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2598
+							?>
2599 2599
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2600 2600
                                 <?php echo $context_details[ $context ]['label']; ?>
2601 2601
                             </option>
2602 2602
                         <?php endforeach;
2603
-                    endif; ?>
2603
+					endif; ?>
2604 2604
                 </select>
2605 2605
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2606 2606
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2609,1921 +2609,1921 @@  discard block
 block discarded – undo
2609 2609
             <?php echo $args['extra']; ?>
2610 2610
         </div> <!-- end .ee-msg-switcher-container -->
2611 2611
         <?php
2612
-        $output = ob_get_contents();
2613
-        ob_clean();
2614
-        $this->_context_switcher = $output;
2615
-    }
2616
-
2617
-
2618
-    /**
2619
-     * utility for sanitizing new values coming in.
2620
-     * Note: this is only used when updating a context.
2621
-     *
2622
-     * @access protected
2623
-     *
2624
-     * @param int $index This helps us know which template field to select from the request array.
2625
-     *
2626
-     * @return array
2627
-     */
2628
-    protected function _set_message_template_column_values($index)
2629
-    {
2630
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2631
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2632
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2633
-            }
2634
-        }
2635
-
2636
-
2637
-        $set_column_values = array(
2638
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2639
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2640
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2641
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2642
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2643
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2644
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2645
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2646
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2647
-                ? absint($this->_req_data['MTP_is_global'])
2648
-                : 0,
2649
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2650
-                ? absint($this->_req_data['MTP_is_override'])
2651
-                : 0,
2652
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2653
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2654
-        );
2655
-
2656
-
2657
-        return $set_column_values;
2658
-    }
2659
-
2660
-
2661
-    protected function _insert_or_update_message_template($new = false)
2662
-    {
2663
-
2664
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2665
-        $success = 0;
2666
-        $override = false;
2667
-
2668
-        // setup notices description
2669
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2670
-
2671
-        // need the message type and messenger objects to be able to use the labels for the notices
2672
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2673
-        $messenger_label = $messenger_object instanceof EE_messenger
2674
-            ? ucwords($messenger_object->label['singular'])
2675
-            : '';
2676
-
2677
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2678
-            ? $this->_req_data['MTP_message_type']
2679
-            : '';
2680
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2681
-
2682
-        $message_type_label = $message_type_object instanceof EE_message_type
2683
-            ? ucwords($message_type_object->label['singular'])
2684
-            : '';
2685
-
2686
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2687
-            ? $this->_req_data['MTP_context']
2688
-            : '';
2689
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2690
-
2691
-        $item_desc = $messenger_label && $message_type_label
2692
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2693
-            : '';
2694
-        $item_desc .= 'Message Template';
2695
-        $query_args = array();
2696
-        $edit_array = array();
2697
-        $action_desc = '';
2698
-
2699
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2700
-        // user to edit.
2701
-        if ($new) {
2702
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2703
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2704
-                if (empty($edit_array)) {
2705
-                    $success = 0;
2706
-                } else {
2707
-                    $success = 1;
2708
-                    $edit_array = $edit_array[0];
2709
-                    $query_args = array(
2710
-                        'id'      => $edit_array['GRP_ID'],
2711
-                        'context' => $edit_array['MTP_context'],
2712
-                        'action'  => 'edit_message_template',
2713
-                    );
2714
-                }
2715
-            }
2716
-            $action_desc = 'created';
2717
-        } else {
2718
-            $MTPG = EEM_Message_Template_Group::instance();
2719
-            $MTP = EEM_Message_Template::instance();
2720
-
2721
-
2722
-            // run update for each template field in displayed context
2723
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2724
-                EE_Error::add_error(
2725
-                    esc_html__(
2726
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2727
-                        'event_espresso'
2728
-                    ),
2729
-                    __FILE__,
2730
-                    __FUNCTION__,
2731
-                    __LINE__
2732
-                );
2733
-                $success = 0;
2734
-            } else {
2735
-                // first validate all fields!
2736
-                // this filter allows client code to add its own validation to the template fields as well.
2737
-                // returning an empty array means everything passed validation.
2738
-                // errors in validation should be represented in an array with the following shape:
2739
-                // array(
2740
-                //   'fieldname' => array(
2741
-                //          'msg' => 'error message'
2742
-                //          'value' => 'value for field producing error'
2743
-                // )
2744
-                $custom_validation = (array) apply_filters(
2745
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2746
-                    array(),
2747
-                    $this->_req_data['MTP_template_fields'],
2748
-                    $context_slug,
2749
-                    $messenger_slug,
2750
-                    $message_type_slug
2751
-                );
2752
-
2753
-                $system_validation = $MTPG->validate(
2754
-                    $this->_req_data['MTP_template_fields'],
2755
-                    $context_slug,
2756
-                    $messenger_slug,
2757
-                    $message_type_slug
2758
-                );
2759
-
2760
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2761
-                    : $system_validation;
2762
-                $validates = array_merge($custom_validation, $system_validation);
2763
-
2764
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2765
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2766
-                //  WE need to make sure there is no actual error messages in validates.
2767
-                if (is_array($validates) && ! empty($validates)) {
2768
-                    // add the transient so when the form loads we know which fields to highlight
2769
-                    $this->_add_transient('edit_message_template', $validates);
2770
-
2771
-                    $success = 0;
2772
-
2773
-                    // setup notices
2774
-                    foreach ($validates as $field => $error) {
2775
-                        if (isset($error['msg'])) {
2776
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2777
-                        }
2778
-                    }
2779
-                } else {
2780
-                    $set_column_values = array();
2781
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2782
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2783
-
2784
-                        $where_cols_n_values = array(
2785
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2786
-                        );
2787
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2788
-                        if (! current_user_can('unfiltered_html')) {
2789
-                            if (is_array($set_column_values['MTP_content'])) {
2790
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2791
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2792
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2793
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2794
-                                    // runs we need to re-slash the data. Sheesh. See
2795
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2796
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2797
-                                        wp_kses(
2798
-                                            stripslashes($value),
2799
-                                            wp_kses_allowed_html('post')
2800
-                                        )
2801
-                                    );
2802
-                                }
2803
-                            } else {
2804
-                                $set_column_values['MTP_content'] = wp_kses(
2805
-                                    $set_column_values['MTP_content'],
2806
-                                    wp_kses_allowed_html('post')
2807
-                                );
2808
-                            }
2809
-                        }
2810
-                        $message_template_fields = array(
2811
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2812
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2813
-                            'MTP_context'        => $set_column_values['MTP_context'],
2814
-                            'MTP_content'        => $set_column_values['MTP_content'],
2815
-                        );
2816
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2817
-                            if ($updated === false) {
2818
-                                EE_Error::add_error(
2819
-                                    sprintf(
2820
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2821
-                                        $template_field
2822
-                                    ),
2823
-                                    __FILE__,
2824
-                                    __FUNCTION__,
2825
-                                    __LINE__
2826
-                                );
2827
-                            } else {
2828
-                                $success = 1;
2829
-                            }
2830
-                        } else {
2831
-                            // only do this logic if we don't have a MTP_ID for this field
2832
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2833
-                                // this has already been through the template field validator and sanitized, so it will be
2834
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2835
-                                // message template field in a messenger/message type and existing users don't have the
2836
-                                // default setup for it.
2837
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2838
-                                $updated = $MTP->insert($message_template_fields);
2839
-                                if (! $updated || is_wp_error($updated)) {
2840
-                                    EE_Error::add_error(
2841
-                                        sprintf(
2842
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2843
-                                            $template_field
2844
-                                        ),
2845
-                                        __FILE__,
2846
-                                        __FUNCTION__,
2847
-                                        __LINE__
2848
-                                    );
2849
-                                    $success = 0;
2850
-                                } else {
2851
-                                    $success = 1;
2852
-                                }
2853
-                            }
2854
-                        }
2855
-                        $action_desc = 'updated';
2856
-                    }
2857
-
2858
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2859
-                    $mtpg_fields = array(
2860
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2861
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2862
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2863
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2864
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2865
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2866
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2867
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2868
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2869
-                            : '',
2870
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2871
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2872
-                            : '',
2873
-                    );
2874
-
2875
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2876
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2877
-
2878
-                    if ($updated === false) {
2879
-                        EE_Error::add_error(
2880
-                            sprintf(
2881
-                                esc_html__(
2882
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2883
-                                    'event_espresso'
2884
-                                ),
2885
-                                $set_column_values['GRP_ID']
2886
-                            ),
2887
-                            __FILE__,
2888
-                            __FUNCTION__,
2889
-                            __LINE__
2890
-                        );
2891
-                    } else {
2892
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2893
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2894
-                            ? $this->_req_data['MTP_template_pack']
2895
-                            : 'default';
2896
-
2897
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2898
-                            ? $this->_req_data['MTP_template_variation']
2899
-                            : 'default';
2900
-
2901
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2902
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2903
-                            $mtpg_obj->set_template_pack_name($template_pack);
2904
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2905
-                        }
2906
-                        $success = 1;
2907
-                    }
2908
-                }
2909
-            }
2910
-        }
2911
-
2912
-        // we return things differently if doing ajax
2913
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2914
-            $this->_template_args['success'] = $success;
2915
-            $this->_template_args['error'] = ! $success ? true : false;
2916
-            $this->_template_args['content'] = '';
2917
-            $this->_template_args['data'] = array(
2918
-                'grpID'        => $edit_array['GRP_ID'],
2919
-                'templateName' => $edit_array['template_name'],
2920
-            );
2921
-            if ($success) {
2922
-                EE_Error::overwrite_success();
2923
-                EE_Error::add_success(
2924
-                    esc_html__(
2925
-                        '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.',
2926
-                        'event_espresso'
2927
-                    )
2928
-                );
2929
-            }
2930
-
2931
-            $this->_return_json();
2932
-        }
2933
-
2934
-
2935
-        // was a test send triggered?
2936
-        if (isset($this->_req_data['test_button'])) {
2937
-            EE_Error::overwrite_success();
2938
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2939
-            $override = true;
2940
-        }
2941
-
2942
-        if (empty($query_args)) {
2943
-            $query_args = array(
2944
-                'id'      => $this->_req_data['GRP_ID'],
2945
-                'context' => $context_slug,
2946
-                'action'  => 'edit_message_template',
2947
-            );
2948
-        }
2949
-
2950
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2951
-    }
2952
-
2953
-
2954
-    /**
2955
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2956
-     *
2957
-     * @param  string $context      what context being tested
2958
-     * @param  string $messenger    messenger being tested
2959
-     * @param  string $message_type message type being tested
2960
-     * @throws EE_Error
2961
-     * @throws InvalidArgumentException
2962
-     * @throws InvalidDataTypeException
2963
-     * @throws InvalidInterfaceException
2964
-     */
2965
-    protected function _do_test_send($context, $messenger, $message_type)
2966
-    {
2967
-        // set things up for preview
2968
-        $this->_req_data['messenger'] = $messenger;
2969
-        $this->_req_data['message_type'] = $message_type;
2970
-        $this->_req_data['context'] = $context;
2971
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2972
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
2973
-
2974
-        // let's save any existing fields that might be required by the messenger
2975
-        if (isset($this->_req_data['test_settings_fld'])
2976
-            && $active_messenger instanceof EE_messenger
2977
-            && apply_filters(
2978
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2979
-                true,
2980
-                $this->_req_data['test_settings_fld'],
2981
-                $active_messenger
2982
-            )
2983
-        ) {
2984
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2985
-        }
2986
-
2987
-        /**
2988
-         * Use filter to add additional controls on whether message can send or not
2989
-         */
2990
-        if (apply_filters(
2991
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
2992
-            true,
2993
-            $context,
2994
-            $this->_req_data,
2995
-            $messenger,
2996
-            $message_type
2997
-        )) {
2998
-            $success = $this->_preview_message(true);
2999
-            if ($success) {
3000
-                EE_Error::add_success(__('Test message sent', 'event_espresso'));
3001
-            } else {
3002
-                EE_Error::add_error(
3003
-                    esc_html__('The test message was not sent', 'event_espresso'),
3004
-                    __FILE__,
3005
-                    __FUNCTION__,
3006
-                    __LINE__
3007
-                );
3008
-            }
3009
-        }
3010
-    }
3011
-
3012
-
3013
-    /**
3014
-     * _generate_new_templates
3015
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3016
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3017
-     * for the event.
3018
-     *
3019
-     *
3020
-     * @param  string $messenger     the messenger we are generating templates for
3021
-     * @param array   $message_types array of message types that the templates are generated for.
3022
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3023
-     *                               indicate the message_template_group being used as the base.
3024
-     *
3025
-     * @param bool    $global
3026
-     *
3027
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3028
-     *                               encountering problems.
3029
-     * @throws EE_Error
3030
-     */
3031
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3032
-    {
3033
-
3034
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3035
-        // just don't generate any templates.
3036
-        if (empty($message_types)) {
3037
-            return true;
3038
-        }
3039
-
3040
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3041
-    }
3042
-
3043
-
3044
-    /**
3045
-     * [_trash_or_restore_message_template]
3046
-     *
3047
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3048
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3049
-     *                        an individual context (FALSE).
3050
-     * @return void
3051
-     * @throws EE_Error
3052
-     * @throws InvalidArgumentException
3053
-     * @throws InvalidDataTypeException
3054
-     * @throws InvalidInterfaceException
3055
-     */
3056
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3057
-    {
3058
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3059
-        $MTP = EEM_Message_Template_Group::instance();
3060
-
3061
-        $success = 1;
3062
-
3063
-        // incoming GRP_IDs
3064
-        if ($all) {
3065
-            // Checkboxes
3066
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3067
-                // if array has more than one element then success message should be plural.
3068
-                // todo: what about nonce?
3069
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3070
-
3071
-                // cycle through checkboxes
3072
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3074
-                    if (! $trashed_or_restored) {
3075
-                        $success = 0;
3076
-                    }
3077
-                }
3078
-            } else {
3079
-                // grab single GRP_ID and handle
3080
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3081
-                if (! empty($GRP_ID)) {
3082
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3083
-                    if (! $trashed_or_restored) {
3084
-                        $success = 0;
3085
-                    }
3086
-                } else {
3087
-                    $success = 0;
3088
-                }
3089
-            }
3090
-        }
3091
-
3092
-        $action_desc = $trash
3093
-            ? esc_html__('moved to the trash', 'event_espresso')
3094
-            : esc_html__('restored', 'event_espresso');
3095
-
3096
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3097
-
3098
-        $item_desc = $all ? _n(
3099
-            'Message Template Group',
3100
-            'Message Template Groups',
3101
-            $success,
3102
-            'event_espresso'
3103
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3104
-
3105
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3106
-            'template',
3107
-            'templates',
3108
-            $success,
3109
-            'event_espresso'
3110
-        ) : $item_desc;
3111
-
3112
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3113
-    }
3114
-
3115
-
3116
-    /**
3117
-     * [_delete_message_template]
3118
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3119
-     *
3120
-     * @return void
3121
-     * @throws EE_Error
3122
-     * @throws InvalidArgumentException
3123
-     * @throws InvalidDataTypeException
3124
-     * @throws InvalidInterfaceException
3125
-     */
3126
-    protected function _delete_message_template()
3127
-    {
3128
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3129
-
3130
-        // checkboxes
3131
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3132
-            // if array has more than one element then success message should be plural
3133
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3134
-
3135
-            // cycle through bulk action checkboxes
3136
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3137
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3138
-            }
3139
-        } else {
3140
-            // grab single grp_id and delete
3141
-            $GRP_ID = absint($this->_req_data['id']);
3142
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3143
-        }
3144
-
3145
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3146
-    }
3147
-
3148
-
3149
-    /**
3150
-     * helper for permanently deleting a mtP group and all related message_templates
3151
-     *
3152
-     * @param  int  $GRP_ID        The group being deleted
3153
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3154
-     * @return bool boolean to indicate the success of the deletes or not.
3155
-     * @throws EE_Error
3156
-     * @throws InvalidArgumentException
3157
-     * @throws InvalidDataTypeException
3158
-     * @throws InvalidInterfaceException
3159
-     */
3160
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3161
-    {
3162
-        $success = 1;
3163
-        $MTPG = EEM_Message_Template_Group::instance();
3164
-        // first let's GET this group
3165
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3166
-        // then delete permanently all the related Message Templates
3167
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3168
-
3169
-        if ($deleted === 0) {
3170
-            $success = 0;
3171
-        }
3172
-
3173
-        // now delete permanently this particular group
3174
-
3175
-        if ($include_group && ! $MTG->delete_permanently()) {
3176
-            $success = 0;
3177
-        }
3178
-
3179
-        return $success;
3180
-    }
3181
-
3182
-
3183
-    /**
3184
-     *    _learn_more_about_message_templates_link
3185
-     *
3186
-     * @access protected
3187
-     * @return string
3188
-     */
3189
-    protected function _learn_more_about_message_templates_link()
3190
-    {
3191
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3192
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3193
-               . '</a>';
3194
-    }
3195
-
3196
-
3197
-    /**
3198
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3199
-     * ajax and other routes.
3200
-     *
3201
-     * @return void
3202
-     * @throws DomainException
3203
-     */
3204
-    protected function _settings()
3205
-    {
3206
-
3207
-
3208
-        $this->_set_m_mt_settings();
3209
-
3210
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3211
-            ? $this->_req_data['selected_messenger']
3212
-            : 'email';
3213
-
3214
-        // let's setup the messenger tabs
3215
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3216
-            $this->_m_mt_settings['messenger_tabs'],
3217
-            'messenger_links',
3218
-            '|',
3219
-            $selected_messenger
3220
-        );
3221
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3222
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3223
-
3224
-        $this->display_admin_page_with_sidebar();
3225
-    }
3226
-
3227
-
3228
-    /**
3229
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3230
-     *
3231
-     * @access protected
3232
-     * @return void
3233
-     * @throws DomainException
3234
-     */
3235
-    protected function _set_m_mt_settings()
3236
-    {
3237
-        // first if this is already set then lets get out no need to regenerate data.
3238
-        if (! empty($this->_m_mt_settings)) {
3239
-            return;
3240
-        }
3241
-
3242
-        // get all installed messengers and message_types
3243
-        /** @type EE_messenger[] $messengers */
3244
-        $messengers = $this->_message_resource_manager->installed_messengers();
3245
-        /** @type EE_message_type[] $message_types */
3246
-        $message_types = $this->_message_resource_manager->installed_message_types();
3247
-
3248
-
3249
-        // assemble the array for the _tab_text_links helper
3250
-
3251
-        foreach ($messengers as $messenger) {
3252
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3253
-                'label' => ucwords($messenger->label['singular']),
3254
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3255
-                    ? 'messenger-active'
3256
-                    : '',
3257
-                'href'  => $messenger->name,
3258
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3259
-                'slug'  => $messenger->name,
3260
-                'obj'   => $messenger,
3261
-            );
3262
-
3263
-
3264
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3265
-
3266
-            foreach ($message_types as $message_type) {
3267
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3268
-                // it shouldn't show in either the inactive OR active metabox.
3269
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3270
-                    continue;
3271
-                }
3272
-
3273
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3274
-                    $messenger->name,
3275
-                    $message_type->name
3276
-                )
3277
-                    ? 'active'
3278
-                    : 'inactive';
3279
-
3280
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3281
-                    'label'    => ucwords($message_type->label['singular']),
3282
-                    'class'    => 'message-type-' . $a_or_i,
3283
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3284
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3285
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3286
-                    'title'    => $a_or_i === 'active'
3287
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3288
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3289
-                    'content'  => $a_or_i === 'active'
3290
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3291
-                        : $this->_message_type_settings_content($message_type, $messenger),
3292
-                    'slug'     => $message_type->name,
3293
-                    'active'   => $a_or_i === 'active',
3294
-                    'obj'      => $message_type,
3295
-                );
3296
-            }
3297
-        }
3298
-    }
3299
-
3300
-
3301
-    /**
3302
-     * This just prepares the content for the message type settings
3303
-     *
3304
-     * @param  EE_message_type $message_type The message type object
3305
-     * @param  EE_messenger    $messenger    The messenger object
3306
-     * @param  boolean         $active       Whether the message type is active or not
3307
-     * @return string html output for the content
3308
-     * @throws DomainException
3309
-     */
3310
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3311
-    {
3312
-        // get message type fields
3313
-        $fields = $message_type->get_admin_settings_fields();
3314
-        $settings_template_args['template_form_fields'] = '';
3315
-
3316
-        if (! empty($fields) && $active) {
3317
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3318
-            foreach ($fields as $fldname => $fldprops) {
3319
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3320
-                $template_form_field[ $field_id ] = array(
3321
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3322
-                    'label'      => $fldprops['label'],
3323
-                    'input'      => $fldprops['field_type'],
3324
-                    'type'       => $fldprops['value_type'],
3325
-                    'required'   => $fldprops['required'],
3326
-                    'validation' => $fldprops['validation'],
3327
-                    'value'      => isset($existing_settings[ $fldname ])
3328
-                        ? $existing_settings[ $fldname ]
3329
-                        : $fldprops['default'],
3330
-                    'options'    => isset($fldprops['options'])
3331
-                        ? $fldprops['options']
3332
-                        : array(),
3333
-                    'default'    => isset($existing_settings[ $fldname ])
3334
-                        ? $existing_settings[ $fldname ]
3335
-                        : $fldprops['default'],
3336
-                    'css_class'  => 'no-drag',
3337
-                    'format'     => $fldprops['format'],
3338
-                );
3339
-            }
3340
-
3341
-
3342
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3343
-                ? $this->_generate_admin_form_fields(
3344
-                    $template_form_field,
3345
-                    'string',
3346
-                    'ee_mt_activate_form'
3347
-                )
3348
-                : '';
3349
-        }
3350
-
3351
-        $settings_template_args['description'] = $message_type->description;
3352
-        // we also need some hidden fields
3353
-        $settings_template_args['hidden_fields'] = array(
3354
-            'message_type_settings[messenger]'    => array(
3355
-                'type'  => 'hidden',
3356
-                'value' => $messenger->name,
3357
-            ),
3358
-            'message_type_settings[message_type]' => array(
3359
-                'type'  => 'hidden',
3360
-                'value' => $message_type->name,
3361
-            ),
3362
-            'type'                                => array(
3363
-                'type'  => 'hidden',
3364
-                'value' => 'message_type',
3365
-            ),
3366
-        );
3367
-
3368
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3369
-            $settings_template_args['hidden_fields'],
3370
-            'array'
3371
-        );
3372
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3373
-            ? ' hidden'
3374
-            : '';
3375
-
3376
-
3377
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3378
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3379
-
3380
-        return $content;
3381
-    }
3382
-
3383
-
3384
-    /**
3385
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3386
-     *
3387
-     * @access protected
3388
-     * @return void
3389
-     * @throws DomainException
3390
-     */
3391
-    protected function _messages_settings_metaboxes()
3392
-    {
3393
-        $this->_set_m_mt_settings();
3394
-        $m_boxes = $mt_boxes = array();
3395
-        $m_template_args = $mt_template_args = array();
3396
-
3397
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3398
-            ? $this->_req_data['selected_messenger']
3399
-            : 'email';
3400
-
3401
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3402
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3403
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3404
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3405
-                // messenger meta boxes
3406
-                $active = $selected_messenger === $messenger;
3407
-                $active_mt_tabs = isset(
3408
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3409
-                )
3410
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3411
-                    : '';
3412
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3413
-                    esc_html__('%s Settings', 'event_espresso'),
3414
-                    $tab_array['label']
3415
-                );
3416
-                $m_template_args[ $messenger . '_a_box' ] = array(
3417
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3418
-                    'inactive_message_types' => isset(
3419
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3420
-                    )
3421
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3422
-                        : '',
3423
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3424
-                    'hidden'                 => $active ? '' : ' hidden',
3425
-                    'hide_on_message'        => $hide_on_message,
3426
-                    'messenger'              => $messenger,
3427
-                    'active'                 => $active,
3428
-                );
3429
-                // message type meta boxes
3430
-                // (which is really just the inactive container for each messenger
3431
-                // showing inactive message types for that messenger)
3432
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3433
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3434
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3435
-                    'inactive_message_types' => isset(
3436
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3437
-                    )
3438
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3439
-                        : '',
3440
-                    'hidden'                 => $active ? '' : ' hidden',
3441
-                    'hide_on_message'        => $hide_on_message,
3442
-                    'hide_off_message'       => $hide_off_message,
3443
-                    'messenger'              => $messenger,
3444
-                    'active'                 => $active,
3445
-                );
3446
-            }
3447
-        }
3448
-
3449
-
3450
-        // register messenger metaboxes
3451
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3452
-        foreach ($m_boxes as $box => $label) {
3453
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3454
-            $msgr = str_replace('_a_box', '', $box);
3455
-            add_meta_box(
3456
-                'espresso_' . $msgr . '_settings',
3457
-                $label,
3458
-                function ($post, $metabox) {
3459
-                    echo EEH_Template::display_template(
3460
-                        $metabox["args"]["template_path"],
3461
-                        $metabox["args"]["template_args"],
3462
-                        true
3463
-                    );
3464
-                },
3465
-                $this->_current_screen->id,
3466
-                'normal',
3467
-                'high',
3468
-                $callback_args
3469
-            );
3470
-        }
3471
-
3472
-        // register message type metaboxes
3473
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3474
-        foreach ($mt_boxes as $box => $label) {
3475
-            $callback_args = array(
3476
-                'template_path' => $mt_template_path,
3477
-                'template_args' => $mt_template_args[ $box ],
3478
-            );
3479
-            $mt = str_replace('_i_box', '', $box);
3480
-            add_meta_box(
3481
-                'espresso_' . $mt . '_inactive_mts',
3482
-                $label,
3483
-                function ($post, $metabox) {
3484
-                    echo EEH_Template::display_template(
3485
-                        $metabox["args"]["template_path"],
3486
-                        $metabox["args"]["template_args"],
3487
-                        true
3488
-                    );
3489
-                },
3490
-                $this->_current_screen->id,
3491
-                'side',
3492
-                'high',
3493
-                $callback_args
3494
-            );
3495
-        }
3496
-
3497
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3498
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3499
-        if (is_main_site()) {
3500
-            add_meta_box(
3501
-                'espresso_global_message_settings',
3502
-                esc_html__('Global Message Settings', 'event_espresso'),
3503
-                array($this, 'global_messages_settings_metabox_content'),
3504
-                $this->_current_screen->id,
3505
-                'normal',
3506
-                'low',
3507
-                array()
3508
-            );
3509
-        }
3510
-    }
3511
-
3512
-
3513
-    /**
3514
-     *  This generates the content for the global messages settings metabox.
3515
-     *
3516
-     * @return string
3517
-     * @throws EE_Error
3518
-     * @throws InvalidArgumentException
3519
-     * @throws ReflectionException
3520
-     * @throws InvalidDataTypeException
3521
-     * @throws InvalidInterfaceException
3522
-     */
3523
-    public function global_messages_settings_metabox_content()
3524
-    {
3525
-        $form = $this->_generate_global_settings_form();
3526
-        echo $form->form_open(
3527
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3528
-            'POST'
3529
-        )
3530
-             . $form->get_html()
3531
-             . $form->form_close();
3532
-    }
3533
-
3534
-
3535
-    /**
3536
-     * This generates and returns the form object for the global messages settings.
3537
-     *
3538
-     * @return EE_Form_Section_Proper
3539
-     * @throws EE_Error
3540
-     * @throws InvalidArgumentException
3541
-     * @throws ReflectionException
3542
-     * @throws InvalidDataTypeException
3543
-     * @throws InvalidInterfaceException
3544
-     */
3545
-    protected function _generate_global_settings_form()
3546
-    {
3547
-        EE_Registry::instance()->load_helper('HTML');
3548
-        /** @var EE_Network_Core_Config $network_config */
3549
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3550
-
3551
-        return new EE_Form_Section_Proper(
3552
-            array(
3553
-                'name'            => 'global_messages_settings',
3554
-                'html_id'         => 'global_messages_settings',
3555
-                'html_class'      => 'form-table',
3556
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3557
-                'subsections'     => apply_filters(
3558
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3559
-                    array(
3560
-                        'do_messages_on_same_request' => new EE_Select_Input(
3561
-                            array(
3562
-                                true  => esc_html__("On the same request", "event_espresso"),
3563
-                                false => esc_html__("On a separate request", "event_espresso"),
3564
-                            ),
3565
-                            array(
3566
-                                'default'         => $network_config->do_messages_on_same_request,
3567
-                                'html_label_text' => esc_html__(
3568
-                                    'Generate and send all messages:',
3569
-                                    'event_espresso'
3570
-                                ),
3571
-                                'html_help_text'  => esc_html__(
3572
-                                    '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.',
3573
-                                    'event_espresso'
3574
-                                ),
3575
-                            )
3576
-                        ),
3577
-                        'delete_threshold'            => new EE_Select_Input(
3578
-                            array(
3579
-                                0  => esc_html__('Forever', 'event_espresso'),
3580
-                                3  => esc_html__('3 Months', 'event_espresso'),
3581
-                                6  => esc_html__('6 Months', 'event_espresso'),
3582
-                                9  => esc_html__('9 Months', 'event_espresso'),
3583
-                                12 => esc_html__('12 Months', 'event_espresso'),
3584
-                                24 => esc_html__('24 Months', 'event_espresso'),
3585
-                                36 => esc_html__('36 Months', 'event_espresso'),
3586
-                            ),
3587
-                            array(
3588
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3589
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3590
-                                'html_help_text'  => esc_html__(
3591
-                                    'You can control how long a record of processed messages is kept via this option.',
3592
-                                    'event_espresso'
3593
-                                ),
3594
-                            )
3595
-                        ),
3596
-                        'update_settings'             => new EE_Submit_Input(
3597
-                            array(
3598
-                                'default'         => esc_html__('Update', 'event_espresso'),
3599
-                                'html_label_text' => '&nbsp',
3600
-                            )
3601
-                        ),
3602
-                    )
3603
-                ),
3604
-            )
3605
-        );
3606
-    }
3607
-
3608
-
3609
-    /**
3610
-     * This handles updating the global settings set on the admin page.
3611
-     *
3612
-     * @throws EE_Error
3613
-     * @throws InvalidDataTypeException
3614
-     * @throws InvalidInterfaceException
3615
-     * @throws InvalidArgumentException
3616
-     * @throws ReflectionException
3617
-     */
3618
-    protected function _update_global_settings()
3619
-    {
3620
-        /** @var EE_Network_Core_Config $network_config */
3621
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3622
-        $messages_config = EE_Registry::instance()->CFG->messages;
3623
-        $form = $this->_generate_global_settings_form();
3624
-        if ($form->was_submitted()) {
3625
-            $form->receive_form_submission();
3626
-            if ($form->is_valid()) {
3627
-                $valid_data = $form->valid_data();
3628
-                foreach ($valid_data as $property => $value) {
3629
-                    $setter = 'set_' . $property;
3630
-                    if (method_exists($network_config, $setter)) {
3631
-                        $network_config->{$setter}($value);
3632
-                    } elseif (property_exists($network_config, $property)
3633
-                        && $network_config->{$property} !== $value
3634
-                    ) {
3635
-                        $network_config->{$property} = $value;
3636
-                    } elseif (property_exists($messages_config, $property)
3637
-                        && $messages_config->{$property} !== $value
3638
-                    ) {
3639
-                        $messages_config->{$property} = $value;
3640
-                    }
3641
-                }
3642
-                // only update if the form submission was valid!
3643
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3644
-                EE_Registry::instance()->CFG->update_espresso_config();
3645
-                EE_Error::overwrite_success();
3646
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3647
-            }
3648
-        }
3649
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3650
-    }
3651
-
3652
-
3653
-    /**
3654
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3655
-     *
3656
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3657
-     * @return string html formatted tabs
3658
-     * @throws DomainException
3659
-     */
3660
-    protected function _get_mt_tabs($tab_array)
3661
-    {
3662
-        $tab_array = (array) $tab_array;
3663
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3664
-        $tabs = '';
3665
-
3666
-        foreach ($tab_array as $tab) {
3667
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3668
-        }
3669
-
3670
-        return $tabs;
3671
-    }
3672
-
3673
-
3674
-    /**
3675
-     * This prepares the content of the messenger meta box admin settings
3676
-     *
3677
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3678
-     * @return string html formatted content
3679
-     * @throws DomainException
3680
-     */
3681
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3682
-    {
3683
-
3684
-        $fields = $messenger->get_admin_settings_fields();
3685
-        $settings_template_args['template_form_fields'] = '';
3686
-
3687
-        // is $messenger active?
3688
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3689
-
3690
-
3691
-        if (! empty($fields)) {
3692
-            $existing_settings = $messenger->get_existing_admin_settings();
3693
-
3694
-            foreach ($fields as $fldname => $fldprops) {
3695
-                $field_id = $messenger->name . '-' . $fldname;
3696
-                $template_form_field[ $field_id ] = array(
3697
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3698
-                    'label'      => $fldprops['label'],
3699
-                    'input'      => $fldprops['field_type'],
3700
-                    'type'       => $fldprops['value_type'],
3701
-                    'required'   => $fldprops['required'],
3702
-                    'validation' => $fldprops['validation'],
3703
-                    'value'      => isset($existing_settings[ $field_id ])
3704
-                        ? $existing_settings[ $field_id ]
3705
-                        : $fldprops['default'],
3706
-                    'css_class'  => '',
3707
-                    'format'     => $fldprops['format'],
3708
-                );
3709
-            }
3710
-
3711
-
3712
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3713
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3714
-                : '';
3715
-        }
3716
-
3717
-        // we also need some hidden fields
3718
-        $settings_template_args['hidden_fields'] = array(
3719
-            'messenger_settings[messenger]' => array(
3720
-                'type'  => 'hidden',
3721
-                'value' => $messenger->name,
3722
-            ),
3723
-            'type'                          => array(
3724
-                'type'  => 'hidden',
3725
-                'value' => 'messenger',
3726
-            ),
3727
-        );
3728
-
3729
-        // make sure any active message types that are existing are included in the hidden fields
3730
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3731
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3732
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3733
-                    'type'  => 'hidden',
3734
-                    'value' => $mt,
3735
-                );
3736
-            }
3737
-        }
3738
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3739
-            $settings_template_args['hidden_fields'],
3740
-            'array'
3741
-        );
3742
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
-
3744
-        $settings_template_args['messenger'] = $messenger->name;
3745
-        $settings_template_args['description'] = $messenger->description;
3746
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3747
-
3748
-
3749
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3750
-            $messenger->name
3751
-        )
3752
-            ? $settings_template_args['show_hide_edit_form']
3753
-            : ' hidden';
3754
-
3755
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3756
-            ? ' hidden'
3757
-            : $settings_template_args['show_hide_edit_form'];
3758
-
3759
-
3760
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3761
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3762
-        $settings_template_args['on_off_status'] = $active ? true : false;
3763
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3764
-        $content = EEH_Template::display_template(
3765
-            $template,
3766
-            $settings_template_args,
3767
-            true
3768
-        );
3769
-
3770
-        return $content;
3771
-    }
3772
-
3773
-
3774
-    /**
3775
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3776
-     *
3777
-     * @throws DomainException
3778
-     * @throws EE_Error
3779
-     * @throws InvalidDataTypeException
3780
-     * @throws InvalidInterfaceException
3781
-     * @throws InvalidArgumentException
3782
-     * @throws ReflectionException
3783
-     */
3784
-    public function activate_messenger_toggle()
3785
-    {
3786
-        $success = true;
3787
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3788
-        // let's check that we have required data
3789
-        if (! isset($this->_req_data['messenger'])) {
3790
-            EE_Error::add_error(
3791
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3792
-                __FILE__,
3793
-                __FUNCTION__,
3794
-                __LINE__
3795
-            );
3796
-            $success = false;
3797
-        }
3798
-
3799
-        // do a nonce check here since we're not arriving via a normal route
3800
-        $nonce = isset($this->_req_data['activate_nonce'])
3801
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3802
-            : '';
3803
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3804
-
3805
-        $this->_verify_nonce($nonce, $nonce_ref);
3806
-
3807
-
3808
-        if (! isset($this->_req_data['status'])) {
3809
-            EE_Error::add_error(
3810
-                esc_html__(
3811
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3812
-                    'event_espresso'
3813
-                ),
3814
-                __FILE__,
3815
-                __FUNCTION__,
3816
-                __LINE__
3817
-            );
3818
-            $success = false;
3819
-        }
3820
-
3821
-        // do check to verify we have a valid status.
3822
-        $status = $this->_req_data['status'];
3823
-
3824
-        if ($status !== 'off' && $status !== 'on') {
3825
-            EE_Error::add_error(
3826
-                sprintf(
3827
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3828
-                    $this->_req_data['status']
3829
-                ),
3830
-                __FILE__,
3831
-                __FUNCTION__,
3832
-                __LINE__
3833
-            );
3834
-            $success = false;
3835
-        }
3836
-
3837
-        if ($success) {
3838
-            // made it here?  Stop dawdling then!!
3839
-            $success = $status === 'off'
3840
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3841
-                : $this->_activate_messenger($this->_req_data['messenger']);
3842
-        }
3843
-
3844
-        $this->_template_args['success'] = $success;
3845
-
3846
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3847
-        $this->_return_json();
3848
-    }
3849
-
3850
-
3851
-    /**
3852
-     * used by ajax from the messages settings page to activate|deactivate a message type
3853
-     *
3854
-     * @throws DomainException
3855
-     * @throws EE_Error
3856
-     * @throws ReflectionException
3857
-     * @throws InvalidDataTypeException
3858
-     * @throws InvalidInterfaceException
3859
-     * @throws InvalidArgumentException
3860
-     */
3861
-    public function activate_mt_toggle()
3862
-    {
3863
-        $success = true;
3864
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3865
-
3866
-        // let's make sure we have the necessary data
3867
-        if (! isset($this->_req_data['message_type'])) {
3868
-            EE_Error::add_error(
3869
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3870
-                __FILE__,
3871
-                __FUNCTION__,
3872
-                __LINE__
3873
-            );
3874
-            $success = false;
3875
-        }
3876
-
3877
-        if (! isset($this->_req_data['messenger'])) {
3878
-            EE_Error::add_error(
3879
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3880
-                __FILE__,
3881
-                __FUNCTION__,
3882
-                __LINE__
3883
-            );
3884
-            $success = false;
3885
-        }
3886
-
3887
-        if (! isset($this->_req_data['status'])) {
3888
-            EE_Error::add_error(
3889
-                esc_html__(
3890
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3891
-                    'event_espresso'
3892
-                ),
3893
-                __FILE__,
3894
-                __FUNCTION__,
3895
-                __LINE__
3896
-            );
3897
-            $success = false;
3898
-        }
3899
-
3900
-
3901
-        // do check to verify we have a valid status.
3902
-        $status = $this->_req_data['status'];
3903
-
3904
-        if ($status !== 'activate' && $status !== 'deactivate') {
3905
-            EE_Error::add_error(
3906
-                sprintf(
3907
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3908
-                    $this->_req_data['status']
3909
-                ),
3910
-                __FILE__,
3911
-                __FUNCTION__,
3912
-                __LINE__
3913
-            );
3914
-            $success = false;
3915
-        }
3916
-
3917
-
3918
-        // do a nonce check here since we're not arriving via a normal route
3919
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3920
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3921
-
3922
-        $this->_verify_nonce($nonce, $nonce_ref);
3923
-
3924
-        if ($success) {
3925
-            // made it here? um, what are you waiting for then?
3926
-            $success = $status === 'deactivate'
3927
-                ? $this->_deactivate_message_type_for_messenger(
3928
-                    $this->_req_data['messenger'],
3929
-                    $this->_req_data['message_type']
3930
-                )
3931
-                : $this->_activate_message_type_for_messenger(
3932
-                    $this->_req_data['messenger'],
3933
-                    $this->_req_data['message_type']
3934
-                );
3935
-        }
3936
-
3937
-        $this->_template_args['success'] = $success;
3938
-        $this->_return_json();
3939
-    }
3940
-
3941
-
3942
-    /**
3943
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3944
-     *
3945
-     * @param string $messenger_name The name of the messenger being activated
3946
-     * @return bool
3947
-     * @throws DomainException
3948
-     * @throws EE_Error
3949
-     * @throws InvalidArgumentException
3950
-     * @throws ReflectionException
3951
-     * @throws InvalidDataTypeException
3952
-     * @throws InvalidInterfaceException
3953
-     */
3954
-    protected function _activate_messenger($messenger_name)
3955
-    {
3956
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3957
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3958
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
3959
-            ? $active_messenger->get_default_message_types()
3960
-            : array();
3961
-
3962
-        // ensure is active
3963
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3964
-
3965
-        // set response_data for reload
3966
-        foreach ($message_types_to_activate as $message_type_name) {
3967
-            /** @var EE_message_type $message_type */
3968
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3969
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3970
-                $messenger_name,
3971
-                $message_type_name
3972
-            )
3973
-                && $message_type instanceof EE_message_type
3974
-            ) {
3975
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3976
-                if ($message_type->get_admin_settings_fields()) {
3977
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3978
-                }
3979
-            }
3980
-        }
3981
-
3982
-        // add success message for activating messenger
3983
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3984
-    }
3985
-
3986
-
3987
-    /**
3988
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3989
-     *
3990
-     * @param string $messenger_name The name of the messenger being activated
3991
-     * @return bool
3992
-     * @throws DomainException
3993
-     * @throws EE_Error
3994
-     * @throws InvalidArgumentException
3995
-     * @throws ReflectionException
3996
-     * @throws InvalidDataTypeException
3997
-     * @throws InvalidInterfaceException
3998
-     */
3999
-    protected function _deactivate_messenger($messenger_name)
4000
-    {
4001
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4002
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4003
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4004
-
4005
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4006
-    }
4007
-
4008
-
4009
-    /**
4010
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4011
-     *
4012
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4013
-     * @param string $message_type_name The name of the message type being activated for the messenger
4014
-     * @return bool
4015
-     * @throws DomainException
4016
-     * @throws EE_Error
4017
-     * @throws InvalidArgumentException
4018
-     * @throws ReflectionException
4019
-     * @throws InvalidDataTypeException
4020
-     * @throws InvalidInterfaceException
4021
-     */
4022
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4023
-    {
4024
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4025
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4026
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4027
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4028
-
4029
-        // ensure is active
4030
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4031
-
4032
-        // set response for load
4033
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4034
-            $messenger_name,
4035
-            $message_type_name
4036
-        )
4037
-        ) {
4038
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4039
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4040
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4041
-            }
4042
-        }
4043
-
4044
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4045
-            $active_messenger,
4046
-            $message_type_to_activate
4047
-        );
4048
-    }
4049
-
4050
-
4051
-    /**
4052
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4053
-     *
4054
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4055
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4056
-     * @return bool
4057
-     * @throws DomainException
4058
-     * @throws EE_Error
4059
-     * @throws InvalidArgumentException
4060
-     * @throws ReflectionException
4061
-     * @throws InvalidDataTypeException
4062
-     * @throws InvalidInterfaceException
4063
-     */
4064
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4065
-    {
4066
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4071
-
4072
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4073
-            $active_messenger,
4074
-            $message_type_to_deactivate
4075
-        );
4076
-    }
4077
-
4078
-
4079
-    /**
4080
-     * This just initializes the defaults for activating messenger and message type responses.
4081
-     */
4082
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4083
-    {
4084
-        $this->_template_args['data']['active_mts'] = array();
4085
-        $this->_template_args['data']['mt_reload'] = array();
4086
-    }
4087
-
4088
-
4089
-    /**
4090
-     * Setup appropriate response for activating a messenger and/or message types
4091
-     *
4092
-     * @param EE_messenger         $messenger
4093
-     * @param EE_message_type|null $message_type
4094
-     * @return bool
4095
-     * @throws DomainException
4096
-     * @throws EE_Error
4097
-     * @throws InvalidArgumentException
4098
-     * @throws ReflectionException
4099
-     * @throws InvalidDataTypeException
4100
-     * @throws InvalidInterfaceException
4101
-     */
4102
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4103
-        $messenger,
4104
-        EE_Message_Type $message_type = null
4105
-    ) {
4106
-        // if $messenger isn't a valid messenger object then get out.
4107
-        if (! $messenger instanceof EE_Messenger) {
4108
-            EE_Error::add_error(
4109
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4110
-                __FILE__,
4111
-                __FUNCTION__,
4112
-                __LINE__
4113
-            );
4114
-
4115
-            return false;
4116
-        }
4117
-        // activated
4118
-        if ($this->_template_args['data']['active_mts']) {
4119
-            EE_Error::overwrite_success();
4120
-            // activated a message type with the messenger
4121
-            if ($message_type instanceof EE_message_type) {
4122
-                EE_Error::add_success(
4123
-                    sprintf(
4124
-                        esc_html__(
4125
-                            '%s message type has been successfully activated with the %s messenger',
4126
-                            'event_espresso'
4127
-                        ),
4128
-                        ucwords($message_type->label['singular']),
4129
-                        ucwords($messenger->label['singular'])
4130
-                    )
4131
-                );
4132
-
4133
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4134
-                if ($message_type->name === 'invoice') {
4135
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4136
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4137
-                    if ($pm instanceof EE_Payment_Method) {
4138
-                        EE_Error::add_attention(
4139
-                            esc_html__(
4140
-                                '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.',
4141
-                                'event_espresso'
4142
-                            )
4143
-                        );
4144
-                    }
4145
-                }
4146
-                // just toggles the entire messenger
4147
-            } else {
4148
-                EE_Error::add_success(
4149
-                    sprintf(
4150
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4151
-                        ucwords($messenger->label['singular'])
4152
-                    )
4153
-                );
4154
-            }
4155
-
4156
-            return true;
4157
-
4158
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4159
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4160
-            // in which case we just give a success message for the messenger being successfully activated.
4161
-        } else {
4162
-            if (! $messenger->get_default_message_types()) {
4163
-                // messenger doesn't have any default message types so still a success.
4164
-                EE_Error::add_success(
4165
-                    sprintf(
4166
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4167
-                        ucwords($messenger->label['singular'])
4168
-                    )
4169
-                );
4170
-
4171
-                return true;
4172
-            } else {
4173
-                EE_Error::add_error(
4174
-                    $message_type instanceof EE_message_type
4175
-                        ? sprintf(
4176
-                            esc_html__(
4177
-                                '%s message type was not successfully activated with the %s messenger',
4178
-                                'event_espresso'
4179
-                            ),
4180
-                            ucwords($message_type->label['singular']),
4181
-                            ucwords($messenger->label['singular'])
4182
-                        )
4183
-                        : sprintf(
4184
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4185
-                            ucwords($messenger->label['singular'])
4186
-                        ),
4187
-                    __FILE__,
4188
-                    __FUNCTION__,
4189
-                    __LINE__
4190
-                );
4191
-
4192
-                return false;
4193
-            }
4194
-        }
4195
-    }
4196
-
4197
-
4198
-    /**
4199
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4200
-     *
4201
-     * @param EE_messenger         $messenger
4202
-     * @param EE_message_type|null $message_type
4203
-     * @return bool
4204
-     * @throws DomainException
4205
-     * @throws EE_Error
4206
-     * @throws InvalidArgumentException
4207
-     * @throws ReflectionException
4208
-     * @throws InvalidDataTypeException
4209
-     * @throws InvalidInterfaceException
4210
-     */
4211
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4212
-        $messenger,
4213
-        EE_message_type $message_type = null
4214
-    ) {
4215
-        EE_Error::overwrite_success();
4216
-
4217
-        // if $messenger isn't a valid messenger object then get out.
4218
-        if (! $messenger instanceof EE_Messenger) {
4219
-            EE_Error::add_error(
4220
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4221
-                __FILE__,
4222
-                __FUNCTION__,
4223
-                __LINE__
4224
-            );
4225
-
4226
-            return false;
4227
-        }
4228
-
4229
-        if ($message_type instanceof EE_message_type) {
4230
-            $message_type_name = $message_type->name;
4231
-            EE_Error::add_success(
4232
-                sprintf(
4233
-                    esc_html__(
4234
-                        '%s message type has been successfully deactivated for the %s messenger.',
4235
-                        'event_espresso'
4236
-                    ),
4237
-                    ucwords($message_type->label['singular']),
4238
-                    ucwords($messenger->label['singular'])
4239
-                )
4240
-            );
4241
-        } else {
4242
-            $message_type_name = '';
4243
-            EE_Error::add_success(
4244
-                sprintf(
4245
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4246
-                    ucwords($messenger->label['singular'])
4247
-                )
4248
-            );
4249
-        }
4250
-
4251
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4252
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4253
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4254
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4255
-            if ($count_updated > 0) {
4256
-                $msg = $message_type_name === 'invoice'
4257
-                    ? esc_html__(
4258
-                        '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.',
4259
-                        'event_espresso'
4260
-                    )
4261
-                    : esc_html__(
4262
-                        '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.',
4263
-                        'event_espresso'
4264
-                    );
4265
-                EE_Error::add_attention($msg);
4266
-            }
4267
-        }
4268
-
4269
-        return true;
4270
-    }
4271
-
4272
-
4273
-    /**
4274
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4275
-     *
4276
-     * @throws DomainException
4277
-     */
4278
-    public function update_mt_form()
4279
-    {
4280
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4281
-            EE_Error::add_error(
4282
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4283
-                __FILE__,
4284
-                __FUNCTION__,
4285
-                __LINE__
4286
-            );
4287
-            $this->_return_json();
4288
-        }
4289
-
4290
-        $message_types = $this->get_installed_message_types();
4291
-
4292
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4293
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4294
-
4295
-        $content = $this->_message_type_settings_content(
4296
-            $message_type,
4297
-            $messenger,
4298
-            true
4299
-        );
4300
-        $this->_template_args['success'] = true;
4301
-        $this->_template_args['content'] = $content;
4302
-        $this->_return_json();
4303
-    }
4304
-
4305
-
4306
-    /**
4307
-     * this handles saving the settings for a messenger or message type
4308
-     *
4309
-     */
4310
-    public function save_settings()
4311
-    {
4312
-        if (! isset($this->_req_data['type'])) {
4313
-            EE_Error::add_error(
4314
-                esc_html__(
4315
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4316
-                    'event_espresso'
4317
-                ),
4318
-                __FILE__,
4319
-                __FUNCTION__,
4320
-                __LINE__
4321
-            );
4322
-            $this->_template_args['error'] = true;
4323
-            $this->_return_json();
4324
-        }
4325
-
4326
-
4327
-        if ($this->_req_data['type'] === 'messenger') {
4328
-            // this should be an array.
4329
-            $settings = $this->_req_data['messenger_settings'];
4330
-            $messenger = $settings['messenger'];
4331
-            // let's setup the settings data
4332
-            foreach ($settings as $key => $value) {
4333
-                switch ($key) {
4334
-                    case 'messenger':
4335
-                        unset($settings['messenger']);
4336
-                        break;
4337
-                    case 'message_types':
4338
-                        unset($settings['message_types']);
4339
-                        break;
4340
-                    default:
4341
-                        $settings[ $key ] = $value;
4342
-                        break;
4343
-                }
4344
-            }
4345
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4346
-        } elseif ($this->_req_data['type'] === 'message_type') {
4347
-            $settings = $this->_req_data['message_type_settings'];
4348
-            $messenger = $settings['messenger'];
4349
-            $message_type = $settings['message_type'];
4350
-
4351
-            foreach ($settings as $key => $value) {
4352
-                switch ($key) {
4353
-                    case 'messenger':
4354
-                        unset($settings['messenger']);
4355
-                        break;
4356
-                    case 'message_type':
4357
-                        unset($settings['message_type']);
4358
-                        break;
4359
-                    default:
4360
-                        $settings[ $key ] = $value;
4361
-                        break;
4362
-                }
4363
-            }
4364
-
4365
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4366
-        }
4367
-
4368
-        // okay we should have the data all setup.  Now we just update!
4369
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4370
-
4371
-        if ($success) {
4372
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4373
-        } else {
4374
-            EE_Error::add_error(
4375
-                esc_html__(
4376
-                    'Settings did not get updated',
4377
-                    'event_espresso'
4378
-                ),
4379
-                __FILE__,
4380
-                __FUNCTION__,
4381
-                __LINE__
4382
-            );
4383
-        }
4384
-
4385
-        $this->_template_args['success'] = $success;
4386
-        $this->_return_json();
4387
-    }
4388
-
4389
-
4390
-
4391
-
4392
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4393
-
4394
-
4395
-    /**
4396
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4397
-     * However, this does not send immediately, it just queues for sending.
4398
-     *
4399
-     * @since 4.9.0
4400
-     * @throws EE_Error
4401
-     * @throws InvalidDataTypeException
4402
-     * @throws InvalidInterfaceException
4403
-     * @throws InvalidArgumentException
4404
-     * @throws ReflectionException
4405
-     */
4406
-    protected function _generate_now()
4407
-    {
4408
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4409
-        $this->_redirect_after_action(false, '', '', array(), true);
4410
-    }
4411
-
4412
-
4413
-    /**
4414
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4415
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4416
-     *
4417
-     * @since 4.9.0
4418
-     * @throws EE_Error
4419
-     * @throws InvalidDataTypeException
4420
-     * @throws InvalidInterfaceException
4421
-     * @throws InvalidArgumentException
4422
-     * @throws ReflectionException
4423
-     */
4424
-    protected function _generate_and_send_now()
4425
-    {
4426
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4427
-        $this->_redirect_after_action(false, '', '', array(), true);
4428
-    }
4429
-
4430
-
4431
-    /**
4432
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4433
-     *
4434
-     * @since 4.9.0
4435
-     * @throws EE_Error
4436
-     * @throws InvalidDataTypeException
4437
-     * @throws InvalidInterfaceException
4438
-     * @throws InvalidArgumentException
4439
-     * @throws ReflectionException
4440
-     */
4441
-    protected function _queue_for_resending()
4442
-    {
4443
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4444
-        $this->_redirect_after_action(false, '', '', array(), true);
4445
-    }
4446
-
4447
-
4448
-    /**
4449
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4450
-     *
4451
-     * @since 4.9.0
4452
-     * @throws EE_Error
4453
-     * @throws InvalidDataTypeException
4454
-     * @throws InvalidInterfaceException
4455
-     * @throws InvalidArgumentException
4456
-     * @throws ReflectionException
4457
-     */
4458
-    protected function _send_now()
4459
-    {
4460
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4461
-        $this->_redirect_after_action(false, '', '', array(), true);
4462
-    }
4463
-
4464
-
4465
-    /**
4466
-     * Deletes EE_messages for IDs in the request.
4467
-     *
4468
-     * @since 4.9.0
4469
-     * @throws EE_Error
4470
-     * @throws InvalidDataTypeException
4471
-     * @throws InvalidInterfaceException
4472
-     * @throws InvalidArgumentException
4473
-     */
4474
-    protected function _delete_ee_messages()
4475
-    {
4476
-        $msg_ids = $this->_get_msg_ids_from_request();
4477
-        $deleted_count = 0;
4478
-        foreach ($msg_ids as $msg_id) {
4479
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4480
-                $deleted_count++;
4481
-            }
4482
-        }
4483
-        if ($deleted_count) {
4484
-            EE_Error::add_success(
4485
-                esc_html(
4486
-                    _n(
4487
-                        'Message successfully deleted',
4488
-                        'Messages successfully deleted',
4489
-                        $deleted_count,
4490
-                        'event_espresso'
4491
-                    )
4492
-                )
4493
-            );
4494
-            $this->_redirect_after_action(
4495
-                false,
4496
-                '',
4497
-                '',
4498
-                array(),
4499
-                true
4500
-            );
4501
-        } else {
4502
-            EE_Error::add_error(
4503
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4504
-                __FILE__,
4505
-                __FUNCTION__,
4506
-                __LINE__
4507
-            );
4508
-            $this->_redirect_after_action(false, '', '', array(), true);
4509
-        }
4510
-    }
4511
-
4512
-
4513
-    /**
4514
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4515
-     *
4516
-     * @since 4.9.0
4517
-     * @return array
4518
-     */
4519
-    protected function _get_msg_ids_from_request()
4520
-    {
4521
-        if (! isset($this->_req_data['MSG_ID'])) {
4522
-            return array();
4523
-        }
4524
-
4525
-        return is_array($this->_req_data['MSG_ID'])
4526
-            ? array_keys($this->_req_data['MSG_ID'])
4527
-            : array($this->_req_data['MSG_ID']);
4528
-    }
2612
+		$output = ob_get_contents();
2613
+		ob_clean();
2614
+		$this->_context_switcher = $output;
2615
+	}
2616
+
2617
+
2618
+	/**
2619
+	 * utility for sanitizing new values coming in.
2620
+	 * Note: this is only used when updating a context.
2621
+	 *
2622
+	 * @access protected
2623
+	 *
2624
+	 * @param int $index This helps us know which template field to select from the request array.
2625
+	 *
2626
+	 * @return array
2627
+	 */
2628
+	protected function _set_message_template_column_values($index)
2629
+	{
2630
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2631
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2632
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2633
+			}
2634
+		}
2635
+
2636
+
2637
+		$set_column_values = array(
2638
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2639
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2640
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2641
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2642
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2643
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2644
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2645
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2646
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2647
+				? absint($this->_req_data['MTP_is_global'])
2648
+				: 0,
2649
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2650
+				? absint($this->_req_data['MTP_is_override'])
2651
+				: 0,
2652
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2653
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2654
+		);
2655
+
2656
+
2657
+		return $set_column_values;
2658
+	}
2659
+
2660
+
2661
+	protected function _insert_or_update_message_template($new = false)
2662
+	{
2663
+
2664
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2665
+		$success = 0;
2666
+		$override = false;
2667
+
2668
+		// setup notices description
2669
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2670
+
2671
+		// need the message type and messenger objects to be able to use the labels for the notices
2672
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2673
+		$messenger_label = $messenger_object instanceof EE_messenger
2674
+			? ucwords($messenger_object->label['singular'])
2675
+			: '';
2676
+
2677
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2678
+			? $this->_req_data['MTP_message_type']
2679
+			: '';
2680
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2681
+
2682
+		$message_type_label = $message_type_object instanceof EE_message_type
2683
+			? ucwords($message_type_object->label['singular'])
2684
+			: '';
2685
+
2686
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2687
+			? $this->_req_data['MTP_context']
2688
+			: '';
2689
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2690
+
2691
+		$item_desc = $messenger_label && $message_type_label
2692
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2693
+			: '';
2694
+		$item_desc .= 'Message Template';
2695
+		$query_args = array();
2696
+		$edit_array = array();
2697
+		$action_desc = '';
2698
+
2699
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2700
+		// user to edit.
2701
+		if ($new) {
2702
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2703
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2704
+				if (empty($edit_array)) {
2705
+					$success = 0;
2706
+				} else {
2707
+					$success = 1;
2708
+					$edit_array = $edit_array[0];
2709
+					$query_args = array(
2710
+						'id'      => $edit_array['GRP_ID'],
2711
+						'context' => $edit_array['MTP_context'],
2712
+						'action'  => 'edit_message_template',
2713
+					);
2714
+				}
2715
+			}
2716
+			$action_desc = 'created';
2717
+		} else {
2718
+			$MTPG = EEM_Message_Template_Group::instance();
2719
+			$MTP = EEM_Message_Template::instance();
2720
+
2721
+
2722
+			// run update for each template field in displayed context
2723
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2724
+				EE_Error::add_error(
2725
+					esc_html__(
2726
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2727
+						'event_espresso'
2728
+					),
2729
+					__FILE__,
2730
+					__FUNCTION__,
2731
+					__LINE__
2732
+				);
2733
+				$success = 0;
2734
+			} else {
2735
+				// first validate all fields!
2736
+				// this filter allows client code to add its own validation to the template fields as well.
2737
+				// returning an empty array means everything passed validation.
2738
+				// errors in validation should be represented in an array with the following shape:
2739
+				// array(
2740
+				//   'fieldname' => array(
2741
+				//          'msg' => 'error message'
2742
+				//          'value' => 'value for field producing error'
2743
+				// )
2744
+				$custom_validation = (array) apply_filters(
2745
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2746
+					array(),
2747
+					$this->_req_data['MTP_template_fields'],
2748
+					$context_slug,
2749
+					$messenger_slug,
2750
+					$message_type_slug
2751
+				);
2752
+
2753
+				$system_validation = $MTPG->validate(
2754
+					$this->_req_data['MTP_template_fields'],
2755
+					$context_slug,
2756
+					$messenger_slug,
2757
+					$message_type_slug
2758
+				);
2759
+
2760
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2761
+					: $system_validation;
2762
+				$validates = array_merge($custom_validation, $system_validation);
2763
+
2764
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2765
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2766
+				//  WE need to make sure there is no actual error messages in validates.
2767
+				if (is_array($validates) && ! empty($validates)) {
2768
+					// add the transient so when the form loads we know which fields to highlight
2769
+					$this->_add_transient('edit_message_template', $validates);
2770
+
2771
+					$success = 0;
2772
+
2773
+					// setup notices
2774
+					foreach ($validates as $field => $error) {
2775
+						if (isset($error['msg'])) {
2776
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2777
+						}
2778
+					}
2779
+				} else {
2780
+					$set_column_values = array();
2781
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2782
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2783
+
2784
+						$where_cols_n_values = array(
2785
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2786
+						);
2787
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2788
+						if (! current_user_can('unfiltered_html')) {
2789
+							if (is_array($set_column_values['MTP_content'])) {
2790
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2791
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2792
+									// only removes slashes from double-quotes, so attributes using single quotes always
2793
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2794
+									// runs we need to re-slash the data. Sheesh. See
2795
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2796
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2797
+										wp_kses(
2798
+											stripslashes($value),
2799
+											wp_kses_allowed_html('post')
2800
+										)
2801
+									);
2802
+								}
2803
+							} else {
2804
+								$set_column_values['MTP_content'] = wp_kses(
2805
+									$set_column_values['MTP_content'],
2806
+									wp_kses_allowed_html('post')
2807
+								);
2808
+							}
2809
+						}
2810
+						$message_template_fields = array(
2811
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2812
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2813
+							'MTP_context'        => $set_column_values['MTP_context'],
2814
+							'MTP_content'        => $set_column_values['MTP_content'],
2815
+						);
2816
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2817
+							if ($updated === false) {
2818
+								EE_Error::add_error(
2819
+									sprintf(
2820
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2821
+										$template_field
2822
+									),
2823
+									__FILE__,
2824
+									__FUNCTION__,
2825
+									__LINE__
2826
+								);
2827
+							} else {
2828
+								$success = 1;
2829
+							}
2830
+						} else {
2831
+							// only do this logic if we don't have a MTP_ID for this field
2832
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2833
+								// this has already been through the template field validator and sanitized, so it will be
2834
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2835
+								// message template field in a messenger/message type and existing users don't have the
2836
+								// default setup for it.
2837
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2838
+								$updated = $MTP->insert($message_template_fields);
2839
+								if (! $updated || is_wp_error($updated)) {
2840
+									EE_Error::add_error(
2841
+										sprintf(
2842
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2843
+											$template_field
2844
+										),
2845
+										__FILE__,
2846
+										__FUNCTION__,
2847
+										__LINE__
2848
+									);
2849
+									$success = 0;
2850
+								} else {
2851
+									$success = 1;
2852
+								}
2853
+							}
2854
+						}
2855
+						$action_desc = 'updated';
2856
+					}
2857
+
2858
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2859
+					$mtpg_fields = array(
2860
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2861
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2862
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2863
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2864
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2865
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2866
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2867
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2868
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2869
+							: '',
2870
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2871
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2872
+							: '',
2873
+					);
2874
+
2875
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2876
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2877
+
2878
+					if ($updated === false) {
2879
+						EE_Error::add_error(
2880
+							sprintf(
2881
+								esc_html__(
2882
+									'The Message Template Group (%d) was NOT updated for some reason',
2883
+									'event_espresso'
2884
+								),
2885
+								$set_column_values['GRP_ID']
2886
+							),
2887
+							__FILE__,
2888
+							__FUNCTION__,
2889
+							__LINE__
2890
+						);
2891
+					} else {
2892
+						// k now we need to ensure the template_pack and template_variation fields are set.
2893
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2894
+							? $this->_req_data['MTP_template_pack']
2895
+							: 'default';
2896
+
2897
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2898
+							? $this->_req_data['MTP_template_variation']
2899
+							: 'default';
2900
+
2901
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2902
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2903
+							$mtpg_obj->set_template_pack_name($template_pack);
2904
+							$mtpg_obj->set_template_pack_variation($template_variation);
2905
+						}
2906
+						$success = 1;
2907
+					}
2908
+				}
2909
+			}
2910
+		}
2911
+
2912
+		// we return things differently if doing ajax
2913
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2914
+			$this->_template_args['success'] = $success;
2915
+			$this->_template_args['error'] = ! $success ? true : false;
2916
+			$this->_template_args['content'] = '';
2917
+			$this->_template_args['data'] = array(
2918
+				'grpID'        => $edit_array['GRP_ID'],
2919
+				'templateName' => $edit_array['template_name'],
2920
+			);
2921
+			if ($success) {
2922
+				EE_Error::overwrite_success();
2923
+				EE_Error::add_success(
2924
+					esc_html__(
2925
+						'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.',
2926
+						'event_espresso'
2927
+					)
2928
+				);
2929
+			}
2930
+
2931
+			$this->_return_json();
2932
+		}
2933
+
2934
+
2935
+		// was a test send triggered?
2936
+		if (isset($this->_req_data['test_button'])) {
2937
+			EE_Error::overwrite_success();
2938
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2939
+			$override = true;
2940
+		}
2941
+
2942
+		if (empty($query_args)) {
2943
+			$query_args = array(
2944
+				'id'      => $this->_req_data['GRP_ID'],
2945
+				'context' => $context_slug,
2946
+				'action'  => 'edit_message_template',
2947
+			);
2948
+		}
2949
+
2950
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2951
+	}
2952
+
2953
+
2954
+	/**
2955
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2956
+	 *
2957
+	 * @param  string $context      what context being tested
2958
+	 * @param  string $messenger    messenger being tested
2959
+	 * @param  string $message_type message type being tested
2960
+	 * @throws EE_Error
2961
+	 * @throws InvalidArgumentException
2962
+	 * @throws InvalidDataTypeException
2963
+	 * @throws InvalidInterfaceException
2964
+	 */
2965
+	protected function _do_test_send($context, $messenger, $message_type)
2966
+	{
2967
+		// set things up for preview
2968
+		$this->_req_data['messenger'] = $messenger;
2969
+		$this->_req_data['message_type'] = $message_type;
2970
+		$this->_req_data['context'] = $context;
2971
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2972
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
2973
+
2974
+		// let's save any existing fields that might be required by the messenger
2975
+		if (isset($this->_req_data['test_settings_fld'])
2976
+			&& $active_messenger instanceof EE_messenger
2977
+			&& apply_filters(
2978
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2979
+				true,
2980
+				$this->_req_data['test_settings_fld'],
2981
+				$active_messenger
2982
+			)
2983
+		) {
2984
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2985
+		}
2986
+
2987
+		/**
2988
+		 * Use filter to add additional controls on whether message can send or not
2989
+		 */
2990
+		if (apply_filters(
2991
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
2992
+			true,
2993
+			$context,
2994
+			$this->_req_data,
2995
+			$messenger,
2996
+			$message_type
2997
+		)) {
2998
+			$success = $this->_preview_message(true);
2999
+			if ($success) {
3000
+				EE_Error::add_success(__('Test message sent', 'event_espresso'));
3001
+			} else {
3002
+				EE_Error::add_error(
3003
+					esc_html__('The test message was not sent', 'event_espresso'),
3004
+					__FILE__,
3005
+					__FUNCTION__,
3006
+					__LINE__
3007
+				);
3008
+			}
3009
+		}
3010
+	}
3011
+
3012
+
3013
+	/**
3014
+	 * _generate_new_templates
3015
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3016
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3017
+	 * for the event.
3018
+	 *
3019
+	 *
3020
+	 * @param  string $messenger     the messenger we are generating templates for
3021
+	 * @param array   $message_types array of message types that the templates are generated for.
3022
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3023
+	 *                               indicate the message_template_group being used as the base.
3024
+	 *
3025
+	 * @param bool    $global
3026
+	 *
3027
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3028
+	 *                               encountering problems.
3029
+	 * @throws EE_Error
3030
+	 */
3031
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3032
+	{
3033
+
3034
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3035
+		// just don't generate any templates.
3036
+		if (empty($message_types)) {
3037
+			return true;
3038
+		}
3039
+
3040
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3041
+	}
3042
+
3043
+
3044
+	/**
3045
+	 * [_trash_or_restore_message_template]
3046
+	 *
3047
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3048
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3049
+	 *                        an individual context (FALSE).
3050
+	 * @return void
3051
+	 * @throws EE_Error
3052
+	 * @throws InvalidArgumentException
3053
+	 * @throws InvalidDataTypeException
3054
+	 * @throws InvalidInterfaceException
3055
+	 */
3056
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3057
+	{
3058
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3059
+		$MTP = EEM_Message_Template_Group::instance();
3060
+
3061
+		$success = 1;
3062
+
3063
+		// incoming GRP_IDs
3064
+		if ($all) {
3065
+			// Checkboxes
3066
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3067
+				// if array has more than one element then success message should be plural.
3068
+				// todo: what about nonce?
3069
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3070
+
3071
+				// cycle through checkboxes
3072
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3074
+					if (! $trashed_or_restored) {
3075
+						$success = 0;
3076
+					}
3077
+				}
3078
+			} else {
3079
+				// grab single GRP_ID and handle
3080
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3081
+				if (! empty($GRP_ID)) {
3082
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3083
+					if (! $trashed_or_restored) {
3084
+						$success = 0;
3085
+					}
3086
+				} else {
3087
+					$success = 0;
3088
+				}
3089
+			}
3090
+		}
3091
+
3092
+		$action_desc = $trash
3093
+			? esc_html__('moved to the trash', 'event_espresso')
3094
+			: esc_html__('restored', 'event_espresso');
3095
+
3096
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3097
+
3098
+		$item_desc = $all ? _n(
3099
+			'Message Template Group',
3100
+			'Message Template Groups',
3101
+			$success,
3102
+			'event_espresso'
3103
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3104
+
3105
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3106
+			'template',
3107
+			'templates',
3108
+			$success,
3109
+			'event_espresso'
3110
+		) : $item_desc;
3111
+
3112
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3113
+	}
3114
+
3115
+
3116
+	/**
3117
+	 * [_delete_message_template]
3118
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3119
+	 *
3120
+	 * @return void
3121
+	 * @throws EE_Error
3122
+	 * @throws InvalidArgumentException
3123
+	 * @throws InvalidDataTypeException
3124
+	 * @throws InvalidInterfaceException
3125
+	 */
3126
+	protected function _delete_message_template()
3127
+	{
3128
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3129
+
3130
+		// checkboxes
3131
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3132
+			// if array has more than one element then success message should be plural
3133
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3134
+
3135
+			// cycle through bulk action checkboxes
3136
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3137
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3138
+			}
3139
+		} else {
3140
+			// grab single grp_id and delete
3141
+			$GRP_ID = absint($this->_req_data['id']);
3142
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3143
+		}
3144
+
3145
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3146
+	}
3147
+
3148
+
3149
+	/**
3150
+	 * helper for permanently deleting a mtP group and all related message_templates
3151
+	 *
3152
+	 * @param  int  $GRP_ID        The group being deleted
3153
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3154
+	 * @return bool boolean to indicate the success of the deletes or not.
3155
+	 * @throws EE_Error
3156
+	 * @throws InvalidArgumentException
3157
+	 * @throws InvalidDataTypeException
3158
+	 * @throws InvalidInterfaceException
3159
+	 */
3160
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3161
+	{
3162
+		$success = 1;
3163
+		$MTPG = EEM_Message_Template_Group::instance();
3164
+		// first let's GET this group
3165
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3166
+		// then delete permanently all the related Message Templates
3167
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3168
+
3169
+		if ($deleted === 0) {
3170
+			$success = 0;
3171
+		}
3172
+
3173
+		// now delete permanently this particular group
3174
+
3175
+		if ($include_group && ! $MTG->delete_permanently()) {
3176
+			$success = 0;
3177
+		}
3178
+
3179
+		return $success;
3180
+	}
3181
+
3182
+
3183
+	/**
3184
+	 *    _learn_more_about_message_templates_link
3185
+	 *
3186
+	 * @access protected
3187
+	 * @return string
3188
+	 */
3189
+	protected function _learn_more_about_message_templates_link()
3190
+	{
3191
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3192
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3193
+			   . '</a>';
3194
+	}
3195
+
3196
+
3197
+	/**
3198
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3199
+	 * ajax and other routes.
3200
+	 *
3201
+	 * @return void
3202
+	 * @throws DomainException
3203
+	 */
3204
+	protected function _settings()
3205
+	{
3206
+
3207
+
3208
+		$this->_set_m_mt_settings();
3209
+
3210
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3211
+			? $this->_req_data['selected_messenger']
3212
+			: 'email';
3213
+
3214
+		// let's setup the messenger tabs
3215
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3216
+			$this->_m_mt_settings['messenger_tabs'],
3217
+			'messenger_links',
3218
+			'|',
3219
+			$selected_messenger
3220
+		);
3221
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3222
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3223
+
3224
+		$this->display_admin_page_with_sidebar();
3225
+	}
3226
+
3227
+
3228
+	/**
3229
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3230
+	 *
3231
+	 * @access protected
3232
+	 * @return void
3233
+	 * @throws DomainException
3234
+	 */
3235
+	protected function _set_m_mt_settings()
3236
+	{
3237
+		// first if this is already set then lets get out no need to regenerate data.
3238
+		if (! empty($this->_m_mt_settings)) {
3239
+			return;
3240
+		}
3241
+
3242
+		// get all installed messengers and message_types
3243
+		/** @type EE_messenger[] $messengers */
3244
+		$messengers = $this->_message_resource_manager->installed_messengers();
3245
+		/** @type EE_message_type[] $message_types */
3246
+		$message_types = $this->_message_resource_manager->installed_message_types();
3247
+
3248
+
3249
+		// assemble the array for the _tab_text_links helper
3250
+
3251
+		foreach ($messengers as $messenger) {
3252
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3253
+				'label' => ucwords($messenger->label['singular']),
3254
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3255
+					? 'messenger-active'
3256
+					: '',
3257
+				'href'  => $messenger->name,
3258
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3259
+				'slug'  => $messenger->name,
3260
+				'obj'   => $messenger,
3261
+			);
3262
+
3263
+
3264
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3265
+
3266
+			foreach ($message_types as $message_type) {
3267
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3268
+				// it shouldn't show in either the inactive OR active metabox.
3269
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3270
+					continue;
3271
+				}
3272
+
3273
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3274
+					$messenger->name,
3275
+					$message_type->name
3276
+				)
3277
+					? 'active'
3278
+					: 'inactive';
3279
+
3280
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3281
+					'label'    => ucwords($message_type->label['singular']),
3282
+					'class'    => 'message-type-' . $a_or_i,
3283
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3284
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3285
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3286
+					'title'    => $a_or_i === 'active'
3287
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3288
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3289
+					'content'  => $a_or_i === 'active'
3290
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3291
+						: $this->_message_type_settings_content($message_type, $messenger),
3292
+					'slug'     => $message_type->name,
3293
+					'active'   => $a_or_i === 'active',
3294
+					'obj'      => $message_type,
3295
+				);
3296
+			}
3297
+		}
3298
+	}
3299
+
3300
+
3301
+	/**
3302
+	 * This just prepares the content for the message type settings
3303
+	 *
3304
+	 * @param  EE_message_type $message_type The message type object
3305
+	 * @param  EE_messenger    $messenger    The messenger object
3306
+	 * @param  boolean         $active       Whether the message type is active or not
3307
+	 * @return string html output for the content
3308
+	 * @throws DomainException
3309
+	 */
3310
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3311
+	{
3312
+		// get message type fields
3313
+		$fields = $message_type->get_admin_settings_fields();
3314
+		$settings_template_args['template_form_fields'] = '';
3315
+
3316
+		if (! empty($fields) && $active) {
3317
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3318
+			foreach ($fields as $fldname => $fldprops) {
3319
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3320
+				$template_form_field[ $field_id ] = array(
3321
+					'name'       => 'message_type_settings[' . $fldname . ']',
3322
+					'label'      => $fldprops['label'],
3323
+					'input'      => $fldprops['field_type'],
3324
+					'type'       => $fldprops['value_type'],
3325
+					'required'   => $fldprops['required'],
3326
+					'validation' => $fldprops['validation'],
3327
+					'value'      => isset($existing_settings[ $fldname ])
3328
+						? $existing_settings[ $fldname ]
3329
+						: $fldprops['default'],
3330
+					'options'    => isset($fldprops['options'])
3331
+						? $fldprops['options']
3332
+						: array(),
3333
+					'default'    => isset($existing_settings[ $fldname ])
3334
+						? $existing_settings[ $fldname ]
3335
+						: $fldprops['default'],
3336
+					'css_class'  => 'no-drag',
3337
+					'format'     => $fldprops['format'],
3338
+				);
3339
+			}
3340
+
3341
+
3342
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3343
+				? $this->_generate_admin_form_fields(
3344
+					$template_form_field,
3345
+					'string',
3346
+					'ee_mt_activate_form'
3347
+				)
3348
+				: '';
3349
+		}
3350
+
3351
+		$settings_template_args['description'] = $message_type->description;
3352
+		// we also need some hidden fields
3353
+		$settings_template_args['hidden_fields'] = array(
3354
+			'message_type_settings[messenger]'    => array(
3355
+				'type'  => 'hidden',
3356
+				'value' => $messenger->name,
3357
+			),
3358
+			'message_type_settings[message_type]' => array(
3359
+				'type'  => 'hidden',
3360
+				'value' => $message_type->name,
3361
+			),
3362
+			'type'                                => array(
3363
+				'type'  => 'hidden',
3364
+				'value' => 'message_type',
3365
+			),
3366
+		);
3367
+
3368
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3369
+			$settings_template_args['hidden_fields'],
3370
+			'array'
3371
+		);
3372
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3373
+			? ' hidden'
3374
+			: '';
3375
+
3376
+
3377
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3378
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3379
+
3380
+		return $content;
3381
+	}
3382
+
3383
+
3384
+	/**
3385
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3386
+	 *
3387
+	 * @access protected
3388
+	 * @return void
3389
+	 * @throws DomainException
3390
+	 */
3391
+	protected function _messages_settings_metaboxes()
3392
+	{
3393
+		$this->_set_m_mt_settings();
3394
+		$m_boxes = $mt_boxes = array();
3395
+		$m_template_args = $mt_template_args = array();
3396
+
3397
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3398
+			? $this->_req_data['selected_messenger']
3399
+			: 'email';
3400
+
3401
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3402
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3403
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3404
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3405
+				// messenger meta boxes
3406
+				$active = $selected_messenger === $messenger;
3407
+				$active_mt_tabs = isset(
3408
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3409
+				)
3410
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3411
+					: '';
3412
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3413
+					esc_html__('%s Settings', 'event_espresso'),
3414
+					$tab_array['label']
3415
+				);
3416
+				$m_template_args[ $messenger . '_a_box' ] = array(
3417
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3418
+					'inactive_message_types' => isset(
3419
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3420
+					)
3421
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3422
+						: '',
3423
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3424
+					'hidden'                 => $active ? '' : ' hidden',
3425
+					'hide_on_message'        => $hide_on_message,
3426
+					'messenger'              => $messenger,
3427
+					'active'                 => $active,
3428
+				);
3429
+				// message type meta boxes
3430
+				// (which is really just the inactive container for each messenger
3431
+				// showing inactive message types for that messenger)
3432
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3433
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3434
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3435
+					'inactive_message_types' => isset(
3436
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3437
+					)
3438
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3439
+						: '',
3440
+					'hidden'                 => $active ? '' : ' hidden',
3441
+					'hide_on_message'        => $hide_on_message,
3442
+					'hide_off_message'       => $hide_off_message,
3443
+					'messenger'              => $messenger,
3444
+					'active'                 => $active,
3445
+				);
3446
+			}
3447
+		}
3448
+
3449
+
3450
+		// register messenger metaboxes
3451
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3452
+		foreach ($m_boxes as $box => $label) {
3453
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3454
+			$msgr = str_replace('_a_box', '', $box);
3455
+			add_meta_box(
3456
+				'espresso_' . $msgr . '_settings',
3457
+				$label,
3458
+				function ($post, $metabox) {
3459
+					echo EEH_Template::display_template(
3460
+						$metabox["args"]["template_path"],
3461
+						$metabox["args"]["template_args"],
3462
+						true
3463
+					);
3464
+				},
3465
+				$this->_current_screen->id,
3466
+				'normal',
3467
+				'high',
3468
+				$callback_args
3469
+			);
3470
+		}
3471
+
3472
+		// register message type metaboxes
3473
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3474
+		foreach ($mt_boxes as $box => $label) {
3475
+			$callback_args = array(
3476
+				'template_path' => $mt_template_path,
3477
+				'template_args' => $mt_template_args[ $box ],
3478
+			);
3479
+			$mt = str_replace('_i_box', '', $box);
3480
+			add_meta_box(
3481
+				'espresso_' . $mt . '_inactive_mts',
3482
+				$label,
3483
+				function ($post, $metabox) {
3484
+					echo EEH_Template::display_template(
3485
+						$metabox["args"]["template_path"],
3486
+						$metabox["args"]["template_args"],
3487
+						true
3488
+					);
3489
+				},
3490
+				$this->_current_screen->id,
3491
+				'side',
3492
+				'high',
3493
+				$callback_args
3494
+			);
3495
+		}
3496
+
3497
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3498
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3499
+		if (is_main_site()) {
3500
+			add_meta_box(
3501
+				'espresso_global_message_settings',
3502
+				esc_html__('Global Message Settings', 'event_espresso'),
3503
+				array($this, 'global_messages_settings_metabox_content'),
3504
+				$this->_current_screen->id,
3505
+				'normal',
3506
+				'low',
3507
+				array()
3508
+			);
3509
+		}
3510
+	}
3511
+
3512
+
3513
+	/**
3514
+	 *  This generates the content for the global messages settings metabox.
3515
+	 *
3516
+	 * @return string
3517
+	 * @throws EE_Error
3518
+	 * @throws InvalidArgumentException
3519
+	 * @throws ReflectionException
3520
+	 * @throws InvalidDataTypeException
3521
+	 * @throws InvalidInterfaceException
3522
+	 */
3523
+	public function global_messages_settings_metabox_content()
3524
+	{
3525
+		$form = $this->_generate_global_settings_form();
3526
+		echo $form->form_open(
3527
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3528
+			'POST'
3529
+		)
3530
+			 . $form->get_html()
3531
+			 . $form->form_close();
3532
+	}
3533
+
3534
+
3535
+	/**
3536
+	 * This generates and returns the form object for the global messages settings.
3537
+	 *
3538
+	 * @return EE_Form_Section_Proper
3539
+	 * @throws EE_Error
3540
+	 * @throws InvalidArgumentException
3541
+	 * @throws ReflectionException
3542
+	 * @throws InvalidDataTypeException
3543
+	 * @throws InvalidInterfaceException
3544
+	 */
3545
+	protected function _generate_global_settings_form()
3546
+	{
3547
+		EE_Registry::instance()->load_helper('HTML');
3548
+		/** @var EE_Network_Core_Config $network_config */
3549
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3550
+
3551
+		return new EE_Form_Section_Proper(
3552
+			array(
3553
+				'name'            => 'global_messages_settings',
3554
+				'html_id'         => 'global_messages_settings',
3555
+				'html_class'      => 'form-table',
3556
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3557
+				'subsections'     => apply_filters(
3558
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3559
+					array(
3560
+						'do_messages_on_same_request' => new EE_Select_Input(
3561
+							array(
3562
+								true  => esc_html__("On the same request", "event_espresso"),
3563
+								false => esc_html__("On a separate request", "event_espresso"),
3564
+							),
3565
+							array(
3566
+								'default'         => $network_config->do_messages_on_same_request,
3567
+								'html_label_text' => esc_html__(
3568
+									'Generate and send all messages:',
3569
+									'event_espresso'
3570
+								),
3571
+								'html_help_text'  => esc_html__(
3572
+									'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.',
3573
+									'event_espresso'
3574
+								),
3575
+							)
3576
+						),
3577
+						'delete_threshold'            => new EE_Select_Input(
3578
+							array(
3579
+								0  => esc_html__('Forever', 'event_espresso'),
3580
+								3  => esc_html__('3 Months', 'event_espresso'),
3581
+								6  => esc_html__('6 Months', 'event_espresso'),
3582
+								9  => esc_html__('9 Months', 'event_espresso'),
3583
+								12 => esc_html__('12 Months', 'event_espresso'),
3584
+								24 => esc_html__('24 Months', 'event_espresso'),
3585
+								36 => esc_html__('36 Months', 'event_espresso'),
3586
+							),
3587
+							array(
3588
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3589
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3590
+								'html_help_text'  => esc_html__(
3591
+									'You can control how long a record of processed messages is kept via this option.',
3592
+									'event_espresso'
3593
+								),
3594
+							)
3595
+						),
3596
+						'update_settings'             => new EE_Submit_Input(
3597
+							array(
3598
+								'default'         => esc_html__('Update', 'event_espresso'),
3599
+								'html_label_text' => '&nbsp',
3600
+							)
3601
+						),
3602
+					)
3603
+				),
3604
+			)
3605
+		);
3606
+	}
3607
+
3608
+
3609
+	/**
3610
+	 * This handles updating the global settings set on the admin page.
3611
+	 *
3612
+	 * @throws EE_Error
3613
+	 * @throws InvalidDataTypeException
3614
+	 * @throws InvalidInterfaceException
3615
+	 * @throws InvalidArgumentException
3616
+	 * @throws ReflectionException
3617
+	 */
3618
+	protected function _update_global_settings()
3619
+	{
3620
+		/** @var EE_Network_Core_Config $network_config */
3621
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3622
+		$messages_config = EE_Registry::instance()->CFG->messages;
3623
+		$form = $this->_generate_global_settings_form();
3624
+		if ($form->was_submitted()) {
3625
+			$form->receive_form_submission();
3626
+			if ($form->is_valid()) {
3627
+				$valid_data = $form->valid_data();
3628
+				foreach ($valid_data as $property => $value) {
3629
+					$setter = 'set_' . $property;
3630
+					if (method_exists($network_config, $setter)) {
3631
+						$network_config->{$setter}($value);
3632
+					} elseif (property_exists($network_config, $property)
3633
+						&& $network_config->{$property} !== $value
3634
+					) {
3635
+						$network_config->{$property} = $value;
3636
+					} elseif (property_exists($messages_config, $property)
3637
+						&& $messages_config->{$property} !== $value
3638
+					) {
3639
+						$messages_config->{$property} = $value;
3640
+					}
3641
+				}
3642
+				// only update if the form submission was valid!
3643
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3644
+				EE_Registry::instance()->CFG->update_espresso_config();
3645
+				EE_Error::overwrite_success();
3646
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3647
+			}
3648
+		}
3649
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3650
+	}
3651
+
3652
+
3653
+	/**
3654
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3655
+	 *
3656
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3657
+	 * @return string html formatted tabs
3658
+	 * @throws DomainException
3659
+	 */
3660
+	protected function _get_mt_tabs($tab_array)
3661
+	{
3662
+		$tab_array = (array) $tab_array;
3663
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3664
+		$tabs = '';
3665
+
3666
+		foreach ($tab_array as $tab) {
3667
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3668
+		}
3669
+
3670
+		return $tabs;
3671
+	}
3672
+
3673
+
3674
+	/**
3675
+	 * This prepares the content of the messenger meta box admin settings
3676
+	 *
3677
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3678
+	 * @return string html formatted content
3679
+	 * @throws DomainException
3680
+	 */
3681
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3682
+	{
3683
+
3684
+		$fields = $messenger->get_admin_settings_fields();
3685
+		$settings_template_args['template_form_fields'] = '';
3686
+
3687
+		// is $messenger active?
3688
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3689
+
3690
+
3691
+		if (! empty($fields)) {
3692
+			$existing_settings = $messenger->get_existing_admin_settings();
3693
+
3694
+			foreach ($fields as $fldname => $fldprops) {
3695
+				$field_id = $messenger->name . '-' . $fldname;
3696
+				$template_form_field[ $field_id ] = array(
3697
+					'name'       => 'messenger_settings[' . $field_id . ']',
3698
+					'label'      => $fldprops['label'],
3699
+					'input'      => $fldprops['field_type'],
3700
+					'type'       => $fldprops['value_type'],
3701
+					'required'   => $fldprops['required'],
3702
+					'validation' => $fldprops['validation'],
3703
+					'value'      => isset($existing_settings[ $field_id ])
3704
+						? $existing_settings[ $field_id ]
3705
+						: $fldprops['default'],
3706
+					'css_class'  => '',
3707
+					'format'     => $fldprops['format'],
3708
+				);
3709
+			}
3710
+
3711
+
3712
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3713
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3714
+				: '';
3715
+		}
3716
+
3717
+		// we also need some hidden fields
3718
+		$settings_template_args['hidden_fields'] = array(
3719
+			'messenger_settings[messenger]' => array(
3720
+				'type'  => 'hidden',
3721
+				'value' => $messenger->name,
3722
+			),
3723
+			'type'                          => array(
3724
+				'type'  => 'hidden',
3725
+				'value' => 'messenger',
3726
+			),
3727
+		);
3728
+
3729
+		// make sure any active message types that are existing are included in the hidden fields
3730
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3731
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3732
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3733
+					'type'  => 'hidden',
3734
+					'value' => $mt,
3735
+				);
3736
+			}
3737
+		}
3738
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3739
+			$settings_template_args['hidden_fields'],
3740
+			'array'
3741
+		);
3742
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
+
3744
+		$settings_template_args['messenger'] = $messenger->name;
3745
+		$settings_template_args['description'] = $messenger->description;
3746
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3747
+
3748
+
3749
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3750
+			$messenger->name
3751
+		)
3752
+			? $settings_template_args['show_hide_edit_form']
3753
+			: ' hidden';
3754
+
3755
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3756
+			? ' hidden'
3757
+			: $settings_template_args['show_hide_edit_form'];
3758
+
3759
+
3760
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3761
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3762
+		$settings_template_args['on_off_status'] = $active ? true : false;
3763
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3764
+		$content = EEH_Template::display_template(
3765
+			$template,
3766
+			$settings_template_args,
3767
+			true
3768
+		);
3769
+
3770
+		return $content;
3771
+	}
3772
+
3773
+
3774
+	/**
3775
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3776
+	 *
3777
+	 * @throws DomainException
3778
+	 * @throws EE_Error
3779
+	 * @throws InvalidDataTypeException
3780
+	 * @throws InvalidInterfaceException
3781
+	 * @throws InvalidArgumentException
3782
+	 * @throws ReflectionException
3783
+	 */
3784
+	public function activate_messenger_toggle()
3785
+	{
3786
+		$success = true;
3787
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3788
+		// let's check that we have required data
3789
+		if (! isset($this->_req_data['messenger'])) {
3790
+			EE_Error::add_error(
3791
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3792
+				__FILE__,
3793
+				__FUNCTION__,
3794
+				__LINE__
3795
+			);
3796
+			$success = false;
3797
+		}
3798
+
3799
+		// do a nonce check here since we're not arriving via a normal route
3800
+		$nonce = isset($this->_req_data['activate_nonce'])
3801
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3802
+			: '';
3803
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3804
+
3805
+		$this->_verify_nonce($nonce, $nonce_ref);
3806
+
3807
+
3808
+		if (! isset($this->_req_data['status'])) {
3809
+			EE_Error::add_error(
3810
+				esc_html__(
3811
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3812
+					'event_espresso'
3813
+				),
3814
+				__FILE__,
3815
+				__FUNCTION__,
3816
+				__LINE__
3817
+			);
3818
+			$success = false;
3819
+		}
3820
+
3821
+		// do check to verify we have a valid status.
3822
+		$status = $this->_req_data['status'];
3823
+
3824
+		if ($status !== 'off' && $status !== 'on') {
3825
+			EE_Error::add_error(
3826
+				sprintf(
3827
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3828
+					$this->_req_data['status']
3829
+				),
3830
+				__FILE__,
3831
+				__FUNCTION__,
3832
+				__LINE__
3833
+			);
3834
+			$success = false;
3835
+		}
3836
+
3837
+		if ($success) {
3838
+			// made it here?  Stop dawdling then!!
3839
+			$success = $status === 'off'
3840
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3841
+				: $this->_activate_messenger($this->_req_data['messenger']);
3842
+		}
3843
+
3844
+		$this->_template_args['success'] = $success;
3845
+
3846
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3847
+		$this->_return_json();
3848
+	}
3849
+
3850
+
3851
+	/**
3852
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3853
+	 *
3854
+	 * @throws DomainException
3855
+	 * @throws EE_Error
3856
+	 * @throws ReflectionException
3857
+	 * @throws InvalidDataTypeException
3858
+	 * @throws InvalidInterfaceException
3859
+	 * @throws InvalidArgumentException
3860
+	 */
3861
+	public function activate_mt_toggle()
3862
+	{
3863
+		$success = true;
3864
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3865
+
3866
+		// let's make sure we have the necessary data
3867
+		if (! isset($this->_req_data['message_type'])) {
3868
+			EE_Error::add_error(
3869
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3870
+				__FILE__,
3871
+				__FUNCTION__,
3872
+				__LINE__
3873
+			);
3874
+			$success = false;
3875
+		}
3876
+
3877
+		if (! isset($this->_req_data['messenger'])) {
3878
+			EE_Error::add_error(
3879
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3880
+				__FILE__,
3881
+				__FUNCTION__,
3882
+				__LINE__
3883
+			);
3884
+			$success = false;
3885
+		}
3886
+
3887
+		if (! isset($this->_req_data['status'])) {
3888
+			EE_Error::add_error(
3889
+				esc_html__(
3890
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3891
+					'event_espresso'
3892
+				),
3893
+				__FILE__,
3894
+				__FUNCTION__,
3895
+				__LINE__
3896
+			);
3897
+			$success = false;
3898
+		}
3899
+
3900
+
3901
+		// do check to verify we have a valid status.
3902
+		$status = $this->_req_data['status'];
3903
+
3904
+		if ($status !== 'activate' && $status !== 'deactivate') {
3905
+			EE_Error::add_error(
3906
+				sprintf(
3907
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3908
+					$this->_req_data['status']
3909
+				),
3910
+				__FILE__,
3911
+				__FUNCTION__,
3912
+				__LINE__
3913
+			);
3914
+			$success = false;
3915
+		}
3916
+
3917
+
3918
+		// do a nonce check here since we're not arriving via a normal route
3919
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3920
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3921
+
3922
+		$this->_verify_nonce($nonce, $nonce_ref);
3923
+
3924
+		if ($success) {
3925
+			// made it here? um, what are you waiting for then?
3926
+			$success = $status === 'deactivate'
3927
+				? $this->_deactivate_message_type_for_messenger(
3928
+					$this->_req_data['messenger'],
3929
+					$this->_req_data['message_type']
3930
+				)
3931
+				: $this->_activate_message_type_for_messenger(
3932
+					$this->_req_data['messenger'],
3933
+					$this->_req_data['message_type']
3934
+				);
3935
+		}
3936
+
3937
+		$this->_template_args['success'] = $success;
3938
+		$this->_return_json();
3939
+	}
3940
+
3941
+
3942
+	/**
3943
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3944
+	 *
3945
+	 * @param string $messenger_name The name of the messenger being activated
3946
+	 * @return bool
3947
+	 * @throws DomainException
3948
+	 * @throws EE_Error
3949
+	 * @throws InvalidArgumentException
3950
+	 * @throws ReflectionException
3951
+	 * @throws InvalidDataTypeException
3952
+	 * @throws InvalidInterfaceException
3953
+	 */
3954
+	protected function _activate_messenger($messenger_name)
3955
+	{
3956
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3957
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3958
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
3959
+			? $active_messenger->get_default_message_types()
3960
+			: array();
3961
+
3962
+		// ensure is active
3963
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3964
+
3965
+		// set response_data for reload
3966
+		foreach ($message_types_to_activate as $message_type_name) {
3967
+			/** @var EE_message_type $message_type */
3968
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3969
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3970
+				$messenger_name,
3971
+				$message_type_name
3972
+			)
3973
+				&& $message_type instanceof EE_message_type
3974
+			) {
3975
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3976
+				if ($message_type->get_admin_settings_fields()) {
3977
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3978
+				}
3979
+			}
3980
+		}
3981
+
3982
+		// add success message for activating messenger
3983
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3984
+	}
3985
+
3986
+
3987
+	/**
3988
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3989
+	 *
3990
+	 * @param string $messenger_name The name of the messenger being activated
3991
+	 * @return bool
3992
+	 * @throws DomainException
3993
+	 * @throws EE_Error
3994
+	 * @throws InvalidArgumentException
3995
+	 * @throws ReflectionException
3996
+	 * @throws InvalidDataTypeException
3997
+	 * @throws InvalidInterfaceException
3998
+	 */
3999
+	protected function _deactivate_messenger($messenger_name)
4000
+	{
4001
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4002
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4003
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4004
+
4005
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4006
+	}
4007
+
4008
+
4009
+	/**
4010
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4011
+	 *
4012
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4013
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4014
+	 * @return bool
4015
+	 * @throws DomainException
4016
+	 * @throws EE_Error
4017
+	 * @throws InvalidArgumentException
4018
+	 * @throws ReflectionException
4019
+	 * @throws InvalidDataTypeException
4020
+	 * @throws InvalidInterfaceException
4021
+	 */
4022
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4023
+	{
4024
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4025
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4026
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4027
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4028
+
4029
+		// ensure is active
4030
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4031
+
4032
+		// set response for load
4033
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4034
+			$messenger_name,
4035
+			$message_type_name
4036
+		)
4037
+		) {
4038
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4039
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4040
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4041
+			}
4042
+		}
4043
+
4044
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4045
+			$active_messenger,
4046
+			$message_type_to_activate
4047
+		);
4048
+	}
4049
+
4050
+
4051
+	/**
4052
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4053
+	 *
4054
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4055
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4056
+	 * @return bool
4057
+	 * @throws DomainException
4058
+	 * @throws EE_Error
4059
+	 * @throws InvalidArgumentException
4060
+	 * @throws ReflectionException
4061
+	 * @throws InvalidDataTypeException
4062
+	 * @throws InvalidInterfaceException
4063
+	 */
4064
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4065
+	{
4066
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4071
+
4072
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4073
+			$active_messenger,
4074
+			$message_type_to_deactivate
4075
+		);
4076
+	}
4077
+
4078
+
4079
+	/**
4080
+	 * This just initializes the defaults for activating messenger and message type responses.
4081
+	 */
4082
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4083
+	{
4084
+		$this->_template_args['data']['active_mts'] = array();
4085
+		$this->_template_args['data']['mt_reload'] = array();
4086
+	}
4087
+
4088
+
4089
+	/**
4090
+	 * Setup appropriate response for activating a messenger and/or message types
4091
+	 *
4092
+	 * @param EE_messenger         $messenger
4093
+	 * @param EE_message_type|null $message_type
4094
+	 * @return bool
4095
+	 * @throws DomainException
4096
+	 * @throws EE_Error
4097
+	 * @throws InvalidArgumentException
4098
+	 * @throws ReflectionException
4099
+	 * @throws InvalidDataTypeException
4100
+	 * @throws InvalidInterfaceException
4101
+	 */
4102
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4103
+		$messenger,
4104
+		EE_Message_Type $message_type = null
4105
+	) {
4106
+		// if $messenger isn't a valid messenger object then get out.
4107
+		if (! $messenger instanceof EE_Messenger) {
4108
+			EE_Error::add_error(
4109
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4110
+				__FILE__,
4111
+				__FUNCTION__,
4112
+				__LINE__
4113
+			);
4114
+
4115
+			return false;
4116
+		}
4117
+		// activated
4118
+		if ($this->_template_args['data']['active_mts']) {
4119
+			EE_Error::overwrite_success();
4120
+			// activated a message type with the messenger
4121
+			if ($message_type instanceof EE_message_type) {
4122
+				EE_Error::add_success(
4123
+					sprintf(
4124
+						esc_html__(
4125
+							'%s message type has been successfully activated with the %s messenger',
4126
+							'event_espresso'
4127
+						),
4128
+						ucwords($message_type->label['singular']),
4129
+						ucwords($messenger->label['singular'])
4130
+					)
4131
+				);
4132
+
4133
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4134
+				if ($message_type->name === 'invoice') {
4135
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4136
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4137
+					if ($pm instanceof EE_Payment_Method) {
4138
+						EE_Error::add_attention(
4139
+							esc_html__(
4140
+								'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.',
4141
+								'event_espresso'
4142
+							)
4143
+						);
4144
+					}
4145
+				}
4146
+				// just toggles the entire messenger
4147
+			} else {
4148
+				EE_Error::add_success(
4149
+					sprintf(
4150
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4151
+						ucwords($messenger->label['singular'])
4152
+					)
4153
+				);
4154
+			}
4155
+
4156
+			return true;
4157
+
4158
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4159
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4160
+			// in which case we just give a success message for the messenger being successfully activated.
4161
+		} else {
4162
+			if (! $messenger->get_default_message_types()) {
4163
+				// messenger doesn't have any default message types so still a success.
4164
+				EE_Error::add_success(
4165
+					sprintf(
4166
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4167
+						ucwords($messenger->label['singular'])
4168
+					)
4169
+				);
4170
+
4171
+				return true;
4172
+			} else {
4173
+				EE_Error::add_error(
4174
+					$message_type instanceof EE_message_type
4175
+						? sprintf(
4176
+							esc_html__(
4177
+								'%s message type was not successfully activated with the %s messenger',
4178
+								'event_espresso'
4179
+							),
4180
+							ucwords($message_type->label['singular']),
4181
+							ucwords($messenger->label['singular'])
4182
+						)
4183
+						: sprintf(
4184
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4185
+							ucwords($messenger->label['singular'])
4186
+						),
4187
+					__FILE__,
4188
+					__FUNCTION__,
4189
+					__LINE__
4190
+				);
4191
+
4192
+				return false;
4193
+			}
4194
+		}
4195
+	}
4196
+
4197
+
4198
+	/**
4199
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4200
+	 *
4201
+	 * @param EE_messenger         $messenger
4202
+	 * @param EE_message_type|null $message_type
4203
+	 * @return bool
4204
+	 * @throws DomainException
4205
+	 * @throws EE_Error
4206
+	 * @throws InvalidArgumentException
4207
+	 * @throws ReflectionException
4208
+	 * @throws InvalidDataTypeException
4209
+	 * @throws InvalidInterfaceException
4210
+	 */
4211
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4212
+		$messenger,
4213
+		EE_message_type $message_type = null
4214
+	) {
4215
+		EE_Error::overwrite_success();
4216
+
4217
+		// if $messenger isn't a valid messenger object then get out.
4218
+		if (! $messenger instanceof EE_Messenger) {
4219
+			EE_Error::add_error(
4220
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4221
+				__FILE__,
4222
+				__FUNCTION__,
4223
+				__LINE__
4224
+			);
4225
+
4226
+			return false;
4227
+		}
4228
+
4229
+		if ($message_type instanceof EE_message_type) {
4230
+			$message_type_name = $message_type->name;
4231
+			EE_Error::add_success(
4232
+				sprintf(
4233
+					esc_html__(
4234
+						'%s message type has been successfully deactivated for the %s messenger.',
4235
+						'event_espresso'
4236
+					),
4237
+					ucwords($message_type->label['singular']),
4238
+					ucwords($messenger->label['singular'])
4239
+				)
4240
+			);
4241
+		} else {
4242
+			$message_type_name = '';
4243
+			EE_Error::add_success(
4244
+				sprintf(
4245
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4246
+					ucwords($messenger->label['singular'])
4247
+				)
4248
+			);
4249
+		}
4250
+
4251
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4252
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4253
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4254
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4255
+			if ($count_updated > 0) {
4256
+				$msg = $message_type_name === 'invoice'
4257
+					? esc_html__(
4258
+						'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.',
4259
+						'event_espresso'
4260
+					)
4261
+					: esc_html__(
4262
+						'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.',
4263
+						'event_espresso'
4264
+					);
4265
+				EE_Error::add_attention($msg);
4266
+			}
4267
+		}
4268
+
4269
+		return true;
4270
+	}
4271
+
4272
+
4273
+	/**
4274
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4275
+	 *
4276
+	 * @throws DomainException
4277
+	 */
4278
+	public function update_mt_form()
4279
+	{
4280
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4281
+			EE_Error::add_error(
4282
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4283
+				__FILE__,
4284
+				__FUNCTION__,
4285
+				__LINE__
4286
+			);
4287
+			$this->_return_json();
4288
+		}
4289
+
4290
+		$message_types = $this->get_installed_message_types();
4291
+
4292
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4293
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4294
+
4295
+		$content = $this->_message_type_settings_content(
4296
+			$message_type,
4297
+			$messenger,
4298
+			true
4299
+		);
4300
+		$this->_template_args['success'] = true;
4301
+		$this->_template_args['content'] = $content;
4302
+		$this->_return_json();
4303
+	}
4304
+
4305
+
4306
+	/**
4307
+	 * this handles saving the settings for a messenger or message type
4308
+	 *
4309
+	 */
4310
+	public function save_settings()
4311
+	{
4312
+		if (! isset($this->_req_data['type'])) {
4313
+			EE_Error::add_error(
4314
+				esc_html__(
4315
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4316
+					'event_espresso'
4317
+				),
4318
+				__FILE__,
4319
+				__FUNCTION__,
4320
+				__LINE__
4321
+			);
4322
+			$this->_template_args['error'] = true;
4323
+			$this->_return_json();
4324
+		}
4325
+
4326
+
4327
+		if ($this->_req_data['type'] === 'messenger') {
4328
+			// this should be an array.
4329
+			$settings = $this->_req_data['messenger_settings'];
4330
+			$messenger = $settings['messenger'];
4331
+			// let's setup the settings data
4332
+			foreach ($settings as $key => $value) {
4333
+				switch ($key) {
4334
+					case 'messenger':
4335
+						unset($settings['messenger']);
4336
+						break;
4337
+					case 'message_types':
4338
+						unset($settings['message_types']);
4339
+						break;
4340
+					default:
4341
+						$settings[ $key ] = $value;
4342
+						break;
4343
+				}
4344
+			}
4345
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4346
+		} elseif ($this->_req_data['type'] === 'message_type') {
4347
+			$settings = $this->_req_data['message_type_settings'];
4348
+			$messenger = $settings['messenger'];
4349
+			$message_type = $settings['message_type'];
4350
+
4351
+			foreach ($settings as $key => $value) {
4352
+				switch ($key) {
4353
+					case 'messenger':
4354
+						unset($settings['messenger']);
4355
+						break;
4356
+					case 'message_type':
4357
+						unset($settings['message_type']);
4358
+						break;
4359
+					default:
4360
+						$settings[ $key ] = $value;
4361
+						break;
4362
+				}
4363
+			}
4364
+
4365
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4366
+		}
4367
+
4368
+		// okay we should have the data all setup.  Now we just update!
4369
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4370
+
4371
+		if ($success) {
4372
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4373
+		} else {
4374
+			EE_Error::add_error(
4375
+				esc_html__(
4376
+					'Settings did not get updated',
4377
+					'event_espresso'
4378
+				),
4379
+				__FILE__,
4380
+				__FUNCTION__,
4381
+				__LINE__
4382
+			);
4383
+		}
4384
+
4385
+		$this->_template_args['success'] = $success;
4386
+		$this->_return_json();
4387
+	}
4388
+
4389
+
4390
+
4391
+
4392
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4393
+
4394
+
4395
+	/**
4396
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4397
+	 * However, this does not send immediately, it just queues for sending.
4398
+	 *
4399
+	 * @since 4.9.0
4400
+	 * @throws EE_Error
4401
+	 * @throws InvalidDataTypeException
4402
+	 * @throws InvalidInterfaceException
4403
+	 * @throws InvalidArgumentException
4404
+	 * @throws ReflectionException
4405
+	 */
4406
+	protected function _generate_now()
4407
+	{
4408
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4409
+		$this->_redirect_after_action(false, '', '', array(), true);
4410
+	}
4411
+
4412
+
4413
+	/**
4414
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4415
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4416
+	 *
4417
+	 * @since 4.9.0
4418
+	 * @throws EE_Error
4419
+	 * @throws InvalidDataTypeException
4420
+	 * @throws InvalidInterfaceException
4421
+	 * @throws InvalidArgumentException
4422
+	 * @throws ReflectionException
4423
+	 */
4424
+	protected function _generate_and_send_now()
4425
+	{
4426
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4427
+		$this->_redirect_after_action(false, '', '', array(), true);
4428
+	}
4429
+
4430
+
4431
+	/**
4432
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4433
+	 *
4434
+	 * @since 4.9.0
4435
+	 * @throws EE_Error
4436
+	 * @throws InvalidDataTypeException
4437
+	 * @throws InvalidInterfaceException
4438
+	 * @throws InvalidArgumentException
4439
+	 * @throws ReflectionException
4440
+	 */
4441
+	protected function _queue_for_resending()
4442
+	{
4443
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4444
+		$this->_redirect_after_action(false, '', '', array(), true);
4445
+	}
4446
+
4447
+
4448
+	/**
4449
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4450
+	 *
4451
+	 * @since 4.9.0
4452
+	 * @throws EE_Error
4453
+	 * @throws InvalidDataTypeException
4454
+	 * @throws InvalidInterfaceException
4455
+	 * @throws InvalidArgumentException
4456
+	 * @throws ReflectionException
4457
+	 */
4458
+	protected function _send_now()
4459
+	{
4460
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4461
+		$this->_redirect_after_action(false, '', '', array(), true);
4462
+	}
4463
+
4464
+
4465
+	/**
4466
+	 * Deletes EE_messages for IDs in the request.
4467
+	 *
4468
+	 * @since 4.9.0
4469
+	 * @throws EE_Error
4470
+	 * @throws InvalidDataTypeException
4471
+	 * @throws InvalidInterfaceException
4472
+	 * @throws InvalidArgumentException
4473
+	 */
4474
+	protected function _delete_ee_messages()
4475
+	{
4476
+		$msg_ids = $this->_get_msg_ids_from_request();
4477
+		$deleted_count = 0;
4478
+		foreach ($msg_ids as $msg_id) {
4479
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4480
+				$deleted_count++;
4481
+			}
4482
+		}
4483
+		if ($deleted_count) {
4484
+			EE_Error::add_success(
4485
+				esc_html(
4486
+					_n(
4487
+						'Message successfully deleted',
4488
+						'Messages successfully deleted',
4489
+						$deleted_count,
4490
+						'event_espresso'
4491
+					)
4492
+				)
4493
+			);
4494
+			$this->_redirect_after_action(
4495
+				false,
4496
+				'',
4497
+				'',
4498
+				array(),
4499
+				true
4500
+			);
4501
+		} else {
4502
+			EE_Error::add_error(
4503
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4504
+				__FILE__,
4505
+				__FUNCTION__,
4506
+				__LINE__
4507
+			);
4508
+			$this->_redirect_after_action(false, '', '', array(), true);
4509
+		}
4510
+	}
4511
+
4512
+
4513
+	/**
4514
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4515
+	 *
4516
+	 * @since 4.9.0
4517
+	 * @return array
4518
+	 */
4519
+	protected function _get_msg_ids_from_request()
4520
+	{
4521
+		if (! isset($this->_req_data['MSG_ID'])) {
4522
+			return array();
4523
+		}
4524
+
4525
+		return is_array($this->_req_data['MSG_ID'])
4526
+			? array_keys($this->_req_data['MSG_ID'])
4527
+			: array($this->_req_data['MSG_ID']);
4528
+	}
4529 4529
 }
Please login to merge, or discard this patch.