Completed
Branch BUG-10489-non-trashed-regs-onl... (a7561f)
by
unknown
46:07 queued 34:09
created
core/admin/EE_Admin_Page.core.php 1 patch
Spacing   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
         $this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
477 477
         $this->page_folder = strtolower(str_replace('_Admin_Page', '', str_replace('Extend_', '', get_class($this))));
478 478
         global $ee_menu_slugs;
479
-        $ee_menu_slugs = (array)$ee_menu_slugs;
479
+        $ee_menu_slugs = (array) $ee_menu_slugs;
480 480
         if (( ! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page])) && ! defined('DOING_AJAX')) {
481 481
             return;
482 482
         }
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
         //however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
492 492
         $this->_req_action = defined('DOING_AJAX') && isset($this->_req_data['route']) ? $this->_req_data['route'] : $this->_req_action;
493 493
         $this->_current_view = $this->_req_action;
494
-        $this->_req_nonce = $this->_req_action . '_nonce';
494
+        $this->_req_nonce = $this->_req_action.'_nonce';
495 495
         $this->_define_page_props();
496 496
         $this->_current_page_view_url = add_query_arg(array('page' => $this->_current_page, 'action' => $this->_current_view), $this->_admin_base_url);
497 497
         //default things
@@ -512,11 +512,11 @@  discard block
 block discarded – undo
512 512
             $this->_extend_page_config_for_cpt();
513 513
         }
514 514
         //filter routes and page_config so addons can add their stuff. Filtering done per class
515
-        $this->_page_routes = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_routes', $this->_page_routes, $this);
516
-        $this->_page_config = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_config', $this->_page_config, $this);
515
+        $this->_page_routes = apply_filters('FHEE__'.get_class($this).'__page_setup__page_routes', $this->_page_routes, $this);
516
+        $this->_page_config = apply_filters('FHEE__'.get_class($this).'__page_setup__page_config', $this->_page_config, $this);
517 517
         //if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
518
-        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
519
-            add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view), 10, 2);
518
+        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_'.$this->_current_view)) {
519
+            add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'AHEE__EE_Admin_Page__route_admin_request_'.$this->_current_view), 10, 2);
520 520
         }
521 521
         //next route only if routing enabled
522 522
         if ($this->_routing && ! defined('DOING_AJAX')) {
@@ -526,8 +526,8 @@  discard block
 block discarded – undo
526 526
             if ($this->_is_UI_request) {
527 527
                 //admin_init stuff - global, all views for this page class, specific view
528 528
                 add_action('admin_init', array($this, 'admin_init'), 10);
529
-                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
530
-                    add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
529
+                if (method_exists($this, 'admin_init_'.$this->_current_view)) {
530
+                    add_action('admin_init', array($this, 'admin_init_'.$this->_current_view), 15);
531 531
                 }
532 532
             } else {
533 533
                 //hijack regular WP loading and route admin request immediately
@@ -547,17 +547,17 @@  discard block
 block discarded – undo
547 547
      */
548 548
     private function _do_other_page_hooks()
549 549
     {
550
-        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
550
+        $registered_pages = apply_filters('FHEE_do_other_page_hooks_'.$this->page_slug, array());
551 551
         foreach ($registered_pages as $page) {
552 552
             //now let's setup the file name and class that should be present
553 553
             $classname = str_replace('.class.php', '', $page);
554 554
             //autoloaders should take care of loading file
555 555
             if ( ! class_exists($classname)) {
556
-                $error_msg[] = sprintf( esc_html__('Something went wrong with loading the %s admin hooks page.', 'event_espresso'), $page);
556
+                $error_msg[] = sprintf(esc_html__('Something went wrong with loading the %s admin hooks page.', 'event_espresso'), $page);
557 557
                 $error_msg[] = $error_msg[0]
558 558
                                . "\r\n"
559
-                               . sprintf( esc_html__('There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
560
-                                'event_espresso'), $page, '<br />', '<strong>' . $classname . '</strong>');
559
+                               . sprintf(esc_html__('There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
560
+                                'event_espresso'), $page, '<br />', '<strong>'.$classname.'</strong>');
561 561
                 throw new EE_Error(implode('||', $error_msg));
562 562
             }
563 563
             $a = new ReflectionClass($classname);
@@ -593,13 +593,13 @@  discard block
 block discarded – undo
593 593
         //load admin_notices - global, page class, and view specific
594 594
         add_action('admin_notices', array($this, 'admin_notices_global'), 5);
595 595
         add_action('admin_notices', array($this, 'admin_notices'), 10);
596
-        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
597
-            add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
596
+        if (method_exists($this, 'admin_notices_'.$this->_current_view)) {
597
+            add_action('admin_notices', array($this, 'admin_notices_'.$this->_current_view), 15);
598 598
         }
599 599
         //load network admin_notices - global, page class, and view specific
600 600
         add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
601
-        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
602
-            add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
601
+        if (method_exists($this, 'network_admin_notices_'.$this->_current_view)) {
602
+            add_action('network_admin_notices', array($this, 'network_admin_notices_'.$this->_current_view));
603 603
         }
604 604
         //this will save any per_page screen options if they are present
605 605
         $this->_set_per_page_screen_options();
@@ -611,8 +611,8 @@  discard block
 block discarded – undo
611 611
         //add screen options - global, page child class, and view specific
612 612
         $this->_add_global_screen_options();
613 613
         $this->_add_screen_options();
614
-        if (method_exists($this, '_add_screen_options_' . $this->_current_view)) {
615
-            call_user_func(array($this, '_add_screen_options_' . $this->_current_view));
614
+        if (method_exists($this, '_add_screen_options_'.$this->_current_view)) {
615
+            call_user_func(array($this, '_add_screen_options_'.$this->_current_view));
616 616
         }
617 617
         //add help tab(s) and tours- set via page_config and qtips.
618 618
         $this->_add_help_tour();
@@ -621,31 +621,31 @@  discard block
 block discarded – undo
621 621
         //add feature_pointers - global, page child class, and view specific
622 622
         $this->_add_feature_pointers();
623 623
         $this->_add_global_feature_pointers();
624
-        if (method_exists($this, '_add_feature_pointer_' . $this->_current_view)) {
625
-            call_user_func(array($this, '_add_feature_pointer_' . $this->_current_view));
624
+        if (method_exists($this, '_add_feature_pointer_'.$this->_current_view)) {
625
+            call_user_func(array($this, '_add_feature_pointer_'.$this->_current_view));
626 626
         }
627 627
         //enqueue scripts/styles - global, page class, and view specific
628 628
         add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
629 629
         add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
630
-        if (method_exists($this, 'load_scripts_styles_' . $this->_current_view)) {
631
-            add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles_' . $this->_current_view), 15);
630
+        if (method_exists($this, 'load_scripts_styles_'.$this->_current_view)) {
631
+            add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles_'.$this->_current_view), 15);
632 632
         }
633 633
         add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
634 634
         //admin_print_footer_scripts - global, page child class, and view specific.  NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.  In most cases that's doing_it_wrong().  But adding hidden container elements etc. is a good use case. Notice the late priority we're giving these
635 635
         add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
636 636
         add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
637
-        if (method_exists($this, 'admin_footer_scripts_' . $this->_current_view)) {
638
-            add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_' . $this->_current_view), 101);
637
+        if (method_exists($this, 'admin_footer_scripts_'.$this->_current_view)) {
638
+            add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_'.$this->_current_view), 101);
639 639
         }
640 640
         //admin footer scripts
641 641
         add_action('admin_footer', array($this, 'admin_footer_global'), 99);
642 642
         add_action('admin_footer', array($this, 'admin_footer'), 100);
643
-        if (method_exists($this, 'admin_footer_' . $this->_current_view)) {
644
-            add_action('admin_footer', array($this, 'admin_footer_' . $this->_current_view), 101);
643
+        if (method_exists($this, 'admin_footer_'.$this->_current_view)) {
644
+            add_action('admin_footer', array($this, 'admin_footer_'.$this->_current_view), 101);
645 645
         }
646 646
         do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
647 647
         //targeted hook
648
-        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load__' . $this->page_slug . '__' . $this->_req_action);
648
+        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load__'.$this->page_slug.'__'.$this->_req_action);
649 649
     }
650 650
 
651 651
 
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
             // user error msg
722 722
             $error_msg = sprintf(__('No page routes have been set for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
723 723
             // developer error msg
724
-            $error_msg .= '||' . $error_msg . __(' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.', 'event_espresso');
724
+            $error_msg .= '||'.$error_msg.__(' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.', 'event_espresso');
725 725
             throw new EE_Error($error_msg);
726 726
         }
727 727
         // and that the requested page route exists
@@ -732,7 +732,7 @@  discard block
 block discarded – undo
732 732
             // user error msg
733 733
             $error_msg = sprintf(__('The requested page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
734 734
             // developer error msg
735
-            $error_msg .= '||' . $error_msg . sprintf(__(' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.', 'event_espresso'), $this->_req_action);
735
+            $error_msg .= '||'.$error_msg.sprintf(__(' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.', 'event_espresso'), $this->_req_action);
736 736
             throw new EE_Error($error_msg);
737 737
         }
738 738
         // and that a default route exists
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
             // user error msg
741 741
             $error_msg = sprintf(__('A default page route has not been set for the % admin page.', 'event_espresso'), $this->_admin_page_title);
742 742
             // developer error msg
743
-            $error_msg .= '||' . $error_msg . __(' Create a key in the "_page_routes" array named "default" and set its value to your default page method.', 'event_espresso');
743
+            $error_msg .= '||'.$error_msg.__(' Create a key in the "_page_routes" array named "default" and set its value to your default page method.', 'event_espresso');
744 744
             throw new EE_Error($error_msg);
745 745
         }
746 746
         //first lets' catch if the UI request has EVER been set.
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
             // user error msg
770 770
             $error_msg = sprintf(__('The given page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
771 771
             // developer error msg
772
-            $error_msg .= '||' . $error_msg . sprintf(__(' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property', 'event_espresso'), $route);
772
+            $error_msg .= '||'.$error_msg.sprintf(__(' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property', 'event_espresso'), $route);
773 773
             throw new EE_Error($error_msg);
774 774
         }
775 775
     }
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
             // these are not the droids you are looking for !!!
792 792
             $msg = sprintf(__('%sNonce Fail.%s', 'event_espresso'), '<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">', '</a>');
793 793
             if (WP_DEBUG) {
794
-                $msg .= "\n  " . sprintf(__('In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!', 'event_espresso'), __CLASS__);
794
+                $msg .= "\n  ".sprintf(__('In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!', 'event_espresso'), __CLASS__);
795 795
             }
796 796
             if ( ! defined('DOING_AJAX')) {
797 797
                 wp_die($msg);
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
                 if (strpos($key, 'nonce') !== false) {
970 970
                     continue;
971 971
                 }
972
-                $args['wp_referer[' . $key . ']'] = $value;
972
+                $args['wp_referer['.$key.']'] = $value;
973 973
             }
974 974
         }
975 975
         return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
                     if ($tour instanceof EE_Help_Tour_final_stop) {
1016 1016
                         continue;
1017 1017
                     }
1018
-                    $tb[] = '<button id="trigger-tour-' . $tour->get_slug() . '" class="button-primary trigger-ee-help-tour">' . $tour->get_label() . '</button>';
1018
+                    $tb[] = '<button id="trigger-tour-'.$tour->get_slug().'" class="button-primary trigger-ee-help-tour">'.$tour->get_label().'</button>';
1019 1019
                 }
1020 1020
                 $tour_buttons .= implode('<br />', $tb);
1021 1021
                 $tour_buttons .= '</div></div>';
@@ -1027,7 +1027,7 @@  discard block
 block discarded – undo
1027 1027
                     throw new EE_Error(sprintf(__('The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1028 1028
                             'event_espresso'), $config['help_sidebar'], get_class($this)));
1029 1029
                 }
1030
-                $content = apply_filters('FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar', call_user_func(array($this, $config['help_sidebar'])));
1030
+                $content = apply_filters('FHEE__'.get_class($this).'__add_help_tabs__help_sidebar', call_user_func(array($this, $config['help_sidebar'])));
1031 1031
                 $content .= $tour_buttons; //add help tour buttons.
1032 1032
                 //do we have any help tours setup?  Cause if we do we want to add the buttons
1033 1033
                 $this->_current_screen->set_help_sidebar($content);
@@ -1040,13 +1040,13 @@  discard block
 block discarded – undo
1040 1040
             if ( ! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1041 1041
                 $_ht['id'] = $this->page_slug;
1042 1042
                 $_ht['title'] = __('Help Tours', 'event_espresso');
1043
-                $_ht['content'] = '<p>' . __('The buttons to the right allow you to start/restart any help tours available for this page', 'event_espresso') . '</p>';
1043
+                $_ht['content'] = '<p>'.__('The buttons to the right allow you to start/restart any help tours available for this page', 'event_espresso').'</p>';
1044 1044
                 $this->_current_screen->add_help_tab($_ht);
1045 1045
             }/**/
1046 1046
             if ( ! isset($config['help_tabs'])) {
1047 1047
                 return;
1048 1048
             } //no help tabs for this route
1049
-            foreach ((array)$config['help_tabs'] as $tab_id => $cfg) {
1049
+            foreach ((array) $config['help_tabs'] as $tab_id => $cfg) {
1050 1050
                 //we're here so there ARE help tabs!
1051 1051
                 //make sure we've got what we need
1052 1052
                 if ( ! isset($cfg['title'])) {
@@ -1061,9 +1061,9 @@  discard block
 block discarded – undo
1061 1061
                     $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1062 1062
                     //second priority goes to filename
1063 1063
                 } else if ( ! empty($cfg['filename'])) {
1064
-                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1064
+                    $file_path = $this->_get_dir().'/help_tabs/'.$cfg['filename'].'.help_tab.php';
1065 1065
                     //it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1066
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tabs/' . $cfg['filename'] . '.help_tab.php' : $file_path;
1066
+                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()).'/help_tabs/'.$cfg['filename'].'.help_tab.php' : $file_path;
1067 1067
                     //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1068 1068
                     if ( ! is_readable($file_path) && ! isset($cfg['callback'])) {
1069 1069
                         EE_Error::add_error(sprintf(__('The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
@@ -1082,7 +1082,7 @@  discard block
 block discarded – undo
1082 1082
                     return;
1083 1083
                 }
1084 1084
                 //setup config array for help tab method
1085
-                $id = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1085
+                $id = $this->page_slug.'-'.$this->_req_action.'-'.$tab_id;
1086 1086
                 $_ht = array(
1087 1087
                         'id'       => $id,
1088 1088
                         'title'    => $cfg['title'],
@@ -1120,9 +1120,9 @@  discard block
 block discarded – undo
1120 1120
             }
1121 1121
             if (isset($config['help_tour'])) {
1122 1122
                 foreach ($config['help_tour'] as $tour) {
1123
-                    $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1123
+                    $file_path = $this->_get_dir().'/help_tours/'.$tour.'.class.php';
1124 1124
                     //let's see if we can get that file... if not its possible this is a decaf route not set in caffienated so lets try and get the caffeinated equivalent
1125
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tours/' . $tour . '.class.php' : $file_path;
1125
+                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()).'/help_tours/'.$tour.'.class.php' : $file_path;
1126 1126
                     //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1127 1127
                     if ( ! is_readable($file_path)) {
1128 1128
                         EE_Error::add_error(sprintf(__('The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling', 'event_espresso'),
@@ -1132,7 +1132,7 @@  discard block
 block discarded – undo
1132 1132
                     require_once $file_path;
1133 1133
                     if ( ! class_exists($tour)) {
1134 1134
                         $error_msg[] = sprintf(__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'), $tour);
1135
-                        $error_msg[] = $error_msg[0] . "\r\n" . sprintf(__('There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1135
+                        $error_msg[] = $error_msg[0]."\r\n".sprintf(__('There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1136 1136
                                         'event_espresso'), $tour, '<br />', $tour, $this->_req_action, get_class($this));
1137 1137
                         throw new EE_Error(implode('||', $error_msg));
1138 1138
                     }
@@ -1164,11 +1164,11 @@  discard block
 block discarded – undo
1164 1164
     protected function _add_qtips()
1165 1165
     {
1166 1166
         if (isset($this->_route_config['qtips'])) {
1167
-            $qtips = (array)$this->_route_config['qtips'];
1167
+            $qtips = (array) $this->_route_config['qtips'];
1168 1168
             //load qtip loader
1169 1169
             $path = array(
1170
-                    $this->_get_dir() . '/qtips/',
1171
-                    EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1170
+                    $this->_get_dir().'/qtips/',
1171
+                    EE_ADMIN_PAGES.basename($this->_get_dir()).'/qtips/',
1172 1172
             );
1173 1173
             EEH_Qtip_Loader::instance()->register($qtips, $path);
1174 1174
         }
@@ -1198,11 +1198,11 @@  discard block
 block discarded – undo
1198 1198
             if ( ! $this->check_user_access($slug, true)) {
1199 1199
                 continue;
1200 1200
             } //no nav tab becasue current user does not have access.
1201
-            $css_class = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1201
+            $css_class = isset($config['css_class']) ? $config['css_class'].' ' : '';
1202 1202
             $this->_nav_tabs[$slug] = array(
1203 1203
                     'url'       => isset($config['nav']['url']) ? $config['nav']['url'] : self::add_query_args_and_nonce(array('action' => $slug), $this->_admin_base_url),
1204 1204
                     'link_text' => isset($config['nav']['label']) ? $config['nav']['label'] : ucwords(str_replace('_', ' ', $slug)),
1205
-                    'css_class' => $this->_req_action == $slug ? $css_class . 'nav-tab-active' : $css_class,
1205
+                    'css_class' => $this->_req_action == $slug ? $css_class.'nav-tab-active' : $css_class,
1206 1206
                     'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1207 1207
             );
1208 1208
             $i++;
@@ -1265,11 +1265,11 @@  discard block
 block discarded – undo
1265 1265
             $capability = empty($capability) ? 'manage_options' : $capability;
1266 1266
         }
1267 1267
         $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1268
-        if (( ! function_exists('is_admin') || ! EE_Registry::instance()->CAP->current_user_can($capability, $this->page_slug . '_' . $route_to_check, $id)) && ! defined('DOING_AJAX')) {
1268
+        if (( ! function_exists('is_admin') || ! EE_Registry::instance()->CAP->current_user_can($capability, $this->page_slug.'_'.$route_to_check, $id)) && ! defined('DOING_AJAX')) {
1269 1269
             if ($verify_only) {
1270 1270
                 return false;
1271 1271
             } else {
1272
-                if ( is_user_logged_in() ) {
1272
+                if (is_user_logged_in()) {
1273 1273
                     wp_die(__('You do not have access to this route.', 'event_espresso'));
1274 1274
                 } else {
1275 1275
                     return false;
@@ -1361,7 +1361,7 @@  discard block
 block discarded – undo
1361 1361
     public function admin_footer_global()
1362 1362
     {
1363 1363
         //dialog container for dialog helper
1364
-        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1364
+        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">'."\n";
1365 1365
         $d_cont .= '<div class="ee-notices"></div>';
1366 1366
         $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1367 1367
         $d_cont .= '</div>';
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
             echo implode('<br />', $this->_help_tour[$this->_req_action]);
1372 1372
         }
1373 1373
         //current set timezone for timezone js
1374
-        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1374
+        echo '<span id="current_timezone" class="hidden">'.EEH_DTT_Helper::get_timezone().'</span>';
1375 1375
     }
1376 1376
 
1377 1377
 
@@ -1396,7 +1396,7 @@  discard block
 block discarded – undo
1396 1396
     {
1397 1397
         $content = '';
1398 1398
         $help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1399
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php';
1399
+        $template_path = EE_ADMIN_TEMPLATE.'admin_help_popup.template.php';
1400 1400
         //loop through the array and setup content
1401 1401
         foreach ($help_array as $trigger => $help) {
1402 1402
             //make sure the array is setup properly
@@ -1430,7 +1430,7 @@  discard block
 block discarded – undo
1430 1430
     private function _get_help_content()
1431 1431
     {
1432 1432
         //what is the method we're looking for?
1433
-        $method_name = '_help_popup_content_' . $this->_req_action;
1433
+        $method_name = '_help_popup_content_'.$this->_req_action;
1434 1434
         //if method doesn't exist let's get out.
1435 1435
         if ( ! method_exists($this, $method_name)) {
1436 1436
             return array();
@@ -1474,8 +1474,8 @@  discard block
 block discarded – undo
1474 1474
             $help_content = $this->_set_help_popup_content($help_array, false);
1475 1475
         }
1476 1476
         //let's setup the trigger
1477
-        $content = '<a class="ee-dialog" href="?height=' . $dimensions[0] . '&width=' . $dimensions[1] . '&inlineId=' . $trigger_id . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1478
-        $content = $content . $help_content;
1477
+        $content = '<a class="ee-dialog" href="?height='.$dimensions[0].'&width='.$dimensions[1].'&inlineId='.$trigger_id.'" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1478
+        $content = $content.$help_content;
1479 1479
         if ($display) {
1480 1480
             echo $content;
1481 1481
         } else {
@@ -1535,27 +1535,27 @@  discard block
 block discarded – undo
1535 1535
             add_action('admin_head', array($this, 'add_xdebug_style'));
1536 1536
         }
1537 1537
         // register all styles
1538
-        wp_register_style('espresso-ui-theme', EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css', array(), EVENT_ESPRESSO_VERSION);
1539
-        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1538
+        wp_register_style('espresso-ui-theme', EE_GLOBAL_ASSETS_URL.'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css', array(), EVENT_ESPRESSO_VERSION);
1539
+        wp_register_style('ee-admin-css', EE_ADMIN_URL.'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1540 1540
         //helpers styles
1541
-        wp_register_style('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css', array(), EVENT_ESPRESSO_VERSION);
1541
+        wp_register_style('ee-text-links', EE_PLUGIN_DIR_URL.'core/helpers/assets/ee_text_list_helper.css', array(), EVENT_ESPRESSO_VERSION);
1542 1542
         /** SCRIPTS **/
1543 1543
         //register all scripts
1544
-        wp_register_script('ee-dialog', EE_ADMIN_URL . 'assets/ee-dialog-helper.js', array('jquery', 'jquery-ui-draggable'), EVENT_ESPRESSO_VERSION, true);
1545
-        wp_register_script('ee_admin_js', EE_ADMIN_URL . 'assets/ee-admin-page.js', array('espresso_core', 'ee-parse-uri', 'ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1546
-        wp_register_script('jquery-ui-timepicker-addon', EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker', 'jquery-ui-slider'), EVENT_ESPRESSO_VERSION, true);
1544
+        wp_register_script('ee-dialog', EE_ADMIN_URL.'assets/ee-dialog-helper.js', array('jquery', 'jquery-ui-draggable'), EVENT_ESPRESSO_VERSION, true);
1545
+        wp_register_script('ee_admin_js', EE_ADMIN_URL.'assets/ee-admin-page.js', array('espresso_core', 'ee-parse-uri', 'ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1546
+        wp_register_script('jquery-ui-timepicker-addon', EE_GLOBAL_ASSETS_URL.'scripts/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker', 'jquery-ui-slider'), EVENT_ESPRESSO_VERSION, true);
1547 1547
         add_filter('FHEE_load_joyride', '__return_true');
1548 1548
         //script for sorting tables
1549
-        wp_register_script('espresso_ajax_table_sorting', EE_ADMIN_URL . "assets/espresso_ajax_table_sorting.js", array('ee_admin_js', 'jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
1549
+        wp_register_script('espresso_ajax_table_sorting', EE_ADMIN_URL."assets/espresso_ajax_table_sorting.js", array('ee_admin_js', 'jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
1550 1550
         //script for parsing uri's
1551
-        wp_register_script('ee-parse-uri', EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js', array(), EVENT_ESPRESSO_VERSION, true);
1551
+        wp_register_script('ee-parse-uri', EE_GLOBAL_ASSETS_URL.'scripts/parseuri.js', array(), EVENT_ESPRESSO_VERSION, true);
1552 1552
         //and parsing associative serialized form elements
1553
-        wp_register_script('ee-serialize-full-array', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1553
+        wp_register_script('ee-serialize-full-array', EE_GLOBAL_ASSETS_URL.'scripts/jquery.serializefullarray.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1554 1554
         //helpers scripts
1555
-        wp_register_script('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1556
-        wp_register_script('ee-moment-core', EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js', array(), EVENT_ESPRESSO_VERSION, true);
1557
-        wp_register_script('ee-moment', EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js', array('ee-moment-core'), EVENT_ESPRESSO_VERSION, true);
1558
-        wp_register_script('ee-datepicker', EE_ADMIN_URL . 'assets/ee-datepicker.js', array('jquery-ui-timepicker-addon', 'ee-moment'), EVENT_ESPRESSO_VERSION, true);
1555
+        wp_register_script('ee-text-links', EE_PLUGIN_DIR_URL.'core/helpers/assets/ee_text_list_helper.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1556
+        wp_register_script('ee-moment-core', EE_THIRD_PARTY_URL.'moment/moment-with-locales.min.js', array(), EVENT_ESPRESSO_VERSION, true);
1557
+        wp_register_script('ee-moment', EE_THIRD_PARTY_URL.'moment/moment-timezone-with-data.min.js', array('ee-moment-core'), EVENT_ESPRESSO_VERSION, true);
1558
+        wp_register_script('ee-datepicker', EE_ADMIN_URL.'assets/ee-datepicker.js', array('jquery-ui-timepicker-addon', 'ee-moment'), EVENT_ESPRESSO_VERSION, true);
1559 1559
         //google charts
1560 1560
         wp_register_script('google-charts', 'https://www.gstatic.com/charts/loader.js', array(), EVENT_ESPRESSO_VERSION, false);
1561 1561
         // ENQUEUE ALL BASICS BY DEFAULT
@@ -1579,7 +1579,7 @@  discard block
 block discarded – undo
1579 1579
          */
1580 1580
         if ( ! empty($this->_help_tour)) {
1581 1581
             //register the js for kicking things off
1582
-            wp_enqueue_script('ee-help-tour', EE_ADMIN_URL . 'assets/ee-help-tour.js', array('jquery-joyride'), EVENT_ESPRESSO_VERSION, true);
1582
+            wp_enqueue_script('ee-help-tour', EE_ADMIN_URL.'assets/ee-help-tour.js', array('jquery-joyride'), EVENT_ESPRESSO_VERSION, true);
1583 1583
             //setup tours for the js tour object
1584 1584
             foreach ($this->_help_tour['tours'] as $tour) {
1585 1585
                 $tours[] = array(
@@ -1674,17 +1674,17 @@  discard block
 block discarded – undo
1674 1674
             return;
1675 1675
         } //not a list_table view so get out.
1676 1676
         //list table functions are per view specific (because some admin pages might have more than one listtable!)
1677
-        if (call_user_func(array($this, '_set_list_table_views_' . $this->_req_action)) === false) {
1677
+        if (call_user_func(array($this, '_set_list_table_views_'.$this->_req_action)) === false) {
1678 1678
             //user error msg
1679 1679
             $error_msg = __('An error occurred. The requested list table views could not be found.', 'event_espresso');
1680 1680
             //developer error msg
1681
-            $error_msg .= '||' . sprintf(__('List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.', 'event_espresso'),
1682
-                            $this->_req_action, '_set_list_table_views_' . $this->_req_action);
1681
+            $error_msg .= '||'.sprintf(__('List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.', 'event_espresso'),
1682
+                            $this->_req_action, '_set_list_table_views_'.$this->_req_action);
1683 1683
             throw new EE_Error($error_msg);
1684 1684
         }
1685 1685
         //let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
1686
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action, $this->_views);
1687
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
1686
+        $this->_views = apply_filters('FHEE_list_table_views_'.$this->page_slug.'_'.$this->_req_action, $this->_views);
1687
+        $this->_views = apply_filters('FHEE_list_table_views_'.$this->page_slug, $this->_views);
1688 1688
         $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
1689 1689
         $this->_set_list_table_view();
1690 1690
         $this->_set_list_table_object();
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
             // check for current view
1760 1760
             $this->_views[$key]['class'] = $this->_view == $view['slug'] ? 'current' : '';
1761 1761
             $query_args['action'] = $this->_req_action;
1762
-            $query_args[$this->_req_action . '_nonce'] = wp_create_nonce($query_args['action'] . '_nonce');
1762
+            $query_args[$this->_req_action.'_nonce'] = wp_create_nonce($query_args['action'].'_nonce');
1763 1763
             $query_args['status'] = $view['slug'];
1764 1764
             //merge any other arguments sent in.
1765 1765
             if (isset($extra_query_args[$view['slug']])) {
@@ -1797,14 +1797,14 @@  discard block
 block discarded – undo
1797 1797
 					<select id="entries-per-page-slct" name="entries-per-page-slct">';
1798 1798
         foreach ($values as $value) {
1799 1799
             if ($value < $max_entries) {
1800
-                $selected = $value == $per_page ? ' selected="' . $per_page . '"' : '';
1800
+                $selected = $value == $per_page ? ' selected="'.$per_page.'"' : '';
1801 1801
                 $entries_per_page_dropdown .= '
1802
-						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
1802
+						<option value="' . $value.'"'.$selected.'>'.$value.'&nbsp;&nbsp;</option>';
1803 1803
             }
1804 1804
         }
1805
-        $selected = $max_entries == $per_page ? ' selected="' . $per_page . '"' : '';
1805
+        $selected = $max_entries == $per_page ? ' selected="'.$per_page.'"' : '';
1806 1806
         $entries_per_page_dropdown .= '
1807
-						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
1807
+						<option value="' . $max_entries.'"'.$selected.'>All&nbsp;&nbsp;</option>';
1808 1808
         $entries_per_page_dropdown .= '
1809 1809
 					</select>
1810 1810
 					entries
@@ -1826,7 +1826,7 @@  discard block
 block discarded – undo
1826 1826
     public function _set_search_attributes()
1827 1827
     {
1828 1828
         $this->_template_args['search']['btn_label'] = sprintf(__('Search %s', 'event_espresso'), empty($this->_search_btn_label) ? $this->page_label : $this->_search_btn_label);
1829
-        $this->_template_args['search']['callback'] = 'search_' . $this->page_slug;
1829
+        $this->_template_args['search']['callback'] = 'search_'.$this->page_slug;
1830 1830
     }
1831 1831
 
1832 1832
     /*** END LIST TABLE METHODS **/
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
                     // user error msg
1865 1865
                     $error_msg = __('An error occurred. The  requested metabox could not be found.', 'event_espresso');
1866 1866
                     // developer error msg
1867
-                    $error_msg .= '||' . sprintf(
1867
+                    $error_msg .= '||'.sprintf(
1868 1868
                                     __(
1869 1869
                                             'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
1870 1870
                                             'event_espresso'
@@ -1894,15 +1894,15 @@  discard block
 block discarded – undo
1894 1894
                 && is_array($this->_route_config['columns'])
1895 1895
                 && count($this->_route_config['columns']) === 2
1896 1896
         ) {
1897
-            add_screen_option('layout_columns', array('max' => (int)$this->_route_config['columns'][0], 'default' => (int)$this->_route_config['columns'][1]));
1897
+            add_screen_option('layout_columns', array('max' => (int) $this->_route_config['columns'][0], 'default' => (int) $this->_route_config['columns'][1]));
1898 1898
             $this->_template_args['num_columns'] = $this->_route_config['columns'][0];
1899 1899
             $screen_id = $this->_current_screen->id;
1900
-            $screen_columns = (int)get_user_option("screen_layout_$screen_id");
1900
+            $screen_columns = (int) get_user_option("screen_layout_$screen_id");
1901 1901
             $total_columns = ! empty($screen_columns) ? $screen_columns : $this->_route_config['columns'][1];
1902
-            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
1902
+            $this->_template_args['current_screen_widget_class'] = 'columns-'.$total_columns;
1903 1903
             $this->_template_args['current_page'] = $this->_wp_page_slug;
1904 1904
             $this->_template_args['screen'] = $this->_current_screen;
1905
-            $this->_column_template_path = EE_ADMIN_TEMPLATE . 'admin_details_metabox_column_wrapper.template.php';
1905
+            $this->_column_template_path = EE_ADMIN_TEMPLATE.'admin_details_metabox_column_wrapper.template.php';
1906 1906
             //finally if we don't have has_metaboxes set in the route config let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
1907 1907
             $this->_route_config['has_metaboxes'] = true;
1908 1908
         }
@@ -1949,7 +1949,7 @@  discard block
 block discarded – undo
1949 1949
      */
1950 1950
     public function espresso_ratings_request()
1951 1951
     {
1952
-        $template_path = EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php';
1952
+        $template_path = EE_ADMIN_TEMPLATE.'espresso_ratings_request_content.template.php';
1953 1953
         EEH_Template::display_template($template_path, array());
1954 1954
     }
1955 1955
 
@@ -1957,18 +1957,18 @@  discard block
 block discarded – undo
1957 1957
 
1958 1958
     public static function cached_rss_display($rss_id, $url)
1959 1959
     {
1960
-        $loading = '<p class="widget-loading hide-if-no-js">' . __('Loading&#8230;') . '</p><p class="hide-if-js">' . __('This widget requires JavaScript.') . '</p>';
1960
+        $loading = '<p class="widget-loading hide-if-no-js">'.__('Loading&#8230;').'</p><p class="hide-if-js">'.__('This widget requires JavaScript.').'</p>';
1961 1961
         $doing_ajax = (defined('DOING_AJAX') && DOING_AJAX);
1962
-        $pre = '<div class="espresso-rss-display">' . "\n\t";
1963
-        $pre .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
1964
-        $post = '</div>' . "\n";
1965
-        $cache_key = 'ee_rss_' . md5($rss_id);
1962
+        $pre = '<div class="espresso-rss-display">'."\n\t";
1963
+        $pre .= '<span id="'.$rss_id.'_url" class="hidden">'.$url.'</span>';
1964
+        $post = '</div>'."\n";
1965
+        $cache_key = 'ee_rss_'.md5($rss_id);
1966 1966
         if (false != ($output = get_transient($cache_key))) {
1967
-            echo $pre . $output . $post;
1967
+            echo $pre.$output.$post;
1968 1968
             return true;
1969 1969
         }
1970 1970
         if ( ! $doing_ajax) {
1971
-            echo $pre . $loading . $post;
1971
+            echo $pre.$loading.$post;
1972 1972
             return false;
1973 1973
         }
1974 1974
         ob_start();
@@ -2027,7 +2027,7 @@  discard block
 block discarded – undo
2027 2027
 
2028 2028
     public function espresso_sponsors_post_box()
2029 2029
     {
2030
-        $templatepath = EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php';
2030
+        $templatepath = EE_ADMIN_TEMPLATE.'admin_general_metabox_contents_espresso_sponsors.template.php';
2031 2031
         EEH_Template::display_template($templatepath);
2032 2032
     }
2033 2033
 
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
 
2036 2036
     private function _publish_post_box()
2037 2037
     {
2038
-        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2038
+        $meta_box_ref = 'espresso_'.$this->page_slug.'_editor_overview';
2039 2039
         //if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array then we'll use that for the metabox label.  Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2040 2040
         if ( ! empty($this->_labels['publishbox'])) {
2041 2041
             $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
@@ -2052,7 +2052,7 @@  discard block
 block discarded – undo
2052 2052
     {
2053 2053
         //if we have extra content set let's add it in if not make sure its empty
2054 2054
         $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content']) ? $this->_template_args['publish_box_extra_content'] : '';
2055
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php';
2055
+        $template_path = EE_ADMIN_TEMPLATE.'admin_details_publish_metabox.template.php';
2056 2056
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2057 2057
     }
2058 2058
 
@@ -2221,7 +2221,7 @@  discard block
 block discarded – undo
2221 2221
         //if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2222 2222
         $call_back_func = $create_func ? create_function('$post, $metabox',
2223 2223
                 'do_action( "AHEE_log", __FILE__, __FUNCTION__, ""); echo EEH_Template::display_template( $metabox["args"]["template_path"], $metabox["args"]["template_args"], TRUE );') : $callback;
2224
-        add_meta_box(str_replace('_', '-', $action) . '-mbox', $title, $call_back_func, $this->_wp_page_slug, $column, $priority, $callback_args);
2224
+        add_meta_box(str_replace('_', '-', $action).'-mbox', $title, $call_back_func, $this->_wp_page_slug, $column, $priority, $callback_args);
2225 2225
     }
2226 2226
 
2227 2227
 
@@ -2302,9 +2302,9 @@  discard block
 block discarded – undo
2302 2302
                 : 'espresso-default-admin';
2303 2303
         $template_path = $sidebar
2304 2304
                 ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2305
-                : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2305
+                : EE_ADMIN_TEMPLATE.'admin_details_wrapper_no_sidebar.template.php';
2306 2306
         if (defined('DOING_AJAX') && DOING_AJAX) {
2307
-            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2307
+            $template_path = EE_ADMIN_TEMPLATE.'admin_details_wrapper_no_sidebar_ajax.template.php';
2308 2308
         }
2309 2309
         $template_path = ! empty($this->_column_template_path) ? $this->_column_template_path : $template_path;
2310 2310
         $this->_template_args['post_body_content'] = isset($this->_template_args['admin_page_content']) ? $this->_template_args['admin_page_content'] : '';
@@ -2350,7 +2350,7 @@  discard block
 block discarded – undo
2350 2350
                         true
2351 2351
                 )
2352 2352
                 : $this->_template_args['preview_action_button'];
2353
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php';
2353
+        $template_path = EE_ADMIN_TEMPLATE.'admin_caf_full_page_preview.template.php';
2354 2354
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2355 2355
                 $template_path,
2356 2356
                 $this->_template_args,
@@ -2401,7 +2401,7 @@  discard block
 block discarded – undo
2401 2401
         //setup search attributes
2402 2402
         $this->_set_search_attributes();
2403 2403
         $this->_template_args['current_page'] = $this->_wp_page_slug;
2404
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2404
+        $template_path = EE_ADMIN_TEMPLATE.'admin_list_wrapper.template.php';
2405 2405
         $this->_template_args['table_url'] = defined('DOING_AJAX')
2406 2406
                 ? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
2407 2407
                 : add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
@@ -2411,29 +2411,29 @@  discard block
 block discarded – undo
2411 2411
         $ajax_sorting_callback = $this->_list_table_object->get_ajax_sorting_callback();
2412 2412
         if ( ! empty($ajax_sorting_callback)) {
2413 2413
             $sortable_list_table_form_fields = wp_nonce_field(
2414
-                    $ajax_sorting_callback . '_nonce',
2415
-                    $ajax_sorting_callback . '_nonce',
2414
+                    $ajax_sorting_callback.'_nonce',
2415
+                    $ajax_sorting_callback.'_nonce',
2416 2416
                     false,
2417 2417
                     false
2418 2418
             );
2419 2419
             //			$reorder_action = 'espresso_' . $ajax_sorting_callback . '_nonce';
2420 2420
             //			$sortable_list_table_form_fields = wp_nonce_field( $reorder_action, 'ajax_table_sort_nonce', FALSE, FALSE );
2421
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="' . $this->page_slug . '" />';
2422
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="' . $ajax_sorting_callback . '" />';
2421
+            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'.$this->page_slug.'" />';
2422
+            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'.$ajax_sorting_callback.'" />';
2423 2423
         } else {
2424 2424
             $sortable_list_table_form_fields = '';
2425 2425
         }
2426 2426
         $this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
2427 2427
         $hidden_form_fields = isset($this->_template_args['list_table_hidden_fields']) ? $this->_template_args['list_table_hidden_fields'] : '';
2428
-        $nonce_ref = $this->_req_action . '_nonce';
2429
-        $hidden_form_fields .= '<input type="hidden" name="' . $nonce_ref . '" value="' . wp_create_nonce($nonce_ref) . '">';
2428
+        $nonce_ref = $this->_req_action.'_nonce';
2429
+        $hidden_form_fields .= '<input type="hidden" name="'.$nonce_ref.'" value="'.wp_create_nonce($nonce_ref).'">';
2430 2430
         $this->_template_args['list_table_hidden_fields'] = $hidden_form_fields;
2431 2431
         //display message about search results?
2432 2432
         $this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
2433
-                ? '<p class="ee-search-results">' . sprintf(
2433
+                ? '<p class="ee-search-results">'.sprintf(
2434 2434
                         esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
2435 2435
                         trim($this->_req_data['s'], '%')
2436
-                ) . '</p>'
2436
+                ).'</p>'
2437 2437
                 : '';
2438 2438
         // filter before_list_table template arg
2439 2439
         $this->_template_args['before_list_table'] = apply_filters(
@@ -2507,8 +2507,8 @@  discard block
 block discarded – undo
2507 2507
      */
2508 2508
     protected function _display_legend($items)
2509 2509
     {
2510
-        $this->_template_args['items'] = apply_filters('FHEE__EE_Admin_Page___display_legend__items', (array)$items, $this);
2511
-        $legend_template = EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php';
2510
+        $this->_template_args['items'] = apply_filters('FHEE__EE_Admin_Page___display_legend__items', (array) $items, $this);
2511
+        $legend_template = EE_ADMIN_TEMPLATE.'admin_details_legend.template.php';
2512 2512
         return EEH_Template::display_template($legend_template, $this->_template_args, true);
2513 2513
     }
2514 2514
 
@@ -2600,13 +2600,13 @@  discard block
 block discarded – undo
2600 2600
         $this->_nav_tabs = $this->_get_main_nav_tabs();
2601 2601
         $this->_template_args['nav_tabs'] = $this->_nav_tabs;
2602 2602
         $this->_template_args['admin_page_title'] = $this->_admin_page_title;
2603
-        $this->_template_args['before_admin_page_content'] = apply_filters('FHEE_before_admin_page_content' . $this->_current_page . $this->_current_view,
2603
+        $this->_template_args['before_admin_page_content'] = apply_filters('FHEE_before_admin_page_content'.$this->_current_page.$this->_current_view,
2604 2604
                 isset($this->_template_args['before_admin_page_content']) ? $this->_template_args['before_admin_page_content'] : '');
2605
-        $this->_template_args['after_admin_page_content'] = apply_filters('FHEE_after_admin_page_content' . $this->_current_page . $this->_current_view,
2605
+        $this->_template_args['after_admin_page_content'] = apply_filters('FHEE_after_admin_page_content'.$this->_current_page.$this->_current_view,
2606 2606
                 isset($this->_template_args['after_admin_page_content']) ? $this->_template_args['after_admin_page_content'] : '');
2607 2607
         $this->_template_args['after_admin_page_content'] .= $this->_set_help_popup_content();
2608 2608
         // load settings page wrapper template
2609
-        $template_path = ! defined('DOING_AJAX') ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php' : EE_ADMIN_TEMPLATE . 'admin_wrapper_ajax.template.php';
2609
+        $template_path = ! defined('DOING_AJAX') ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php' : EE_ADMIN_TEMPLATE.'admin_wrapper_ajax.template.php';
2610 2610
         //about page?
2611 2611
         $template_path = $about ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php' : $template_path;
2612 2612
         if (defined('DOING_AJAX')) {
@@ -2680,20 +2680,20 @@  discard block
 block discarded – undo
2680 2680
     protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
2681 2681
     {
2682 2682
         //make sure $text and $actions are in an array
2683
-        $text = (array)$text;
2684
-        $actions = (array)$actions;
2683
+        $text = (array) $text;
2684
+        $actions = (array) $actions;
2685 2685
         $referrer_url = empty($referrer) ? '' : $referrer;
2686
-        $referrer_url = ! $referrer ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $_SERVER['REQUEST_URI'] . '" />'
2687
-                : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $referrer . '" />';
2686
+        $referrer_url = ! $referrer ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'.$_SERVER['REQUEST_URI'].'" />'
2687
+                : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'.$referrer.'" />';
2688 2688
         $button_text = ! empty($text) ? $text : array(__('Save', 'event_espresso'), __('Save and Close', 'event_espresso'));
2689 2689
         $default_names = array('save', 'save_and_close');
2690 2690
         //add in a hidden index for the current page (so save and close redirects properly)
2691 2691
         $this->_template_args['save_buttons'] = $referrer_url;
2692 2692
         foreach ($button_text as $key => $button) {
2693 2693
             $ref = $default_names[$key];
2694
-            $id = $this->_current_view . '_' . $ref;
2694
+            $id = $this->_current_view.'_'.$ref;
2695 2695
             $name = ! empty($actions) ? $actions[$key] : $ref;
2696
-            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary ' . $ref . '" value="' . $button . '" name="' . $name . '" id="' . $id . '" />';
2696
+            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '.$ref.'" value="'.$button.'" name="'.$name.'" id="'.$id.'" />';
2697 2697
             if ( ! $both) {
2698 2698
                 break;
2699 2699
             }
@@ -2729,15 +2729,15 @@  discard block
 block discarded – undo
2729 2729
     {
2730 2730
         if (empty($route)) {
2731 2731
             $user_msg = __('An error occurred. No action was set for this page\'s form.', 'event_espresso');
2732
-            $dev_msg = $user_msg . "\n" . sprintf(__('The $route argument is required for the %s->%s method.', 'event_espresso'), __FUNCTION__, __CLASS__);
2733
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
2732
+            $dev_msg = $user_msg."\n".sprintf(__('The $route argument is required for the %s->%s method.', 'event_espresso'), __FUNCTION__, __CLASS__);
2733
+            EE_Error::add_error($user_msg.'||'.$dev_msg, __FILE__, __FUNCTION__, __LINE__);
2734 2734
         }
2735 2735
         // open form
2736
-        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="' . $this->_admin_base_url . '" id="' . $route . '_event_form" >';
2736
+        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'.$this->_admin_base_url.'" id="'.$route.'_event_form" >';
2737 2737
         // add nonce
2738
-        $nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
2738
+        $nonce = wp_nonce_field($route.'_nonce', $route.'_nonce', false, false);
2739 2739
         //		$nonce = wp_nonce_field( $route . '_nonce', '_wpnonce', FALSE, FALSE );
2740
-        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
2740
+        $this->_template_args['before_admin_page_content'] .= "\n\t".$nonce;
2741 2741
         // add REQUIRED form action
2742 2742
         $hidden_fields = array(
2743 2743
                 'action' => array('type' => 'hidden', 'value' => $route),
@@ -2747,8 +2747,8 @@  discard block
 block discarded – undo
2747 2747
         // generate form fields
2748 2748
         $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
2749 2749
         // add fields to form
2750
-        foreach ((array)$form_fields as $field_name => $form_field) {
2751
-            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
2750
+        foreach ((array) $form_fields as $field_name => $form_field) {
2751
+            $this->_template_args['before_admin_page_content'] .= "\n\t".$form_field['field'];
2752 2752
         }
2753 2753
         // close form
2754 2754
         $this->_template_args['after_admin_page_content'] = '</form>';
@@ -2829,7 +2829,7 @@  discard block
 block discarded – undo
2829 2829
          * @param array $query_args       The original query_args array coming into the
2830 2830
          *                                method.
2831 2831
          */
2832
-        do_action('AHEE__' . $classname . '___redirect_after_action__before_redirect_modification_' . $this->_req_action, $query_args);
2832
+        do_action('AHEE__'.$classname.'___redirect_after_action__before_redirect_modification_'.$this->_req_action, $query_args);
2833 2833
         //calculate where we're going (if we have a "save and close" button pushed)
2834 2834
         if (isset($this->_req_data['save_and_close']) && isset($this->_req_data['save_and_close_referrer'])) {
2835 2835
             // even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
@@ -2845,7 +2845,7 @@  discard block
 block discarded – undo
2845 2845
             foreach ($this->_default_route_query_args as $query_param => $query_value) {
2846 2846
                 //is there a wp_referer array in our _default_route_query_args property?
2847 2847
                 if ($query_param == 'wp_referer') {
2848
-                    $query_value = (array)$query_value;
2848
+                    $query_value = (array) $query_value;
2849 2849
                     foreach ($query_value as $reference => $value) {
2850 2850
                         if (strpos($reference, 'nonce') !== false) {
2851 2851
                             continue;
@@ -2871,11 +2871,11 @@  discard block
 block discarded – undo
2871 2871
         // if redirecting to anything other than the main page, add a nonce
2872 2872
         if (isset($query_args['action'])) {
2873 2873
             // manually generate wp_nonce and merge that with the query vars becuz the wp_nonce_url function wrecks havoc on some vars
2874
-            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
2874
+            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'].'_nonce');
2875 2875
         }
2876 2876
         //we're adding some hooks and filters in here for processing any things just before redirects (example: an admin page has done an insert or update and we want to run something after that).
2877
-        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
2878
-        $redirect_url = apply_filters('FHEE_redirect_' . $classname . $this->_req_action, self::add_query_args_and_nonce($query_args, $redirect_url), $query_args);
2877
+        do_action('AHEE_redirect_'.$classname.$this->_req_action, $query_args);
2878
+        $redirect_url = apply_filters('FHEE_redirect_'.$classname.$this->_req_action, self::add_query_args_and_nonce($query_args, $redirect_url), $query_args);
2879 2879
         // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
2880 2880
         if (defined('DOING_AJAX')) {
2881 2881
             $default_data = array(
@@ -3005,7 +3005,7 @@  discard block
 block discarded – undo
3005 3005
         $args = array(
3006 3006
                 'label'   => $this->_admin_page_title,
3007 3007
                 'default' => 10,
3008
-                'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3008
+                'option'  => $this->_current_page.'_'.$this->_current_view.'_per_page',
3009 3009
         );
3010 3010
         //ONLY add the screen option if the user has access to it.
3011 3011
         if ($this->check_user_access($this->_current_view, true)) {
@@ -3038,8 +3038,8 @@  discard block
 block discarded – undo
3038 3038
             $map_option = $option;
3039 3039
             $option = str_replace('-', '_', $option);
3040 3040
             switch ($map_option) {
3041
-                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3042
-                    $value = (int)$value;
3041
+                case $this->_current_page.'_'.$this->_current_view.'_per_page':
3042
+                    $value = (int) $value;
3043 3043
                     if ($value < 1 || $value > 999) {
3044 3044
                         return;
3045 3045
                     }
@@ -3066,7 +3066,7 @@  discard block
 block discarded – undo
3066 3066
      */
3067 3067
     public function set_template_args($data)
3068 3068
     {
3069
-        $this->_template_args = array_merge($this->_template_args, (array)$data);
3069
+        $this->_template_args = array_merge($this->_template_args, (array) $data);
3070 3070
     }
3071 3071
 
3072 3072
 
@@ -3088,12 +3088,12 @@  discard block
 block discarded – undo
3088 3088
             $this->_verify_route($route);
3089 3089
         }
3090 3090
         //now let's set the string for what kind of transient we're setting
3091
-        $transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3091
+        $transient = $notices ? 'ee_rte_n_tx_'.$route.'_'.$user_id : 'rte_tx_'.$route.'_'.$user_id;
3092 3092
         $data = $notices ? array('notices' => $data) : $data;
3093 3093
         //is there already a transient for this route?  If there is then let's ADD to that transient
3094 3094
         $existing = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3095 3095
         if ($existing) {
3096
-            $data = array_merge((array)$data, (array)$existing);
3096
+            $data = array_merge((array) $data, (array) $existing);
3097 3097
         }
3098 3098
         if (is_multisite() && is_network_admin()) {
3099 3099
             set_site_transient($transient, $data, 8);
@@ -3114,7 +3114,7 @@  discard block
 block discarded – undo
3114 3114
     {
3115 3115
         $user_id = get_current_user_id();
3116 3116
         $route = ! $route ? $this->_req_action : $route;
3117
-        $transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3117
+        $transient = $notices ? 'ee_rte_n_tx_'.$route.'_'.$user_id : 'rte_tx_'.$route.'_'.$user_id;
3118 3118
         $data = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3119 3119
         //delete transient after retrieval (just in case it hasn't expired);
3120 3120
         if (is_multisite() && is_network_admin()) {
@@ -3355,7 +3355,7 @@  discard block
 block discarded – undo
3355 3355
      */
3356 3356
     protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
3357 3357
     {
3358
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
3358
+        return '<a class="'.$class.'" href="'.$url.'"></a>';
3359 3359
     }
3360 3360
 
3361 3361
 
@@ -3369,7 +3369,7 @@  discard block
 block discarded – undo
3369 3369
      */
3370 3370
     protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
3371 3371
     {
3372
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
3372
+        return '<a class="'.$class.'" href="'.$url.'"></a>';
3373 3373
     }
3374 3374
 
3375 3375
 
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 2 patches
Indentation   +1490 added lines, -1490 removed lines patch added patch discarded remove patch
@@ -18,1496 +18,1496 @@
 block discarded – undo
18 18
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
19 19
 {
20 20
 
21
-    /**
22
-     * for children line items (currently not a normal relation)
23
-     *
24
-     * @type EE_Line_Item[]
25
-     */
26
-    protected $_children = array();
27
-
28
-    /**
29
-     * for the parent line item
30
-     *
31
-     * @var EE_Line_Item
32
-     */
33
-    protected $_parent;
34
-
35
-
36
-
37
-    /**
38
-     *
39
-     * @param array  $props_n_values          incoming values
40
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
-     *                                        used.)
42
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
-     *                                        date_format and the second value is the time format
44
-     * @return EE_Line_Item
45
-     * @throws EE_Error
46
-     */
47
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
48
-    {
49
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
50
-        return $has_object
51
-            ? $has_object
52
-            : new self($props_n_values, false, $timezone);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values  incoming values from the database
59
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
-     *                                the website will be used.
61
-     * @return EE_Line_Item
62
-     * @throws EE_Error
63
-     */
64
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
65
-    {
66
-        return new self($props_n_values, true, $timezone);
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     * Adds some defaults if they're not specified
73
-     *
74
-     * @param array  $fieldValues
75
-     * @param bool   $bydb
76
-     * @param string $timezone
77
-     * @throws EE_Error
78
-     */
79
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
80
-    {
81
-        parent::__construct($fieldValues, $bydb, $timezone);
82
-        if (! $this->get('LIN_code')) {
83
-            $this->set_code($this->generate_code());
84
-        }
85
-    }
86
-
87
-
88
-
89
-    /**
90
-     * Gets ID
91
-     *
92
-     * @return int
93
-     * @throws EE_Error
94
-     */
95
-    public function ID()
96
-    {
97
-        return $this->get('LIN_ID');
98
-    }
99
-
100
-
101
-
102
-    /**
103
-     * Gets TXN_ID
104
-     *
105
-     * @return int
106
-     * @throws EE_Error
107
-     */
108
-    public function TXN_ID()
109
-    {
110
-        return $this->get('TXN_ID');
111
-    }
112
-
113
-
114
-
115
-    /**
116
-     * Sets TXN_ID
117
-     *
118
-     * @param int $TXN_ID
119
-     * @throws EE_Error
120
-     */
121
-    public function set_TXN_ID($TXN_ID)
122
-    {
123
-        $this->set('TXN_ID', $TXN_ID);
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * Gets name
130
-     *
131
-     * @return string
132
-     * @throws EE_Error
133
-     */
134
-    public function name()
135
-    {
136
-        $name = $this->get('LIN_name');
137
-        if (! $name) {
138
-            $name = ucwords(str_replace('-', ' ', $this->type()));
139
-        }
140
-        return $name;
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     * Sets name
147
-     *
148
-     * @param string $name
149
-     * @throws EE_Error
150
-     */
151
-    public function set_name($name)
152
-    {
153
-        $this->set('LIN_name', $name);
154
-    }
155
-
156
-
157
-
158
-    /**
159
-     * Gets desc
160
-     *
161
-     * @return string
162
-     * @throws EE_Error
163
-     */
164
-    public function desc()
165
-    {
166
-        return $this->get('LIN_desc');
167
-    }
168
-
169
-
170
-
171
-    /**
172
-     * Sets desc
173
-     *
174
-     * @param string $desc
175
-     * @throws EE_Error
176
-     */
177
-    public function set_desc($desc)
178
-    {
179
-        $this->set('LIN_desc', $desc);
180
-    }
181
-
182
-
183
-
184
-    /**
185
-     * Gets quantity
186
-     *
187
-     * @return int
188
-     * @throws EE_Error
189
-     */
190
-    public function quantity()
191
-    {
192
-        return $this->get('LIN_quantity');
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * Sets quantity
199
-     *
200
-     * @param int $quantity
201
-     * @throws EE_Error
202
-     */
203
-    public function set_quantity($quantity)
204
-    {
205
-        $this->set('LIN_quantity', max($quantity, 0));
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     * Gets item_id
212
-     *
213
-     * @return string
214
-     * @throws EE_Error
215
-     */
216
-    public function OBJ_ID()
217
-    {
218
-        return $this->get('OBJ_ID');
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * Sets item_id
225
-     *
226
-     * @param string $item_id
227
-     * @throws EE_Error
228
-     */
229
-    public function set_OBJ_ID($item_id)
230
-    {
231
-        $this->set('OBJ_ID', $item_id);
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * Gets item_type
238
-     *
239
-     * @return string
240
-     * @throws EE_Error
241
-     */
242
-    public function OBJ_type()
243
-    {
244
-        return $this->get('OBJ_type');
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Gets item_type
251
-     *
252
-     * @return string
253
-     * @throws EE_Error
254
-     */
255
-    public function OBJ_type_i18n()
256
-    {
257
-        $obj_type = $this->OBJ_type();
258
-        switch ($obj_type) {
259
-            case 'Event':
260
-                $obj_type = __('Event', 'event_espresso');
261
-                break;
262
-            case 'Price':
263
-                $obj_type = __('Price', 'event_espresso');
264
-                break;
265
-            case 'Promotion':
266
-                $obj_type = __('Promotion', 'event_espresso');
267
-                break;
268
-            case 'Ticket':
269
-                $obj_type = __('Ticket', 'event_espresso');
270
-                break;
271
-            case 'Transaction':
272
-                $obj_type = __('Transaction', 'event_espresso');
273
-                break;
274
-        }
275
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * Sets item_type
282
-     *
283
-     * @param string $OBJ_type
284
-     * @throws EE_Error
285
-     */
286
-    public function set_OBJ_type($OBJ_type)
287
-    {
288
-        $this->set('OBJ_type', $OBJ_type);
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * Gets unit_price
295
-     *
296
-     * @return float
297
-     * @throws EE_Error
298
-     */
299
-    public function unit_price()
300
-    {
301
-        return $this->get('LIN_unit_price');
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * Sets unit_price
308
-     *
309
-     * @param float $unit_price
310
-     * @throws EE_Error
311
-     */
312
-    public function set_unit_price($unit_price)
313
-    {
314
-        $this->set('LIN_unit_price', $unit_price);
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * Checks if this item is a percentage modifier or not
321
-     *
322
-     * @return boolean
323
-     * @throws EE_Error
324
-     */
325
-    public function is_percent()
326
-    {
327
-        if ($this->is_tax_sub_total()) {
328
-            //tax subtotals HAVE a percent on them, that percentage only applies
329
-            //to taxable items, so its' an exception. Treat it like a flat line item
330
-            return false;
331
-        }
332
-        $unit_price = abs($this->get('LIN_unit_price'));
333
-        $percent = abs($this->get('LIN_percent'));
334
-        if ($unit_price < .001 && $percent) {
335
-            return true;
336
-        }
337
-        if ($unit_price >= .001 && ! $percent) {
338
-            return false;
339
-        }
340
-        if ($unit_price >= .001 && $percent) {
341
-            throw new EE_Error(
342
-                sprintf(
343
-                    esc_html__('A Line Item can not have a unit price of (%s) AND a percent (%s)!', 'event_espresso'),
344
-                    $unit_price, $percent
345
-                )
346
-            );
347
-        }
348
-        // if they're both 0, assume its not a percent item
349
-        return false;
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * Gets percent (between 100-.001)
356
-     *
357
-     * @return float
358
-     * @throws EE_Error
359
-     */
360
-    public function percent()
361
-    {
362
-        return $this->get('LIN_percent');
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * Sets percent (between 100-0.01)
369
-     *
370
-     * @param float $percent
371
-     * @throws EE_Error
372
-     */
373
-    public function set_percent($percent)
374
-    {
375
-        $this->set('LIN_percent', $percent);
376
-    }
377
-
378
-
379
-
380
-    /**
381
-     * Gets total
382
-     *
383
-     * @return float
384
-     * @throws EE_Error
385
-     */
386
-    public function total()
387
-    {
388
-        return $this->get('LIN_total');
389
-    }
390
-
391
-
392
-
393
-    /**
394
-     * Sets total
395
-     *
396
-     * @param float $total
397
-     * @throws EE_Error
398
-     */
399
-    public function set_total($total)
400
-    {
401
-        $this->set('LIN_total', $total);
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * Gets order
408
-     *
409
-     * @return int
410
-     * @throws EE_Error
411
-     */
412
-    public function order()
413
-    {
414
-        return $this->get('LIN_order');
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * Sets order
421
-     *
422
-     * @param int $order
423
-     * @throws EE_Error
424
-     */
425
-    public function set_order($order)
426
-    {
427
-        $this->set('LIN_order', $order);
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * Gets parent
434
-     *
435
-     * @return int
436
-     * @throws EE_Error
437
-     */
438
-    public function parent_ID()
439
-    {
440
-        return $this->get('LIN_parent');
441
-    }
442
-
443
-
444
-
445
-    /**
446
-     * Sets parent
447
-     *
448
-     * @param int $parent
449
-     * @throws EE_Error
450
-     */
451
-    public function set_parent_ID($parent)
452
-    {
453
-        $this->set('LIN_parent', $parent);
454
-    }
455
-
456
-
457
-
458
-    /**
459
-     * Gets type
460
-     *
461
-     * @return string
462
-     * @throws EE_Error
463
-     */
464
-    public function type()
465
-    {
466
-        return $this->get('LIN_type');
467
-    }
468
-
469
-
470
-
471
-    /**
472
-     * Sets type
473
-     *
474
-     * @param string $type
475
-     * @throws EE_Error
476
-     */
477
-    public function set_type($type)
478
-    {
479
-        $this->set('LIN_type', $type);
480
-    }
481
-
482
-
483
-
484
-    /**
485
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
486
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
487
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
488
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
489
-     *
490
-     * @return EE_Base_Class|EE_Line_Item
491
-     * @throws EE_Error
492
-     */
493
-    public function parent()
494
-    {
495
-        return $this->ID()
496
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
497
-            : $this->_parent;
498
-    }
499
-
500
-
501
-
502
-    /**
503
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
504
-     *
505
-     * @return EE_Base_Class[]|EE_Line_Item[]
506
-     * @throws EE_Error
507
-     */
508
-    public function children()
509
-    {
510
-        if ($this->ID()) {
511
-            return $this->get_model()->get_all(
512
-                array(
513
-                    array('LIN_parent' => $this->ID()),
514
-                    'order_by' => array('LIN_order' => 'ASC'),
515
-                )
516
-            );
517
-        }
518
-        if (! is_array($this->_children)) {
519
-            $this->_children = array();
520
-        }
521
-        return $this->_children;
522
-    }
523
-
524
-
525
-
526
-    /**
527
-     * Gets code
528
-     *
529
-     * @return string
530
-     * @throws EE_Error
531
-     */
532
-    public function code()
533
-    {
534
-        return $this->get('LIN_code');
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Sets code
541
-     *
542
-     * @param string $code
543
-     * @throws EE_Error
544
-     */
545
-    public function set_code($code)
546
-    {
547
-        $this->set('LIN_code', $code);
548
-    }
549
-
550
-
551
-
552
-    /**
553
-     * Gets is_taxable
554
-     *
555
-     * @return boolean
556
-     * @throws EE_Error
557
-     */
558
-    public function is_taxable()
559
-    {
560
-        return $this->get('LIN_is_taxable');
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * Sets is_taxable
567
-     *
568
-     * @param boolean $is_taxable
569
-     * @throws EE_Error
570
-     */
571
-    public function set_is_taxable($is_taxable)
572
-    {
573
-        $this->set('LIN_is_taxable', $is_taxable);
574
-    }
575
-
576
-
577
-
578
-    /**
579
-     * Gets the object that this model-joins-to.
580
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
581
-     * EEM_Promotion_Object
582
-     *
583
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
584
-     *
585
-     * @return EE_Base_Class | NULL
586
-     * @throws EE_Error
587
-     */
588
-    public function get_object()
589
-    {
590
-        $model_name_of_related_obj = $this->OBJ_type();
591
-        return $this->get_model()->has_relation($model_name_of_related_obj)
592
-            ? $this->get_first_related($model_name_of_related_obj)
593
-            : null;
594
-    }
595
-
596
-
597
-
598
-    /**
599
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
600
-     * (IE, if this line item is for a price or something else, will return NULL)
601
-     *
602
-     * @param array $query_params
603
-     * @return EE_Base_Class|EE_Ticket
604
-     * @throws EE_Error
605
-     */
606
-    public function ticket($query_params = array())
607
-    {
608
-        //we're going to assume that when this method is called we always want to receive the attached ticket EVEN if that ticket is archived.  This can be overridden via the incoming $query_params argument
609
-        $remove_defaults = array('default_where_conditions' => 'none');
610
-        $query_params = array_merge($remove_defaults, $query_params);
611
-        return $this->get_first_related('Ticket', $query_params);
612
-    }
613
-
614
-
615
-
616
-    /**
617
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
618
-     *
619
-     * @return EE_Datetime | NULL
620
-     * @throws EE_Error
621
-     */
622
-    public function get_ticket_datetime()
623
-    {
624
-        if ($this->OBJ_type() === 'Ticket') {
625
-            $ticket = $this->ticket();
626
-            if ($ticket instanceof EE_Ticket) {
627
-                $datetime = $ticket->first_datetime();
628
-                if ($datetime instanceof EE_Datetime) {
629
-                    return $datetime;
630
-                }
631
-            }
632
-        }
633
-        return null;
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * Gets the event's name that's related to the ticket, if this is for
640
-     * a ticket
641
-     *
642
-     * @return string
643
-     * @throws EE_Error
644
-     */
645
-    public function ticket_event_name()
646
-    {
647
-        $event_name = esc_html__('Unknown', 'event_espresso');
648
-        $event = $this->ticket_event();
649
-        if ($event instanceof EE_Event) {
650
-            $event_name = $event->name();
651
-        }
652
-        return $event_name;
653
-    }
654
-
655
-
656
-    /**
657
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
658
-     *
659
-     * @return EE_Event|null
660
-     * @throws EE_Error
661
-     */
662
-    public function ticket_event()
663
-    {
664
-        $event = null;
665
-        $ticket = $this->ticket();
666
-        if ($ticket instanceof EE_Ticket) {
667
-            $datetime = $ticket->first_datetime();
668
-            if ($datetime instanceof EE_Datetime) {
669
-                $event = $datetime->event();
670
-            }
671
-        }
672
-        return $event;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * Gets the first datetime for this lien item, assuming it's for a ticket
679
-     *
680
-     * @param string $date_format
681
-     * @param string $time_format
682
-     * @return string
683
-     * @throws EE_Error
684
-     */
685
-    public function ticket_datetime_start($date_format = '', $time_format = '')
686
-    {
687
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
688
-        $datetime = $this->get_ticket_datetime();
689
-        if ($datetime) {
690
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
691
-        }
692
-        return $first_datetime_string;
693
-    }
694
-
695
-
696
-
697
-    /**
698
-     * Adds the line item as a child to this line item. If there is another child line
699
-     * item with the same LIN_code, it is overwritten by this new one
700
-     *
701
-     * @param EEI_Line_Item $line_item
702
-     * @param bool          $set_order
703
-     * @return bool success
704
-     * @throws EE_Error
705
-     */
706
-    public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
707
-    {
708
-        // should we calculate the LIN_order for this line item ?
709
-        if ($set_order || $line_item->order() === null) {
710
-            $line_item->set_order(count($this->children()));
711
-        }
712
-        if ($this->ID()) {
713
-            //check for any duplicate line items (with the same code), if so, this replaces it
714
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
715
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
716
-                $this->delete_child_line_item($line_item_with_same_code->code());
717
-            }
718
-            $line_item->set_parent_ID($this->ID());
719
-            if ($this->TXN_ID()) {
720
-                $line_item->set_TXN_ID($this->TXN_ID());
721
-            }
722
-            return $line_item->save();
723
-        }
724
-        $this->_children[$line_item->code()] = $line_item;
725
-        if ($line_item->parent() !== $this) {
726
-            $line_item->set_parent($this);
727
-        }
728
-        return true;
729
-    }
730
-
731
-
732
-    /**
733
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
734
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
735
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
736
-     * the EE_Line_Item::_parent property.
737
-     *
738
-     * @param EE_Line_Item $line_item
739
-     * @throws EE_Error
740
-     */
741
-    public function set_parent($line_item)
742
-    {
743
-        if ($this->ID()) {
744
-            if (! $line_item->ID()) {
745
-                $line_item->save();
746
-            }
747
-            $this->set_parent_ID($line_item->ID());
748
-            $this->save();
749
-        } else {
750
-            $this->_parent = $line_item;
751
-            $this->set_parent_ID($line_item->ID());
752
-        }
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
759
-     * you can modify this child line item and the parent (this object) can know about them
760
-     * because it also has a reference to that line item
761
-     *
762
-     * @param string $code
763
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
764
-     * @throws EE_Error
765
-     */
766
-    public function get_child_line_item($code)
767
-    {
768
-        if ($this->ID()) {
769
-            return $this->get_model()->get_one(
770
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
771
-            );
772
-        }
773
-        return isset($this->_children[$code])
774
-            ? $this->_children[$code]
775
-            : null;
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
782
-     * cached on it)
783
-     *
784
-     * @return int
785
-     * @throws EE_Error
786
-     */
787
-    public function delete_children_line_items()
788
-    {
789
-        if ($this->ID()) {
790
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
791
-        }
792
-        $count = count($this->_children);
793
-        $this->_children = array();
794
-        return $count;
795
-    }
796
-
797
-
798
-
799
-    /**
800
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
801
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
802
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
803
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
804
-     * deleted)
805
-     *
806
-     * @param string $code
807
-     * @param bool   $stop_search_once_found
808
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
809
-     *             the DB yet)
810
-     * @throws EE_Error
811
-     */
812
-    public function delete_child_line_item($code, $stop_search_once_found = true)
813
-    {
814
-        if ($this->ID()) {
815
-            $items_deleted = 0;
816
-            if ($this->code() === $code) {
817
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
818
-                $items_deleted += (int)$this->delete();
819
-                if ($stop_search_once_found) {
820
-                    return $items_deleted;
821
-                }
822
-            }
823
-            foreach ($this->children() as $child_line_item) {
824
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
825
-            }
826
-            return $items_deleted;
827
-        }
828
-        if (isset($this->_children[$code])) {
829
-            unset($this->_children[$code]);
830
-            return 1;
831
-        }
832
-        return 0;
833
-    }
834
-
835
-
836
-    /**
837
-     * If this line item is in the database, is of the type subtotal, and
838
-     * has no children, why do we have it? It should be deleted so this function
839
-     * does that
840
-     *
841
-     * @return boolean
842
-     * @throws EE_Error
843
-     */
844
-    public function delete_if_childless_subtotal()
845
-    {
846
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
847
-            return $this->delete();
848
-        }
849
-        return false;
850
-    }
851
-
852
-
853
-
854
-    /**
855
-     * Creates a code and returns a string. doesn't assign the code to this model object
856
-     *
857
-     * @return string
858
-     * @throws EE_Error
859
-     */
860
-    public function generate_code()
861
-    {
862
-        // each line item in the cart requires a unique identifier
863
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
864
-    }
865
-
866
-
867
-
868
-    /**
869
-     * @return bool
870
-     * @throws EE_Error
871
-     */
872
-    public function is_tax()
873
-    {
874
-        return $this->type() === EEM_Line_Item::type_tax;
875
-    }
876
-
877
-
878
-
879
-    /**
880
-     * @return bool
881
-     * @throws EE_Error
882
-     */
883
-    public function is_tax_sub_total()
884
-    {
885
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
886
-    }
887
-
888
-
889
-
890
-    /**
891
-     * @return bool
892
-     * @throws EE_Error
893
-     */
894
-    public function is_line_item()
895
-    {
896
-        return $this->type() === EEM_Line_Item::type_line_item;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * @return bool
903
-     * @throws EE_Error
904
-     */
905
-    public function is_sub_line_item()
906
-    {
907
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
908
-    }
909
-
910
-
911
-
912
-    /**
913
-     * @return bool
914
-     * @throws EE_Error
915
-     */
916
-    public function is_sub_total()
917
-    {
918
-        return $this->type() === EEM_Line_Item::type_sub_total;
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * Whether or not this line item is a cancellation line item
925
-     *
926
-     * @return boolean
927
-     * @throws EE_Error
928
-     */
929
-    public function is_cancellation()
930
-    {
931
-        return EEM_Line_Item::type_cancellation === $this->type();
932
-    }
933
-
934
-
935
-
936
-    /**
937
-     * @return bool
938
-     * @throws EE_Error
939
-     */
940
-    public function is_total()
941
-    {
942
-        return $this->type() === EEM_Line_Item::type_total;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * @return bool
949
-     * @throws EE_Error
950
-     */
951
-    public function is_cancelled()
952
-    {
953
-        return $this->type() === EEM_Line_Item::type_cancellation;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * @return string like '2, 004.00', formatted according to the localized currency
960
-     * @throws EE_Error
961
-     */
962
-    public function unit_price_no_code()
963
-    {
964
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * @return string like '2, 004.00', formatted according to the localized currency
971
-     * @throws EE_Error
972
-     */
973
-    public function total_no_code()
974
-    {
975
-        return $this->get_pretty('LIN_total', 'no_currency_code');
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Gets the final total on this item, taking taxes into account.
982
-     * Has the side-effect of setting the sub-total as it was just calculated.
983
-     * If this is used on a grand-total line item, also updates the transaction's
984
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
985
-     * want to change a persistable transaction with info from a non-persistent line item)
986
-     *
987
-     * @return float
988
-     * @throws EE_Error
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidInterfaceException
991
-     * @throws InvalidDataTypeException
992
-     */
993
-    public function recalculate_total_including_taxes()
994
-    {
995
-        $pre_tax_total = $this->recalculate_pre_tax_total();
996
-        $tax_total = $this->recalculate_taxes_and_tax_total();
997
-        $total = $pre_tax_total + $tax_total;
998
-        // no negative totals plz
999
-        $total = max($total, 0);
1000
-        $this->set_total($total);
1001
-        //only update the related transaction's total
1002
-        //if we intend to save this line item and its a grand total
1003
-        if (
1004
-            $this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1005
-            && $this->transaction()
1006
-               instanceof
1007
-               EE_Transaction
1008
-        ) {
1009
-            $this->transaction()->set_total($total);
1010
-            if ($this->transaction()->ID()) {
1011
-                $this->transaction()->save();
1012
-            }
1013
-        }
1014
-        $this->maybe_save();
1015
-        return $total;
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1021
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1022
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1023
-     * when this is called on the grand total
1024
-     *
1025
-     * @return float
1026
-     * @throws InvalidArgumentException
1027
-     * @throws InvalidInterfaceException
1028
-     * @throws InvalidDataTypeException
1029
-     * @throws EE_Error
1030
-     */
1031
-    public function recalculate_pre_tax_total()
1032
-    {
1033
-        $total = 0;
1034
-        $my_children = $this->children();
1035
-        $has_children = ! empty($my_children);
1036
-        if ($has_children && $this->is_line_item()) {
1037
-            $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1038
-        } elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1039
-            $total = $this->unit_price() * $this->quantity();
1040
-        } elseif ($this->is_sub_total() || $this->is_total()) {
1041
-            $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1042
-        } elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1043
-            // completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1044
-            return 0;
1045
-        }
1046
-        // ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1047
-        if (
1048
-            ! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()
1049
-        ) {
1050
-            if ($this->OBJ_type() !== 'Event') {
1051
-                $this->set_quantity(1);
1052
-            }
1053
-            if (! $this->is_percent()) {
1054
-                $this->set_unit_price($total);
1055
-            }
1056
-        }
1057
-        //we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1058
-        //so it ought to be
1059
-        if (! $this->is_total()) {
1060
-            $this->set_total($total);
1061
-            //if not a percent line item, make sure we keep the unit price in sync
1062
-            if (
1063
-                $has_children
1064
-                && $this->is_line_item()
1065
-                && ! $this->is_percent()
1066
-            ) {
1067
-                if ($this->quantity() === 0) {
1068
-                    $new_unit_price = 0;
1069
-                } else {
1070
-                    $new_unit_price = $this->total() / $this->quantity();
1071
-                }
1072
-                $this->set_unit_price($new_unit_price);
1073
-            }
1074
-            $this->maybe_save();
1075
-        }
1076
-        return $total;
1077
-    }
1078
-
1079
-
1080
-
1081
-    /**
1082
-     * Calculates the pretax total when this line item is a subtotal or total line item.
1083
-     * Basically does a sum-then-round approach (ie, any percent line item that are children
1084
-     * will calculate their total based on the un-rounded total we're working with so far, and
1085
-     * THEN round the result; instead of rounding as we go like with sub-line-items)
1086
-     *
1087
-     * @param float          $calculated_total_so_far
1088
-     * @param EE_Line_Item[] $my_children
1089
-     * @return float
1090
-     * @throws InvalidArgumentException
1091
-     * @throws InvalidInterfaceException
1092
-     * @throws InvalidDataTypeException
1093
-     * @throws EE_Error
1094
-     */
1095
-    protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1096
-    {
1097
-        if ($my_children === null) {
1098
-            $my_children = $this->children();
1099
-        }
1100
-        //get the total of all its children
1101
-        foreach ($my_children as $child_line_item) {
1102
-            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1103
-                // percentage line items are based on total so far
1104
-                if ($child_line_item->is_percent()) {
1105
-                    //round as we go so that the line items add up ok
1106
-                    $percent_total = round(
1107
-                        $calculated_total_so_far * $child_line_item->percent() / 100,
1108
-                        EE_Registry::instance()->CFG->currency->dec_plc
1109
-                    );
1110
-                    $child_line_item->set_total($percent_total);
1111
-                    //so far all percent line items should have a quantity of 1
1112
-                    //(ie, no double percent discounts. Although that might be requested someday)
1113
-                    $child_line_item->set_quantity(1);
1114
-                    $child_line_item->maybe_save();
1115
-                    $calculated_total_so_far += $percent_total;
1116
-                } else {
1117
-                    //verify flat sub-line-item quantities match their parent
1118
-                    if ($child_line_item->is_sub_line_item()) {
1119
-                        $child_line_item->set_quantity($this->quantity());
1120
-                    }
1121
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1122
-                }
1123
-            }
1124
-        }
1125
-        if ($this->is_sub_total()) {
1126
-            // no negative totals plz
1127
-            $calculated_total_so_far = max($calculated_total_so_far, 0);
1128
-        }
1129
-        return $calculated_total_so_far;
1130
-    }
1131
-
1132
-
1133
-
1134
-    /**
1135
-     * Calculates the pretax total for a normal line item, in a round-then-sum approach
1136
-     * (where each sub-line-item is applied to the base price for the line item
1137
-     * and the result is immediately rounded, rather than summing all the sub-line-items
1138
-     * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1139
-     *
1140
-     * @param float          $calculated_total_so_far
1141
-     * @param EE_Line_Item[] $my_children
1142
-     * @return float
1143
-     * @throws InvalidArgumentException
1144
-     * @throws InvalidInterfaceException
1145
-     * @throws InvalidDataTypeException
1146
-     * @throws EE_Error
1147
-     */
1148
-    protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1149
-    {
1150
-        if ($my_children === null) {
1151
-            $my_children = $this->children();
1152
-        }
1153
-        //we need to keep track of the running total for a single item,
1154
-        //because we need to round as we go
1155
-        $unit_price_for_total = 0;
1156
-        $quantity_for_total = 1;
1157
-        //get the total of all its children
1158
-        foreach ($my_children as $child_line_item) {
1159
-            if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1160
-                if ($child_line_item->is_percent()) {
1161
-                    //it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1162
-                    //not total multiplied by percent, because that ignores rounding along-the-way
1163
-                    $percent_unit_price = round(
1164
-                        $unit_price_for_total * $child_line_item->percent() / 100,
1165
-                        EE_Registry::instance()->CFG->currency->dec_plc
1166
-                    );
1167
-                    $percent_total = $percent_unit_price * $quantity_for_total;
1168
-                    $child_line_item->set_total($percent_total);
1169
-                    //so far all percent line items should have a quantity of 1
1170
-                    //(ie, no double percent discounts. Although that might be requested someday)
1171
-                    $child_line_item->set_quantity(1);
1172
-                    $child_line_item->maybe_save();
1173
-                    $calculated_total_so_far += $percent_total;
1174
-                    $unit_price_for_total += $percent_unit_price;
1175
-                } else {
1176
-                    //verify flat sub-line-item quantities match their parent
1177
-                    if ($child_line_item->is_sub_line_item()) {
1178
-                        $child_line_item->set_quantity($this->quantity());
1179
-                    }
1180
-                    $quantity_for_total = $child_line_item->quantity();
1181
-                    $calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1182
-                    $unit_price_for_total += $child_line_item->unit_price();
1183
-                }
1184
-            }
1185
-        }
1186
-        return $calculated_total_so_far;
1187
-    }
1188
-
1189
-
1190
-
1191
-    /**
1192
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1193
-     * the totals on each tax calculated, and returns the final tax total
1194
-     *
1195
-     * @return float
1196
-     * @throws EE_Error
1197
-     */
1198
-    public function recalculate_taxes_and_tax_total()
1199
-    {
1200
-        //get all taxes
1201
-        $taxes = $this->tax_descendants();
1202
-        //calculate the pretax total
1203
-        $taxable_total = $this->taxable_total();
1204
-        $tax_total = 0;
1205
-        foreach ($taxes as $tax) {
1206
-            $total_on_this_tax = $taxable_total * $tax->percent() / 100;
1207
-            //remember the total on this line item
1208
-            $tax->set_total($total_on_this_tax);
1209
-            $tax_total += $tax->total();
1210
-        }
1211
-        $this->_recalculate_tax_sub_total();
1212
-        return $tax_total;
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1219
-     *
1220
-     * @return void
1221
-     * @throws EE_Error
1222
-     */
1223
-    private function _recalculate_tax_sub_total()
1224
-    {
1225
-        if ($this->is_tax_sub_total()) {
1226
-            $total = 0;
1227
-            $total_percent = 0;
1228
-            //simply loop through all its children (which should be taxes) and sum their total
1229
-            foreach ($this->children() as $child_tax) {
1230
-                if ($child_tax instanceof EE_Line_Item) {
1231
-                    $total += $child_tax->total();
1232
-                    $total_percent += $child_tax->percent();
1233
-                }
1234
-            }
1235
-            $this->set_total($total);
1236
-            $this->set_percent($total_percent);
1237
-        } elseif ($this->is_total()) {
1238
-            foreach ($this->children() as $maybe_tax_subtotal) {
1239
-                if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1240
-                    $maybe_tax_subtotal->_recalculate_tax_sub_total();
1241
-                }
1242
-            }
1243
-        }
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1250
-     * recalculate_taxes_and_total
1251
-     *
1252
-     * @return float
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function get_total_tax()
1256
-    {
1257
-        $this->_recalculate_tax_sub_total();
1258
-        $total = 0;
1259
-        foreach ($this->tax_descendants() as $tax_line_item) {
1260
-            if ($tax_line_item instanceof EE_Line_Item) {
1261
-                $total += $tax_line_item->total();
1262
-            }
1263
-        }
1264
-        return $total;
1265
-    }
1266
-
1267
-
1268
-    /**
1269
-     * Gets the total for all the items purchased only
1270
-     *
1271
-     * @return float
1272
-     * @throws EE_Error
1273
-     */
1274
-    public function get_items_total()
1275
-    {
1276
-        //by default, let's make sure we're consistent with the existing line item
1277
-        if ($this->is_total()) {
1278
-            $pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1279
-            if ($pretax_subtotal_li instanceof EE_Line_Item) {
1280
-                return $pretax_subtotal_li->total();
1281
-            }
1282
-        }
1283
-        $total = 0;
1284
-        foreach ($this->get_items() as $item) {
1285
-            if ($item instanceof EE_Line_Item) {
1286
-                $total += $item->total();
1287
-            }
1288
-        }
1289
-        return $total;
1290
-    }
1291
-
1292
-
1293
-
1294
-    /**
1295
-     * Gets all the descendants (ie, children or children of children etc) that
1296
-     * are of the type 'tax'
1297
-     *
1298
-     * @return EE_Line_Item[]
1299
-     */
1300
-    public function tax_descendants()
1301
-    {
1302
-        return EEH_Line_Item::get_tax_descendants($this);
1303
-    }
1304
-
1305
-
1306
-
1307
-    /**
1308
-     * Gets all the real items purchased which are children of this item
1309
-     *
1310
-     * @return EE_Line_Item[]
1311
-     */
1312
-    public function get_items()
1313
-    {
1314
-        return EEH_Line_Item::get_line_item_descendants($this);
1315
-    }
1316
-
1317
-
1318
-
1319
-    /**
1320
-     * Returns the amount taxable among this line item's children (or if it has no children,
1321
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1322
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1323
-     * but there is a "Taxable" discount), returns 0.
1324
-     *
1325
-     * @return float
1326
-     * @throws EE_Error
1327
-     */
1328
-    public function taxable_total()
1329
-    {
1330
-        $total = 0;
1331
-        if ($this->children()) {
1332
-            foreach ($this->children() as $child_line_item) {
1333
-                if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1334
-                    //if it's a percent item, only take into account the percent
1335
-                    //that's taxable too (the taxable total so far)
1336
-                    if ($child_line_item->is_percent()) {
1337
-                        $total += ($total * $child_line_item->percent() / 100);
1338
-                    } else {
1339
-                        $total += $child_line_item->total();
1340
-                    }
1341
-                } elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1342
-                    $total += $child_line_item->taxable_total();
1343
-                }
1344
-            }
1345
-        }
1346
-        return max($total, 0);
1347
-    }
1348
-
1349
-
1350
-
1351
-    /**
1352
-     * Gets the transaction for this line item
1353
-     *
1354
-     * @return EE_Base_Class|EE_Transaction
1355
-     * @throws EE_Error
1356
-     */
1357
-    public function transaction()
1358
-    {
1359
-        return $this->get_first_related('Transaction');
1360
-    }
1361
-
1362
-
1363
-
1364
-    /**
1365
-     * Saves this line item to the DB, and recursively saves its descendants.
1366
-     * Because there currently is no proper parent-child relation on the model,
1367
-     * save_this_and_cached() will NOT save the descendants.
1368
-     * Also sets the transaction on this line item and all its descendants before saving
1369
-     *
1370
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1371
-     * @return int count of items saved
1372
-     * @throws EE_Error
1373
-     */
1374
-    public function save_this_and_descendants_to_txn($txn_id = null)
1375
-    {
1376
-        $count = 0;
1377
-        if (! $txn_id) {
1378
-            $txn_id = $this->TXN_ID();
1379
-        }
1380
-        $this->set_TXN_ID($txn_id);
1381
-        $children = $this->children();
1382
-        $count += $this->save()
1383
-            ? 1
1384
-            : 0;
1385
-        foreach ($children as $child_line_item) {
1386
-            if ($child_line_item instanceof EE_Line_Item) {
1387
-                $child_line_item->set_parent_ID($this->ID());
1388
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1389
-            }
1390
-        }
1391
-        return $count;
1392
-    }
1393
-
1394
-
1395
-
1396
-    /**
1397
-     * Saves this line item to the DB, and recursively saves its descendants.
1398
-     *
1399
-     * @return int count of items saved
1400
-     * @throws EE_Error
1401
-     */
1402
-    public function save_this_and_descendants()
1403
-    {
1404
-        $count = 0;
1405
-        $children = $this->children();
1406
-        $count += $this->save()
1407
-            ? 1
1408
-            : 0;
1409
-        foreach ($children as $child_line_item) {
1410
-            if ($child_line_item instanceof EE_Line_Item) {
1411
-                $child_line_item->set_parent_ID($this->ID());
1412
-                $count += $child_line_item->save_this_and_descendants();
1413
-            }
1414
-        }
1415
-        return $count;
1416
-    }
1417
-
1418
-
1419
-
1420
-    /**
1421
-     * returns the cancellation line item if this item was cancelled
1422
-     *
1423
-     * @return EE_Line_Item[]
1424
-     * @throws InvalidArgumentException
1425
-     * @throws InvalidInterfaceException
1426
-     * @throws InvalidDataTypeException
1427
-     * @throws ReflectionException
1428
-     * @throws EE_Error
1429
-     */
1430
-    public function get_cancellations()
1431
-    {
1432
-        EE_Registry::instance()->load_helper('Line_Item');
1433
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1434
-    }
1435
-
1436
-
1437
-
1438
-    /**
1439
-     * If this item has an ID, then this saves it again to update the db
1440
-     *
1441
-     * @return int count of items saved
1442
-     * @throws EE_Error
1443
-     */
1444
-    public function maybe_save()
1445
-    {
1446
-        if ($this->ID()) {
1447
-            return $this->save();
1448
-        }
1449
-        return false;
1450
-    }
1451
-
1452
-
1453
-    /**
1454
-     * clears the cached children and parent from the line item
1455
-     *
1456
-     * @return void
1457
-     */
1458
-    public function clear_related_line_item_cache()
1459
-    {
1460
-        $this->_children = array();
1461
-        $this->_parent = null;
1462
-    }
1463
-
1464
-
1465
-
1466
-    /**
1467
-     * @param bool $raw
1468
-     * @return int
1469
-     * @throws EE_Error
1470
-     */
1471
-    public function timestamp($raw = false)
1472
-    {
1473
-        return $raw
1474
-            ? $this->get_raw('LIN_timestamp')
1475
-            : $this->get('LIN_timestamp');
1476
-    }
1477
-
1478
-
1479
-
1480
-
1481
-    /************************* DEPRECATED *************************/
1482
-    /**
1483
-     * @deprecated 4.6.0
1484
-     * @param string $type one of the constants on EEM_Line_Item
1485
-     * @return EE_Line_Item[]
1486
-     */
1487
-    protected function _get_descendants_of_type($type)
1488
-    {
1489
-        EE_Error::doing_it_wrong(
1490
-            'EE_Line_Item::_get_descendants_of_type()',
1491
-            __('Method replaced with EEH_Line_Item::get_descendants_of_type()', 'event_espresso'), '4.6.0'
1492
-        );
1493
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1494
-    }
1495
-
1496
-
1497
-
1498
-    /**
1499
-     * @deprecated 4.6.0
1500
-     * @param string $type like one of the EEM_Line_Item::type_*
1501
-     * @return EE_Line_Item
1502
-     */
1503
-    public function get_nearest_descendant_of_type($type)
1504
-    {
1505
-        EE_Error::doing_it_wrong(
1506
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1507
-            __('Method replaced with EEH_Line_Item::get_nearest_descendant_of_type()', 'event_espresso'), '4.6.0'
1508
-        );
1509
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1510
-    }
21
+	/**
22
+	 * for children line items (currently not a normal relation)
23
+	 *
24
+	 * @type EE_Line_Item[]
25
+	 */
26
+	protected $_children = array();
27
+
28
+	/**
29
+	 * for the parent line item
30
+	 *
31
+	 * @var EE_Line_Item
32
+	 */
33
+	protected $_parent;
34
+
35
+
36
+
37
+	/**
38
+	 *
39
+	 * @param array  $props_n_values          incoming values
40
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
+	 *                                        used.)
42
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
+	 *                                        date_format and the second value is the time format
44
+	 * @return EE_Line_Item
45
+	 * @throws EE_Error
46
+	 */
47
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
48
+	{
49
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
50
+		return $has_object
51
+			? $has_object
52
+			: new self($props_n_values, false, $timezone);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values  incoming values from the database
59
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
+	 *                                the website will be used.
61
+	 * @return EE_Line_Item
62
+	 * @throws EE_Error
63
+	 */
64
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
65
+	{
66
+		return new self($props_n_values, true, $timezone);
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 * Adds some defaults if they're not specified
73
+	 *
74
+	 * @param array  $fieldValues
75
+	 * @param bool   $bydb
76
+	 * @param string $timezone
77
+	 * @throws EE_Error
78
+	 */
79
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
80
+	{
81
+		parent::__construct($fieldValues, $bydb, $timezone);
82
+		if (! $this->get('LIN_code')) {
83
+			$this->set_code($this->generate_code());
84
+		}
85
+	}
86
+
87
+
88
+
89
+	/**
90
+	 * Gets ID
91
+	 *
92
+	 * @return int
93
+	 * @throws EE_Error
94
+	 */
95
+	public function ID()
96
+	{
97
+		return $this->get('LIN_ID');
98
+	}
99
+
100
+
101
+
102
+	/**
103
+	 * Gets TXN_ID
104
+	 *
105
+	 * @return int
106
+	 * @throws EE_Error
107
+	 */
108
+	public function TXN_ID()
109
+	{
110
+		return $this->get('TXN_ID');
111
+	}
112
+
113
+
114
+
115
+	/**
116
+	 * Sets TXN_ID
117
+	 *
118
+	 * @param int $TXN_ID
119
+	 * @throws EE_Error
120
+	 */
121
+	public function set_TXN_ID($TXN_ID)
122
+	{
123
+		$this->set('TXN_ID', $TXN_ID);
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * Gets name
130
+	 *
131
+	 * @return string
132
+	 * @throws EE_Error
133
+	 */
134
+	public function name()
135
+	{
136
+		$name = $this->get('LIN_name');
137
+		if (! $name) {
138
+			$name = ucwords(str_replace('-', ' ', $this->type()));
139
+		}
140
+		return $name;
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 * Sets name
147
+	 *
148
+	 * @param string $name
149
+	 * @throws EE_Error
150
+	 */
151
+	public function set_name($name)
152
+	{
153
+		$this->set('LIN_name', $name);
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 * Gets desc
160
+	 *
161
+	 * @return string
162
+	 * @throws EE_Error
163
+	 */
164
+	public function desc()
165
+	{
166
+		return $this->get('LIN_desc');
167
+	}
168
+
169
+
170
+
171
+	/**
172
+	 * Sets desc
173
+	 *
174
+	 * @param string $desc
175
+	 * @throws EE_Error
176
+	 */
177
+	public function set_desc($desc)
178
+	{
179
+		$this->set('LIN_desc', $desc);
180
+	}
181
+
182
+
183
+
184
+	/**
185
+	 * Gets quantity
186
+	 *
187
+	 * @return int
188
+	 * @throws EE_Error
189
+	 */
190
+	public function quantity()
191
+	{
192
+		return $this->get('LIN_quantity');
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * Sets quantity
199
+	 *
200
+	 * @param int $quantity
201
+	 * @throws EE_Error
202
+	 */
203
+	public function set_quantity($quantity)
204
+	{
205
+		$this->set('LIN_quantity', max($quantity, 0));
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 * Gets item_id
212
+	 *
213
+	 * @return string
214
+	 * @throws EE_Error
215
+	 */
216
+	public function OBJ_ID()
217
+	{
218
+		return $this->get('OBJ_ID');
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * Sets item_id
225
+	 *
226
+	 * @param string $item_id
227
+	 * @throws EE_Error
228
+	 */
229
+	public function set_OBJ_ID($item_id)
230
+	{
231
+		$this->set('OBJ_ID', $item_id);
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * Gets item_type
238
+	 *
239
+	 * @return string
240
+	 * @throws EE_Error
241
+	 */
242
+	public function OBJ_type()
243
+	{
244
+		return $this->get('OBJ_type');
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Gets item_type
251
+	 *
252
+	 * @return string
253
+	 * @throws EE_Error
254
+	 */
255
+	public function OBJ_type_i18n()
256
+	{
257
+		$obj_type = $this->OBJ_type();
258
+		switch ($obj_type) {
259
+			case 'Event':
260
+				$obj_type = __('Event', 'event_espresso');
261
+				break;
262
+			case 'Price':
263
+				$obj_type = __('Price', 'event_espresso');
264
+				break;
265
+			case 'Promotion':
266
+				$obj_type = __('Promotion', 'event_espresso');
267
+				break;
268
+			case 'Ticket':
269
+				$obj_type = __('Ticket', 'event_espresso');
270
+				break;
271
+			case 'Transaction':
272
+				$obj_type = __('Transaction', 'event_espresso');
273
+				break;
274
+		}
275
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * Sets item_type
282
+	 *
283
+	 * @param string $OBJ_type
284
+	 * @throws EE_Error
285
+	 */
286
+	public function set_OBJ_type($OBJ_type)
287
+	{
288
+		$this->set('OBJ_type', $OBJ_type);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * Gets unit_price
295
+	 *
296
+	 * @return float
297
+	 * @throws EE_Error
298
+	 */
299
+	public function unit_price()
300
+	{
301
+		return $this->get('LIN_unit_price');
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * Sets unit_price
308
+	 *
309
+	 * @param float $unit_price
310
+	 * @throws EE_Error
311
+	 */
312
+	public function set_unit_price($unit_price)
313
+	{
314
+		$this->set('LIN_unit_price', $unit_price);
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * Checks if this item is a percentage modifier or not
321
+	 *
322
+	 * @return boolean
323
+	 * @throws EE_Error
324
+	 */
325
+	public function is_percent()
326
+	{
327
+		if ($this->is_tax_sub_total()) {
328
+			//tax subtotals HAVE a percent on them, that percentage only applies
329
+			//to taxable items, so its' an exception. Treat it like a flat line item
330
+			return false;
331
+		}
332
+		$unit_price = abs($this->get('LIN_unit_price'));
333
+		$percent = abs($this->get('LIN_percent'));
334
+		if ($unit_price < .001 && $percent) {
335
+			return true;
336
+		}
337
+		if ($unit_price >= .001 && ! $percent) {
338
+			return false;
339
+		}
340
+		if ($unit_price >= .001 && $percent) {
341
+			throw new EE_Error(
342
+				sprintf(
343
+					esc_html__('A Line Item can not have a unit price of (%s) AND a percent (%s)!', 'event_espresso'),
344
+					$unit_price, $percent
345
+				)
346
+			);
347
+		}
348
+		// if they're both 0, assume its not a percent item
349
+		return false;
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * Gets percent (between 100-.001)
356
+	 *
357
+	 * @return float
358
+	 * @throws EE_Error
359
+	 */
360
+	public function percent()
361
+	{
362
+		return $this->get('LIN_percent');
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * Sets percent (between 100-0.01)
369
+	 *
370
+	 * @param float $percent
371
+	 * @throws EE_Error
372
+	 */
373
+	public function set_percent($percent)
374
+	{
375
+		$this->set('LIN_percent', $percent);
376
+	}
377
+
378
+
379
+
380
+	/**
381
+	 * Gets total
382
+	 *
383
+	 * @return float
384
+	 * @throws EE_Error
385
+	 */
386
+	public function total()
387
+	{
388
+		return $this->get('LIN_total');
389
+	}
390
+
391
+
392
+
393
+	/**
394
+	 * Sets total
395
+	 *
396
+	 * @param float $total
397
+	 * @throws EE_Error
398
+	 */
399
+	public function set_total($total)
400
+	{
401
+		$this->set('LIN_total', $total);
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * Gets order
408
+	 *
409
+	 * @return int
410
+	 * @throws EE_Error
411
+	 */
412
+	public function order()
413
+	{
414
+		return $this->get('LIN_order');
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * Sets order
421
+	 *
422
+	 * @param int $order
423
+	 * @throws EE_Error
424
+	 */
425
+	public function set_order($order)
426
+	{
427
+		$this->set('LIN_order', $order);
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * Gets parent
434
+	 *
435
+	 * @return int
436
+	 * @throws EE_Error
437
+	 */
438
+	public function parent_ID()
439
+	{
440
+		return $this->get('LIN_parent');
441
+	}
442
+
443
+
444
+
445
+	/**
446
+	 * Sets parent
447
+	 *
448
+	 * @param int $parent
449
+	 * @throws EE_Error
450
+	 */
451
+	public function set_parent_ID($parent)
452
+	{
453
+		$this->set('LIN_parent', $parent);
454
+	}
455
+
456
+
457
+
458
+	/**
459
+	 * Gets type
460
+	 *
461
+	 * @return string
462
+	 * @throws EE_Error
463
+	 */
464
+	public function type()
465
+	{
466
+		return $this->get('LIN_type');
467
+	}
468
+
469
+
470
+
471
+	/**
472
+	 * Sets type
473
+	 *
474
+	 * @param string $type
475
+	 * @throws EE_Error
476
+	 */
477
+	public function set_type($type)
478
+	{
479
+		$this->set('LIN_type', $type);
480
+	}
481
+
482
+
483
+
484
+	/**
485
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
486
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
487
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
488
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
489
+	 *
490
+	 * @return EE_Base_Class|EE_Line_Item
491
+	 * @throws EE_Error
492
+	 */
493
+	public function parent()
494
+	{
495
+		return $this->ID()
496
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
497
+			: $this->_parent;
498
+	}
499
+
500
+
501
+
502
+	/**
503
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
504
+	 *
505
+	 * @return EE_Base_Class[]|EE_Line_Item[]
506
+	 * @throws EE_Error
507
+	 */
508
+	public function children()
509
+	{
510
+		if ($this->ID()) {
511
+			return $this->get_model()->get_all(
512
+				array(
513
+					array('LIN_parent' => $this->ID()),
514
+					'order_by' => array('LIN_order' => 'ASC'),
515
+				)
516
+			);
517
+		}
518
+		if (! is_array($this->_children)) {
519
+			$this->_children = array();
520
+		}
521
+		return $this->_children;
522
+	}
523
+
524
+
525
+
526
+	/**
527
+	 * Gets code
528
+	 *
529
+	 * @return string
530
+	 * @throws EE_Error
531
+	 */
532
+	public function code()
533
+	{
534
+		return $this->get('LIN_code');
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Sets code
541
+	 *
542
+	 * @param string $code
543
+	 * @throws EE_Error
544
+	 */
545
+	public function set_code($code)
546
+	{
547
+		$this->set('LIN_code', $code);
548
+	}
549
+
550
+
551
+
552
+	/**
553
+	 * Gets is_taxable
554
+	 *
555
+	 * @return boolean
556
+	 * @throws EE_Error
557
+	 */
558
+	public function is_taxable()
559
+	{
560
+		return $this->get('LIN_is_taxable');
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * Sets is_taxable
567
+	 *
568
+	 * @param boolean $is_taxable
569
+	 * @throws EE_Error
570
+	 */
571
+	public function set_is_taxable($is_taxable)
572
+	{
573
+		$this->set('LIN_is_taxable', $is_taxable);
574
+	}
575
+
576
+
577
+
578
+	/**
579
+	 * Gets the object that this model-joins-to.
580
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
581
+	 * EEM_Promotion_Object
582
+	 *
583
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
584
+	 *
585
+	 * @return EE_Base_Class | NULL
586
+	 * @throws EE_Error
587
+	 */
588
+	public function get_object()
589
+	{
590
+		$model_name_of_related_obj = $this->OBJ_type();
591
+		return $this->get_model()->has_relation($model_name_of_related_obj)
592
+			? $this->get_first_related($model_name_of_related_obj)
593
+			: null;
594
+	}
595
+
596
+
597
+
598
+	/**
599
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
600
+	 * (IE, if this line item is for a price or something else, will return NULL)
601
+	 *
602
+	 * @param array $query_params
603
+	 * @return EE_Base_Class|EE_Ticket
604
+	 * @throws EE_Error
605
+	 */
606
+	public function ticket($query_params = array())
607
+	{
608
+		//we're going to assume that when this method is called we always want to receive the attached ticket EVEN if that ticket is archived.  This can be overridden via the incoming $query_params argument
609
+		$remove_defaults = array('default_where_conditions' => 'none');
610
+		$query_params = array_merge($remove_defaults, $query_params);
611
+		return $this->get_first_related('Ticket', $query_params);
612
+	}
613
+
614
+
615
+
616
+	/**
617
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
618
+	 *
619
+	 * @return EE_Datetime | NULL
620
+	 * @throws EE_Error
621
+	 */
622
+	public function get_ticket_datetime()
623
+	{
624
+		if ($this->OBJ_type() === 'Ticket') {
625
+			$ticket = $this->ticket();
626
+			if ($ticket instanceof EE_Ticket) {
627
+				$datetime = $ticket->first_datetime();
628
+				if ($datetime instanceof EE_Datetime) {
629
+					return $datetime;
630
+				}
631
+			}
632
+		}
633
+		return null;
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * Gets the event's name that's related to the ticket, if this is for
640
+	 * a ticket
641
+	 *
642
+	 * @return string
643
+	 * @throws EE_Error
644
+	 */
645
+	public function ticket_event_name()
646
+	{
647
+		$event_name = esc_html__('Unknown', 'event_espresso');
648
+		$event = $this->ticket_event();
649
+		if ($event instanceof EE_Event) {
650
+			$event_name = $event->name();
651
+		}
652
+		return $event_name;
653
+	}
654
+
655
+
656
+	/**
657
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
658
+	 *
659
+	 * @return EE_Event|null
660
+	 * @throws EE_Error
661
+	 */
662
+	public function ticket_event()
663
+	{
664
+		$event = null;
665
+		$ticket = $this->ticket();
666
+		if ($ticket instanceof EE_Ticket) {
667
+			$datetime = $ticket->first_datetime();
668
+			if ($datetime instanceof EE_Datetime) {
669
+				$event = $datetime->event();
670
+			}
671
+		}
672
+		return $event;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
679
+	 *
680
+	 * @param string $date_format
681
+	 * @param string $time_format
682
+	 * @return string
683
+	 * @throws EE_Error
684
+	 */
685
+	public function ticket_datetime_start($date_format = '', $time_format = '')
686
+	{
687
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
688
+		$datetime = $this->get_ticket_datetime();
689
+		if ($datetime) {
690
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
691
+		}
692
+		return $first_datetime_string;
693
+	}
694
+
695
+
696
+
697
+	/**
698
+	 * Adds the line item as a child to this line item. If there is another child line
699
+	 * item with the same LIN_code, it is overwritten by this new one
700
+	 *
701
+	 * @param EEI_Line_Item $line_item
702
+	 * @param bool          $set_order
703
+	 * @return bool success
704
+	 * @throws EE_Error
705
+	 */
706
+	public function add_child_line_item(EEI_Line_Item $line_item, $set_order = true)
707
+	{
708
+		// should we calculate the LIN_order for this line item ?
709
+		if ($set_order || $line_item->order() === null) {
710
+			$line_item->set_order(count($this->children()));
711
+		}
712
+		if ($this->ID()) {
713
+			//check for any duplicate line items (with the same code), if so, this replaces it
714
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
715
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
716
+				$this->delete_child_line_item($line_item_with_same_code->code());
717
+			}
718
+			$line_item->set_parent_ID($this->ID());
719
+			if ($this->TXN_ID()) {
720
+				$line_item->set_TXN_ID($this->TXN_ID());
721
+			}
722
+			return $line_item->save();
723
+		}
724
+		$this->_children[$line_item->code()] = $line_item;
725
+		if ($line_item->parent() !== $this) {
726
+			$line_item->set_parent($this);
727
+		}
728
+		return true;
729
+	}
730
+
731
+
732
+	/**
733
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
734
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
735
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
736
+	 * the EE_Line_Item::_parent property.
737
+	 *
738
+	 * @param EE_Line_Item $line_item
739
+	 * @throws EE_Error
740
+	 */
741
+	public function set_parent($line_item)
742
+	{
743
+		if ($this->ID()) {
744
+			if (! $line_item->ID()) {
745
+				$line_item->save();
746
+			}
747
+			$this->set_parent_ID($line_item->ID());
748
+			$this->save();
749
+		} else {
750
+			$this->_parent = $line_item;
751
+			$this->set_parent_ID($line_item->ID());
752
+		}
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
759
+	 * you can modify this child line item and the parent (this object) can know about them
760
+	 * because it also has a reference to that line item
761
+	 *
762
+	 * @param string $code
763
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
764
+	 * @throws EE_Error
765
+	 */
766
+	public function get_child_line_item($code)
767
+	{
768
+		if ($this->ID()) {
769
+			return $this->get_model()->get_one(
770
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
771
+			);
772
+		}
773
+		return isset($this->_children[$code])
774
+			? $this->_children[$code]
775
+			: null;
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
782
+	 * cached on it)
783
+	 *
784
+	 * @return int
785
+	 * @throws EE_Error
786
+	 */
787
+	public function delete_children_line_items()
788
+	{
789
+		if ($this->ID()) {
790
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
791
+		}
792
+		$count = count($this->_children);
793
+		$this->_children = array();
794
+		return $count;
795
+	}
796
+
797
+
798
+
799
+	/**
800
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
801
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
802
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
803
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
804
+	 * deleted)
805
+	 *
806
+	 * @param string $code
807
+	 * @param bool   $stop_search_once_found
808
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
809
+	 *             the DB yet)
810
+	 * @throws EE_Error
811
+	 */
812
+	public function delete_child_line_item($code, $stop_search_once_found = true)
813
+	{
814
+		if ($this->ID()) {
815
+			$items_deleted = 0;
816
+			if ($this->code() === $code) {
817
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
818
+				$items_deleted += (int)$this->delete();
819
+				if ($stop_search_once_found) {
820
+					return $items_deleted;
821
+				}
822
+			}
823
+			foreach ($this->children() as $child_line_item) {
824
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
825
+			}
826
+			return $items_deleted;
827
+		}
828
+		if (isset($this->_children[$code])) {
829
+			unset($this->_children[$code]);
830
+			return 1;
831
+		}
832
+		return 0;
833
+	}
834
+
835
+
836
+	/**
837
+	 * If this line item is in the database, is of the type subtotal, and
838
+	 * has no children, why do we have it? It should be deleted so this function
839
+	 * does that
840
+	 *
841
+	 * @return boolean
842
+	 * @throws EE_Error
843
+	 */
844
+	public function delete_if_childless_subtotal()
845
+	{
846
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
847
+			return $this->delete();
848
+		}
849
+		return false;
850
+	}
851
+
852
+
853
+
854
+	/**
855
+	 * Creates a code and returns a string. doesn't assign the code to this model object
856
+	 *
857
+	 * @return string
858
+	 * @throws EE_Error
859
+	 */
860
+	public function generate_code()
861
+	{
862
+		// each line item in the cart requires a unique identifier
863
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
864
+	}
865
+
866
+
867
+
868
+	/**
869
+	 * @return bool
870
+	 * @throws EE_Error
871
+	 */
872
+	public function is_tax()
873
+	{
874
+		return $this->type() === EEM_Line_Item::type_tax;
875
+	}
876
+
877
+
878
+
879
+	/**
880
+	 * @return bool
881
+	 * @throws EE_Error
882
+	 */
883
+	public function is_tax_sub_total()
884
+	{
885
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
886
+	}
887
+
888
+
889
+
890
+	/**
891
+	 * @return bool
892
+	 * @throws EE_Error
893
+	 */
894
+	public function is_line_item()
895
+	{
896
+		return $this->type() === EEM_Line_Item::type_line_item;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * @return bool
903
+	 * @throws EE_Error
904
+	 */
905
+	public function is_sub_line_item()
906
+	{
907
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
908
+	}
909
+
910
+
911
+
912
+	/**
913
+	 * @return bool
914
+	 * @throws EE_Error
915
+	 */
916
+	public function is_sub_total()
917
+	{
918
+		return $this->type() === EEM_Line_Item::type_sub_total;
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * Whether or not this line item is a cancellation line item
925
+	 *
926
+	 * @return boolean
927
+	 * @throws EE_Error
928
+	 */
929
+	public function is_cancellation()
930
+	{
931
+		return EEM_Line_Item::type_cancellation === $this->type();
932
+	}
933
+
934
+
935
+
936
+	/**
937
+	 * @return bool
938
+	 * @throws EE_Error
939
+	 */
940
+	public function is_total()
941
+	{
942
+		return $this->type() === EEM_Line_Item::type_total;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * @return bool
949
+	 * @throws EE_Error
950
+	 */
951
+	public function is_cancelled()
952
+	{
953
+		return $this->type() === EEM_Line_Item::type_cancellation;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * @return string like '2, 004.00', formatted according to the localized currency
960
+	 * @throws EE_Error
961
+	 */
962
+	public function unit_price_no_code()
963
+	{
964
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * @return string like '2, 004.00', formatted according to the localized currency
971
+	 * @throws EE_Error
972
+	 */
973
+	public function total_no_code()
974
+	{
975
+		return $this->get_pretty('LIN_total', 'no_currency_code');
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Gets the final total on this item, taking taxes into account.
982
+	 * Has the side-effect of setting the sub-total as it was just calculated.
983
+	 * If this is used on a grand-total line item, also updates the transaction's
984
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
985
+	 * want to change a persistable transaction with info from a non-persistent line item)
986
+	 *
987
+	 * @return float
988
+	 * @throws EE_Error
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidInterfaceException
991
+	 * @throws InvalidDataTypeException
992
+	 */
993
+	public function recalculate_total_including_taxes()
994
+	{
995
+		$pre_tax_total = $this->recalculate_pre_tax_total();
996
+		$tax_total = $this->recalculate_taxes_and_tax_total();
997
+		$total = $pre_tax_total + $tax_total;
998
+		// no negative totals plz
999
+		$total = max($total, 0);
1000
+		$this->set_total($total);
1001
+		//only update the related transaction's total
1002
+		//if we intend to save this line item and its a grand total
1003
+		if (
1004
+			$this->allow_persist() && $this->type() === EEM_Line_Item::type_total
1005
+			&& $this->transaction()
1006
+			   instanceof
1007
+			   EE_Transaction
1008
+		) {
1009
+			$this->transaction()->set_total($total);
1010
+			if ($this->transaction()->ID()) {
1011
+				$this->transaction()->save();
1012
+			}
1013
+		}
1014
+		$this->maybe_save();
1015
+		return $total;
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1021
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1022
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1023
+	 * when this is called on the grand total
1024
+	 *
1025
+	 * @return float
1026
+	 * @throws InvalidArgumentException
1027
+	 * @throws InvalidInterfaceException
1028
+	 * @throws InvalidDataTypeException
1029
+	 * @throws EE_Error
1030
+	 */
1031
+	public function recalculate_pre_tax_total()
1032
+	{
1033
+		$total = 0;
1034
+		$my_children = $this->children();
1035
+		$has_children = ! empty($my_children);
1036
+		if ($has_children && $this->is_line_item()) {
1037
+			$total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1038
+		} elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1039
+			$total = $this->unit_price() * $this->quantity();
1040
+		} elseif ($this->is_sub_total() || $this->is_total()) {
1041
+			$total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
1042
+		} elseif ($this->is_tax_sub_total() || $this->is_tax() || $this->is_cancelled()) {
1043
+			// completely ignore tax totals, tax sub-totals, and cancelled line items, when calculating the pre-tax-total
1044
+			return 0;
1045
+		}
1046
+		// ensure all non-line items and non-sub-line-items have a quantity of 1 (except for Events)
1047
+		if (
1048
+			! $this->is_line_item() && ! $this->is_sub_line_item() && ! $this->is_cancellation()
1049
+		) {
1050
+			if ($this->OBJ_type() !== 'Event') {
1051
+				$this->set_quantity(1);
1052
+			}
1053
+			if (! $this->is_percent()) {
1054
+				$this->set_unit_price($total);
1055
+			}
1056
+		}
1057
+		//we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1058
+		//so it ought to be
1059
+		if (! $this->is_total()) {
1060
+			$this->set_total($total);
1061
+			//if not a percent line item, make sure we keep the unit price in sync
1062
+			if (
1063
+				$has_children
1064
+				&& $this->is_line_item()
1065
+				&& ! $this->is_percent()
1066
+			) {
1067
+				if ($this->quantity() === 0) {
1068
+					$new_unit_price = 0;
1069
+				} else {
1070
+					$new_unit_price = $this->total() / $this->quantity();
1071
+				}
1072
+				$this->set_unit_price($new_unit_price);
1073
+			}
1074
+			$this->maybe_save();
1075
+		}
1076
+		return $total;
1077
+	}
1078
+
1079
+
1080
+
1081
+	/**
1082
+	 * Calculates the pretax total when this line item is a subtotal or total line item.
1083
+	 * Basically does a sum-then-round approach (ie, any percent line item that are children
1084
+	 * will calculate their total based on the un-rounded total we're working with so far, and
1085
+	 * THEN round the result; instead of rounding as we go like with sub-line-items)
1086
+	 *
1087
+	 * @param float          $calculated_total_so_far
1088
+	 * @param EE_Line_Item[] $my_children
1089
+	 * @return float
1090
+	 * @throws InvalidArgumentException
1091
+	 * @throws InvalidInterfaceException
1092
+	 * @throws InvalidDataTypeException
1093
+	 * @throws EE_Error
1094
+	 */
1095
+	protected function _recalculate_pretax_total_for_subtotal($calculated_total_so_far, $my_children = null)
1096
+	{
1097
+		if ($my_children === null) {
1098
+			$my_children = $this->children();
1099
+		}
1100
+		//get the total of all its children
1101
+		foreach ($my_children as $child_line_item) {
1102
+			if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1103
+				// percentage line items are based on total so far
1104
+				if ($child_line_item->is_percent()) {
1105
+					//round as we go so that the line items add up ok
1106
+					$percent_total = round(
1107
+						$calculated_total_so_far * $child_line_item->percent() / 100,
1108
+						EE_Registry::instance()->CFG->currency->dec_plc
1109
+					);
1110
+					$child_line_item->set_total($percent_total);
1111
+					//so far all percent line items should have a quantity of 1
1112
+					//(ie, no double percent discounts. Although that might be requested someday)
1113
+					$child_line_item->set_quantity(1);
1114
+					$child_line_item->maybe_save();
1115
+					$calculated_total_so_far += $percent_total;
1116
+				} else {
1117
+					//verify flat sub-line-item quantities match their parent
1118
+					if ($child_line_item->is_sub_line_item()) {
1119
+						$child_line_item->set_quantity($this->quantity());
1120
+					}
1121
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1122
+				}
1123
+			}
1124
+		}
1125
+		if ($this->is_sub_total()) {
1126
+			// no negative totals plz
1127
+			$calculated_total_so_far = max($calculated_total_so_far, 0);
1128
+		}
1129
+		return $calculated_total_so_far;
1130
+	}
1131
+
1132
+
1133
+
1134
+	/**
1135
+	 * Calculates the pretax total for a normal line item, in a round-then-sum approach
1136
+	 * (where each sub-line-item is applied to the base price for the line item
1137
+	 * and the result is immediately rounded, rather than summing all the sub-line-items
1138
+	 * then rounding, like we do when recalculating pretax totals on totals and subtotals).
1139
+	 *
1140
+	 * @param float          $calculated_total_so_far
1141
+	 * @param EE_Line_Item[] $my_children
1142
+	 * @return float
1143
+	 * @throws InvalidArgumentException
1144
+	 * @throws InvalidInterfaceException
1145
+	 * @throws InvalidDataTypeException
1146
+	 * @throws EE_Error
1147
+	 */
1148
+	protected function _recalculate_pretax_total_for_line_item($calculated_total_so_far, $my_children = null)
1149
+	{
1150
+		if ($my_children === null) {
1151
+			$my_children = $this->children();
1152
+		}
1153
+		//we need to keep track of the running total for a single item,
1154
+		//because we need to round as we go
1155
+		$unit_price_for_total = 0;
1156
+		$quantity_for_total = 1;
1157
+		//get the total of all its children
1158
+		foreach ($my_children as $child_line_item) {
1159
+			if ($child_line_item instanceof EE_Line_Item && ! $child_line_item->is_cancellation()) {
1160
+				if ($child_line_item->is_percent()) {
1161
+					//it should be the unit-price-so-far multiplied by teh percent multiplied by the quantity
1162
+					//not total multiplied by percent, because that ignores rounding along-the-way
1163
+					$percent_unit_price = round(
1164
+						$unit_price_for_total * $child_line_item->percent() / 100,
1165
+						EE_Registry::instance()->CFG->currency->dec_plc
1166
+					);
1167
+					$percent_total = $percent_unit_price * $quantity_for_total;
1168
+					$child_line_item->set_total($percent_total);
1169
+					//so far all percent line items should have a quantity of 1
1170
+					//(ie, no double percent discounts. Although that might be requested someday)
1171
+					$child_line_item->set_quantity(1);
1172
+					$child_line_item->maybe_save();
1173
+					$calculated_total_so_far += $percent_total;
1174
+					$unit_price_for_total += $percent_unit_price;
1175
+				} else {
1176
+					//verify flat sub-line-item quantities match their parent
1177
+					if ($child_line_item->is_sub_line_item()) {
1178
+						$child_line_item->set_quantity($this->quantity());
1179
+					}
1180
+					$quantity_for_total = $child_line_item->quantity();
1181
+					$calculated_total_so_far += $child_line_item->recalculate_pre_tax_total();
1182
+					$unit_price_for_total += $child_line_item->unit_price();
1183
+				}
1184
+			}
1185
+		}
1186
+		return $calculated_total_so_far;
1187
+	}
1188
+
1189
+
1190
+
1191
+	/**
1192
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1193
+	 * the totals on each tax calculated, and returns the final tax total
1194
+	 *
1195
+	 * @return float
1196
+	 * @throws EE_Error
1197
+	 */
1198
+	public function recalculate_taxes_and_tax_total()
1199
+	{
1200
+		//get all taxes
1201
+		$taxes = $this->tax_descendants();
1202
+		//calculate the pretax total
1203
+		$taxable_total = $this->taxable_total();
1204
+		$tax_total = 0;
1205
+		foreach ($taxes as $tax) {
1206
+			$total_on_this_tax = $taxable_total * $tax->percent() / 100;
1207
+			//remember the total on this line item
1208
+			$tax->set_total($total_on_this_tax);
1209
+			$tax_total += $tax->total();
1210
+		}
1211
+		$this->_recalculate_tax_sub_total();
1212
+		return $tax_total;
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
1219
+	 *
1220
+	 * @return void
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	private function _recalculate_tax_sub_total()
1224
+	{
1225
+		if ($this->is_tax_sub_total()) {
1226
+			$total = 0;
1227
+			$total_percent = 0;
1228
+			//simply loop through all its children (which should be taxes) and sum their total
1229
+			foreach ($this->children() as $child_tax) {
1230
+				if ($child_tax instanceof EE_Line_Item) {
1231
+					$total += $child_tax->total();
1232
+					$total_percent += $child_tax->percent();
1233
+				}
1234
+			}
1235
+			$this->set_total($total);
1236
+			$this->set_percent($total_percent);
1237
+		} elseif ($this->is_total()) {
1238
+			foreach ($this->children() as $maybe_tax_subtotal) {
1239
+				if ($maybe_tax_subtotal instanceof EE_Line_Item) {
1240
+					$maybe_tax_subtotal->_recalculate_tax_sub_total();
1241
+				}
1242
+			}
1243
+		}
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1250
+	 * recalculate_taxes_and_total
1251
+	 *
1252
+	 * @return float
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function get_total_tax()
1256
+	{
1257
+		$this->_recalculate_tax_sub_total();
1258
+		$total = 0;
1259
+		foreach ($this->tax_descendants() as $tax_line_item) {
1260
+			if ($tax_line_item instanceof EE_Line_Item) {
1261
+				$total += $tax_line_item->total();
1262
+			}
1263
+		}
1264
+		return $total;
1265
+	}
1266
+
1267
+
1268
+	/**
1269
+	 * Gets the total for all the items purchased only
1270
+	 *
1271
+	 * @return float
1272
+	 * @throws EE_Error
1273
+	 */
1274
+	public function get_items_total()
1275
+	{
1276
+		//by default, let's make sure we're consistent with the existing line item
1277
+		if ($this->is_total()) {
1278
+			$pretax_subtotal_li = EEH_Line_Item::get_pre_tax_subtotal($this);
1279
+			if ($pretax_subtotal_li instanceof EE_Line_Item) {
1280
+				return $pretax_subtotal_li->total();
1281
+			}
1282
+		}
1283
+		$total = 0;
1284
+		foreach ($this->get_items() as $item) {
1285
+			if ($item instanceof EE_Line_Item) {
1286
+				$total += $item->total();
1287
+			}
1288
+		}
1289
+		return $total;
1290
+	}
1291
+
1292
+
1293
+
1294
+	/**
1295
+	 * Gets all the descendants (ie, children or children of children etc) that
1296
+	 * are of the type 'tax'
1297
+	 *
1298
+	 * @return EE_Line_Item[]
1299
+	 */
1300
+	public function tax_descendants()
1301
+	{
1302
+		return EEH_Line_Item::get_tax_descendants($this);
1303
+	}
1304
+
1305
+
1306
+
1307
+	/**
1308
+	 * Gets all the real items purchased which are children of this item
1309
+	 *
1310
+	 * @return EE_Line_Item[]
1311
+	 */
1312
+	public function get_items()
1313
+	{
1314
+		return EEH_Line_Item::get_line_item_descendants($this);
1315
+	}
1316
+
1317
+
1318
+
1319
+	/**
1320
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1321
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1322
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1323
+	 * but there is a "Taxable" discount), returns 0.
1324
+	 *
1325
+	 * @return float
1326
+	 * @throws EE_Error
1327
+	 */
1328
+	public function taxable_total()
1329
+	{
1330
+		$total = 0;
1331
+		if ($this->children()) {
1332
+			foreach ($this->children() as $child_line_item) {
1333
+				if ($child_line_item->type() === EEM_Line_Item::type_line_item && $child_line_item->is_taxable()) {
1334
+					//if it's a percent item, only take into account the percent
1335
+					//that's taxable too (the taxable total so far)
1336
+					if ($child_line_item->is_percent()) {
1337
+						$total += ($total * $child_line_item->percent() / 100);
1338
+					} else {
1339
+						$total += $child_line_item->total();
1340
+					}
1341
+				} elseif ($child_line_item->type() === EEM_Line_Item::type_sub_total) {
1342
+					$total += $child_line_item->taxable_total();
1343
+				}
1344
+			}
1345
+		}
1346
+		return max($total, 0);
1347
+	}
1348
+
1349
+
1350
+
1351
+	/**
1352
+	 * Gets the transaction for this line item
1353
+	 *
1354
+	 * @return EE_Base_Class|EE_Transaction
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	public function transaction()
1358
+	{
1359
+		return $this->get_first_related('Transaction');
1360
+	}
1361
+
1362
+
1363
+
1364
+	/**
1365
+	 * Saves this line item to the DB, and recursively saves its descendants.
1366
+	 * Because there currently is no proper parent-child relation on the model,
1367
+	 * save_this_and_cached() will NOT save the descendants.
1368
+	 * Also sets the transaction on this line item and all its descendants before saving
1369
+	 *
1370
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1371
+	 * @return int count of items saved
1372
+	 * @throws EE_Error
1373
+	 */
1374
+	public function save_this_and_descendants_to_txn($txn_id = null)
1375
+	{
1376
+		$count = 0;
1377
+		if (! $txn_id) {
1378
+			$txn_id = $this->TXN_ID();
1379
+		}
1380
+		$this->set_TXN_ID($txn_id);
1381
+		$children = $this->children();
1382
+		$count += $this->save()
1383
+			? 1
1384
+			: 0;
1385
+		foreach ($children as $child_line_item) {
1386
+			if ($child_line_item instanceof EE_Line_Item) {
1387
+				$child_line_item->set_parent_ID($this->ID());
1388
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1389
+			}
1390
+		}
1391
+		return $count;
1392
+	}
1393
+
1394
+
1395
+
1396
+	/**
1397
+	 * Saves this line item to the DB, and recursively saves its descendants.
1398
+	 *
1399
+	 * @return int count of items saved
1400
+	 * @throws EE_Error
1401
+	 */
1402
+	public function save_this_and_descendants()
1403
+	{
1404
+		$count = 0;
1405
+		$children = $this->children();
1406
+		$count += $this->save()
1407
+			? 1
1408
+			: 0;
1409
+		foreach ($children as $child_line_item) {
1410
+			if ($child_line_item instanceof EE_Line_Item) {
1411
+				$child_line_item->set_parent_ID($this->ID());
1412
+				$count += $child_line_item->save_this_and_descendants();
1413
+			}
1414
+		}
1415
+		return $count;
1416
+	}
1417
+
1418
+
1419
+
1420
+	/**
1421
+	 * returns the cancellation line item if this item was cancelled
1422
+	 *
1423
+	 * @return EE_Line_Item[]
1424
+	 * @throws InvalidArgumentException
1425
+	 * @throws InvalidInterfaceException
1426
+	 * @throws InvalidDataTypeException
1427
+	 * @throws ReflectionException
1428
+	 * @throws EE_Error
1429
+	 */
1430
+	public function get_cancellations()
1431
+	{
1432
+		EE_Registry::instance()->load_helper('Line_Item');
1433
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1434
+	}
1435
+
1436
+
1437
+
1438
+	/**
1439
+	 * If this item has an ID, then this saves it again to update the db
1440
+	 *
1441
+	 * @return int count of items saved
1442
+	 * @throws EE_Error
1443
+	 */
1444
+	public function maybe_save()
1445
+	{
1446
+		if ($this->ID()) {
1447
+			return $this->save();
1448
+		}
1449
+		return false;
1450
+	}
1451
+
1452
+
1453
+	/**
1454
+	 * clears the cached children and parent from the line item
1455
+	 *
1456
+	 * @return void
1457
+	 */
1458
+	public function clear_related_line_item_cache()
1459
+	{
1460
+		$this->_children = array();
1461
+		$this->_parent = null;
1462
+	}
1463
+
1464
+
1465
+
1466
+	/**
1467
+	 * @param bool $raw
1468
+	 * @return int
1469
+	 * @throws EE_Error
1470
+	 */
1471
+	public function timestamp($raw = false)
1472
+	{
1473
+		return $raw
1474
+			? $this->get_raw('LIN_timestamp')
1475
+			: $this->get('LIN_timestamp');
1476
+	}
1477
+
1478
+
1479
+
1480
+
1481
+	/************************* DEPRECATED *************************/
1482
+	/**
1483
+	 * @deprecated 4.6.0
1484
+	 * @param string $type one of the constants on EEM_Line_Item
1485
+	 * @return EE_Line_Item[]
1486
+	 */
1487
+	protected function _get_descendants_of_type($type)
1488
+	{
1489
+		EE_Error::doing_it_wrong(
1490
+			'EE_Line_Item::_get_descendants_of_type()',
1491
+			__('Method replaced with EEH_Line_Item::get_descendants_of_type()', 'event_espresso'), '4.6.0'
1492
+		);
1493
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1494
+	}
1495
+
1496
+
1497
+
1498
+	/**
1499
+	 * @deprecated 4.6.0
1500
+	 * @param string $type like one of the EEM_Line_Item::type_*
1501
+	 * @return EE_Line_Item
1502
+	 */
1503
+	public function get_nearest_descendant_of_type($type)
1504
+	{
1505
+		EE_Error::doing_it_wrong(
1506
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1507
+			__('Method replaced with EEH_Line_Item::get_nearest_descendant_of_type()', 'event_espresso'), '4.6.0'
1508
+		);
1509
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1510
+	}
1511 1511
 
1512 1512
 
1513 1513
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
     protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
80 80
     {
81 81
         parent::__construct($fieldValues, $bydb, $timezone);
82
-        if (! $this->get('LIN_code')) {
82
+        if ( ! $this->get('LIN_code')) {
83 83
             $this->set_code($this->generate_code());
84 84
         }
85 85
     }
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
     public function name()
135 135
     {
136 136
         $name = $this->get('LIN_name');
137
-        if (! $name) {
137
+        if ( ! $name) {
138 138
             $name = ucwords(str_replace('-', ' ', $this->type()));
139 139
         }
140 140
         return $name;
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
                 )
516 516
             );
517 517
         }
518
-        if (! is_array($this->_children)) {
518
+        if ( ! is_array($this->_children)) {
519 519
             $this->_children = array();
520 520
         }
521 521
         return $this->_children;
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
     public function set_parent($line_item)
742 742
     {
743 743
         if ($this->ID()) {
744
-            if (! $line_item->ID()) {
744
+            if ( ! $line_item->ID()) {
745 745
                 $line_item->save();
746 746
             }
747 747
             $this->set_parent_ID($line_item->ID());
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
             $items_deleted = 0;
816 816
             if ($this->code() === $code) {
817 817
                 $items_deleted += EEH_Line_Item::delete_all_child_items($this);
818
-                $items_deleted += (int)$this->delete();
818
+                $items_deleted += (int) $this->delete();
819 819
                 if ($stop_search_once_found) {
820 820
                     return $items_deleted;
821 821
                 }
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
     public function generate_code()
861 861
     {
862 862
         // each line item in the cart requires a unique identifier
863
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
863
+        return md5($this->get('OBJ_type').$this->get('OBJ_ID').microtime());
864 864
     }
865 865
 
866 866
 
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
         $has_children = ! empty($my_children);
1036 1036
         if ($has_children && $this->is_line_item()) {
1037 1037
             $total = $this->_recalculate_pretax_total_for_line_item($total, $my_children);
1038
-        } elseif (! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1038
+        } elseif ( ! $has_children && ($this->is_sub_line_item() || $this->is_line_item())) {
1039 1039
             $total = $this->unit_price() * $this->quantity();
1040 1040
         } elseif ($this->is_sub_total() || $this->is_total()) {
1041 1041
             $total = $this->_recalculate_pretax_total_for_subtotal($total, $my_children);
@@ -1050,13 +1050,13 @@  discard block
 block discarded – undo
1050 1050
             if ($this->OBJ_type() !== 'Event') {
1051 1051
                 $this->set_quantity(1);
1052 1052
             }
1053
-            if (! $this->is_percent()) {
1053
+            if ( ! $this->is_percent()) {
1054 1054
                 $this->set_unit_price($total);
1055 1055
             }
1056 1056
         }
1057 1057
         //we don't want to bother saving grand totals, because that needs to factor in taxes anyways
1058 1058
         //so it ought to be
1059
-        if (! $this->is_total()) {
1059
+        if ( ! $this->is_total()) {
1060 1060
             $this->set_total($total);
1061 1061
             //if not a percent line item, make sure we keep the unit price in sync
1062 1062
             if (
@@ -1374,7 +1374,7 @@  discard block
 block discarded – undo
1374 1374
     public function save_this_and_descendants_to_txn($txn_id = null)
1375 1375
     {
1376 1376
         $count = 0;
1377
-        if (! $txn_id) {
1377
+        if ( ! $txn_id) {
1378 1378
             $txn_id = $this->TXN_ID();
1379 1379
         }
1380 1380
         $this->set_TXN_ID($txn_id);
Please login to merge, or discard this patch.
core/libraries/messages/messenger/EE_Email_messenger.class.php 2 patches
Indentation   +641 added lines, -641 removed lines patch added patch discarded remove patch
@@ -8,645 +8,645 @@
 block discarded – undo
8 8
 class EE_Email_messenger extends EE_messenger
9 9
 {
10 10
 
11
-    /**
12
-     * To field for email
13
-     * @var string
14
-     */
15
-    protected $_to = '';
16
-
17
-
18
-    /**
19
-     * CC field for email.
20
-     * @var string
21
-     */
22
-    protected $_cc = '';
23
-
24
-    /**
25
-     * From field for email
26
-     * @var string
27
-     */
28
-    protected $_from = '';
29
-
30
-
31
-    /**
32
-     * Subject field for email
33
-     * @var string
34
-     */
35
-    protected $_subject = '';
36
-
37
-
38
-    /**
39
-     * Content field for email
40
-     * @var string
41
-     */
42
-    protected $_content = '';
43
-
44
-
45
-    /**
46
-     * constructor
47
-     *
48
-     * @access public
49
-     */
50
-    public function __construct()
51
-    {
52
-        //set name and description properties
53
-        $this->name                = 'email';
54
-        $this->description         = sprintf(
55
-            esc_html__(
56
-                'This messenger delivers messages via email using the built-in %s function included with WordPress',
57
-                'event_espresso'
58
-            ),
59
-            '<code>wp_mail</code>'
60
-        );
61
-        $this->label               = array(
62
-            'singular' => esc_html__('email', 'event_espresso'),
63
-            'plural'   => esc_html__('emails', 'event_espresso'),
64
-        );
65
-        $this->activate_on_install = true;
66
-
67
-        //we're using defaults so let's call parent constructor that will take care of setting up all the other
68
-        // properties
69
-        parent::__construct();
70
-    }
71
-
72
-
73
-    /**
74
-     * see abstract declaration in parent class for details.
75
-     */
76
-    protected function _set_admin_pages()
77
-    {
78
-        $this->admin_registered_pages = array(
79
-            'events_edit' => true,
80
-        );
81
-    }
82
-
83
-
84
-    /**
85
-     * see abstract declaration in parent class for details
86
-     */
87
-    protected function _set_valid_shortcodes()
88
-    {
89
-        //remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
90
-        // message type.
91
-        $this->_valid_shortcodes = array(
92
-            'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
-            'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
94
-            'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
95
-        );
96
-    }
97
-
98
-
99
-    /**
100
-     * see abstract declaration in parent class for details
101
-     *
102
-     * @access protected
103
-     * @return void
104
-     */
105
-    protected function _set_validator_config()
106
-    {
107
-        $valid_shortcodes = $this->get_valid_shortcodes();
108
-
109
-        $this->_validator_config = array(
110
-            'to'            => array(
111
-                'shortcodes' => $valid_shortcodes['to'],
112
-                'type'       => 'email',
113
-            ),
114
-            'cc' => array(
115
-                'shortcodes' => $valid_shortcodes['to'],
116
-                'type' => 'email',
117
-            ),
118
-            'from'          => array(
119
-                'shortcodes' => $valid_shortcodes['from'],
120
-                'type'       => 'email',
121
-            ),
122
-            'subject'       => array(
123
-                'shortcodes' => array(
124
-                    'organization',
125
-                    'primary_registration_details',
126
-                    'event_author',
127
-                    'primary_registration_details',
128
-                    'recipient_details',
129
-                ),
130
-            ),
131
-            'content'       => array(
132
-                'shortcodes' => array(
133
-                    'event_list',
134
-                    'attendee_list',
135
-                    'ticket_list',
136
-                    'organization',
137
-                    'primary_registration_details',
138
-                    'primary_registration_list',
139
-                    'event_author',
140
-                    'recipient_details',
141
-                    'recipient_list',
142
-                    'transaction',
143
-                    'messenger',
144
-                ),
145
-            ),
146
-            'attendee_list' => array(
147
-                'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
148
-                'required'   => array('[ATTENDEE_LIST]'),
149
-            ),
150
-            'event_list'    => array(
151
-                'shortcodes' => array(
152
-                    'event',
153
-                    'attendee_list',
154
-                    'ticket_list',
155
-                    'venue',
156
-                    'datetime_list',
157
-                    'attendee',
158
-                    'primary_registration_details',
159
-                    'primary_registration_list',
160
-                    'event_author',
161
-                    'recipient_details',
162
-                    'recipient_list',
163
-                ),
164
-                'required'   => array('[EVENT_LIST]'),
165
-            ),
166
-            'ticket_list'   => array(
167
-                'shortcodes' => array(
168
-                    'event_list',
169
-                    'attendee_list',
170
-                    'ticket',
171
-                    'datetime_list',
172
-                    'primary_registration_details',
173
-                    'recipient_details',
174
-                ),
175
-                'required'   => array('[TICKET_LIST]'),
176
-            ),
177
-            'datetime_list' => array(
178
-                'shortcodes' => array('datetime'),
179
-                'required'   => array('[DATETIME_LIST]'),
180
-            ),
181
-        );
182
-    }
183
-
184
-
185
-    /**
186
-     * @see   parent EE_messenger class for docs
187
-     * @since 4.5.0
188
-     */
189
-    public function do_secondary_messenger_hooks($sending_messenger_name)
190
-    {
191
-        if ($sending_messenger_name = 'html') {
192
-            add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
193
-        }
194
-    }
195
-
196
-
197
-    public function add_email_css(
198
-        $variation_path,
199
-        $messenger,
200
-        $message_type,
201
-        $type,
202
-        $variation,
203
-        $file_extension,
204
-        $url,
205
-        EE_Messages_Template_Pack $template_pack
206
-    ) {
207
-        //prevent recursion on this callback.
208
-        remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
209
-        $variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
210
-
211
-        add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
212
-        return $variation;
213
-    }
214
-
215
-
216
-    /**
217
-     * See parent for details
218
-     *
219
-     * @access protected
220
-     * @return void
221
-     */
222
-    protected function _set_test_settings_fields()
223
-    {
224
-        $this->_test_settings_fields = array(
225
-            'to'      => array(
226
-                'input'      => 'text',
227
-                'label'      => esc_html__('Send a test email to', 'event_espresso'),
228
-                'type'       => 'email',
229
-                'required'   => true,
230
-                'validation' => true,
231
-                'css_class'  => 'large-text',
232
-                'format'     => '%s',
233
-                'default'    => get_bloginfo('admin_email'),
234
-            ),
235
-            'subject' => array(
236
-                'input'      => 'hidden',
237
-                'label'      => '',
238
-                'type'       => 'string',
239
-                'required'   => false,
240
-                'validation' => false,
241
-                'format'     => '%s',
242
-                'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
243
-                'default'    => '',
244
-                'css_class'  => '',
245
-            ),
246
-        );
247
-    }
248
-
249
-
250
-    /**
251
-     * _set_template_fields
252
-     * This sets up the fields that a messenger requires for the message to go out.
253
-     *
254
-     * @access  protected
255
-     * @return void
256
-     */
257
-    protected function _set_template_fields()
258
-    {
259
-        // any extra template fields that are NOT used by the messenger but will get used by a messenger field for
260
-        // shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
261
-        // they relate to.  This is important for the Messages_admin to know what fields to display to the user.
262
-        //  Also, notice that the "values" are equal to the field type that messages admin will use to know what
263
-        // kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
264
-        // indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
265
-        // displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
266
-        // will not be displayed/parsed.
267
-        $this->_template_fields = array(
268
-            'to'      => array(
269
-                'input'      => 'text',
270
-                'label'      => esc_html_x(
271
-                    'To',
272
-                    'Label for the "To" field for email addresses',
273
-                    'event_espresso'
274
-                ),
275
-                'type'       => 'string',
276
-                'required'   => true,
277
-                'validation' => true,
278
-                'css_class'  => 'large-text',
279
-                'format'     => '%s',
280
-            ),
281
-            'cc'      => array(
282
-                'input'      => 'text',
283
-                'label'      => esc_html_x(
284
-                    'CC',
285
-                    'Label for the "Carbon Copy" field used for additional email addresses',
286
-                    'event_espresso'
287
-                ),
288
-                'type'       => 'string',
289
-                'required'   => false,
290
-                'validation' => true,
291
-                'css_class'  => 'large-text',
292
-                'format'     => '%s',
293
-            ),
294
-            'from'    => array(
295
-                'input'      => 'text',
296
-                'label'      => esc_html_x(
297
-                    'From',
298
-                    'Label for the "From" field for email addresses.',
299
-                    'event_espresso'
300
-                ),
301
-                'type'       => 'string',
302
-                'required'   => true,
303
-                'validation' => true,
304
-                'css_class'  => 'large-text',
305
-                'format'     => '%s',
306
-            ),
307
-            'subject' => array(
308
-                'input'      => 'text',
309
-                'label'      => esc_html_x(
310
-                    'Subject',
311
-                    'Label for the "Subject" field (short description of contents) for emails.',
312
-                    'event_espresso'
313
-                ),
314
-                'type'       => 'string',
315
-                'required'   => true,
316
-                'validation' => true,
317
-                'css_class'  => 'large-text',
318
-                'format'     => '%s',
319
-            ),
320
-            'content' => '',
321
-            //left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
322
-            'extra'   => array(
323
-                'content' => array(
324
-                    'main'          => array(
325
-                        'input'      => 'wp_editor',
326
-                        'label'      => esc_html__('Main Content', 'event_espresso'),
327
-                        'type'       => 'string',
328
-                        'required'   => true,
329
-                        'validation' => true,
330
-                        'format'     => '%s',
331
-                        'rows'       => '15',
332
-                    ),
333
-                    'event_list'    => array(
334
-                        'input'               => 'wp_editor',
335
-                        'label'               => '[EVENT_LIST]',
336
-                        'type'                => 'string',
337
-                        'required'            => true,
338
-                        'validation'          => true,
339
-                        'format'              => '%s',
340
-                        'rows'                => '15',
341
-                        'shortcodes_required' => array('[EVENT_LIST]'),
342
-                    ),
343
-                    'attendee_list' => array(
344
-                        'input'               => 'textarea',
345
-                        'label'               => '[ATTENDEE_LIST]',
346
-                        'type'                => 'string',
347
-                        'required'            => true,
348
-                        'validation'          => true,
349
-                        'format'              => '%s',
350
-                        'css_class'           => 'large-text',
351
-                        'rows'                => '5',
352
-                        'shortcodes_required' => array('[ATTENDEE_LIST]'),
353
-                    ),
354
-                    'ticket_list'   => array(
355
-                        'input'               => 'textarea',
356
-                        'label'               => '[TICKET_LIST]',
357
-                        'type'                => 'string',
358
-                        'required'            => true,
359
-                        'validation'          => true,
360
-                        'format'              => '%s',
361
-                        'css_class'           => 'large-text',
362
-                        'rows'                => '10',
363
-                        'shortcodes_required' => array('[TICKET_LIST]'),
364
-                    ),
365
-                    'datetime_list' => array(
366
-                        'input'               => 'textarea',
367
-                        'label'               => '[DATETIME_LIST]',
368
-                        'type'                => 'string',
369
-                        'required'            => true,
370
-                        'validation'          => true,
371
-                        'format'              => '%s',
372
-                        'css_class'           => 'large-text',
373
-                        'rows'                => '10',
374
-                        'shortcodes_required' => array('[DATETIME_LIST]'),
375
-                    ),
376
-                ),
377
-            ),
378
-        );
379
-    }
380
-
381
-
382
-    /**
383
-     * See definition of this class in parent
384
-     */
385
-    protected function _set_default_message_types()
386
-    {
387
-        $this->_default_message_types = array(
388
-            'payment',
389
-            'payment_refund',
390
-            'registration',
391
-            'not_approved_registration',
392
-            'pending_approval',
393
-        );
394
-    }
395
-
396
-
397
-    /**
398
-     * @see   definition of this class in parent
399
-     * @since 4.5.0
400
-     */
401
-    protected function _set_valid_message_types()
402
-    {
403
-        $this->_valid_message_types = array(
404
-            'payment',
405
-            'registration',
406
-            'not_approved_registration',
407
-            'declined_registration',
408
-            'cancelled_registration',
409
-            'pending_approval',
410
-            'registration_summary',
411
-            'payment_reminder',
412
-            'payment_declined',
413
-            'payment_refund',
414
-        );
415
-    }
416
-
417
-
418
-    /**
419
-     * setting up admin_settings_fields for messenger.
420
-     */
421
-    protected function _set_admin_settings_fields()
422
-    {
423
-    }
424
-
425
-    /**
426
-     * We just deliver the messages don't kill us!!
427
-     *
428
-     * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
429
-     *              present.
430
-     * @throws EE_Error
431
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
432
-     */
433
-    protected function _send_message()
434
-    {
435
-        $success = wp_mail(
436
-            html_entity_decode($this->_to, ENT_QUOTES, "UTF-8"),
437
-            stripslashes(html_entity_decode($this->_subject, ENT_QUOTES, "UTF-8")),
438
-            $this->_body(),
439
-            $this->_headers()
440
-        );
441
-        if (! $success) {
442
-            EE_Error::add_error(
443
-                sprintf(
444
-                    esc_html__(
445
-                        'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
446
-                        'event_espresso'
447
-                    ),
448
-                    $this->_to,
449
-                    $this->_from,
450
-                    '<br />'
451
-                ),
452
-                __FILE__,
453
-                __FUNCTION__,
454
-                __LINE__
455
-            );
456
-        }
457
-        return $success;
458
-    }
459
-
460
-
461
-    /**
462
-     * see parent for definition
463
-     *
464
-     * @return string html body of the message content and the related css.
465
-     * @throws EE_Error
466
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
467
-     */
468
-    protected function _preview()
469
-    {
470
-        return $this->_body(true);
471
-    }
472
-
473
-
474
-    /**
475
-     * Setup headers for email
476
-     *
477
-     * @access protected
478
-     * @return string formatted header for email
479
-     */
480
-    protected function _headers()
481
-    {
482
-        $this->_ensure_has_from_email_address();
483
-        $from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
484
-        $headers = array(
485
-            'From:' . $from,
486
-            'Reply-To:' . $from,
487
-            'Content-Type:text/html; charset=utf-8',
488
-        );
489
-
490
-        if (! empty($this->_cc)) {
491
-            $headers[] = 'cc: ' . $this->_cc;
492
-        }
493
-
494
-        //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
495
-        // header.
496
-        add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
497
-        add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
498
-        return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
499
-    }
500
-
501
-
502
-    /**
503
-     * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
504
-     * address for the from address to avoid problems with sending emails.
505
-     */
506
-    protected function _ensure_has_from_email_address()
507
-    {
508
-        if (empty($this->_from)) {
509
-            $this->_from = get_bloginfo('admin_email');
510
-        }
511
-    }
512
-
513
-
514
-    /**
515
-     * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
516
-     * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
517
-     * be empty
518
-     *
519
-     * @since 4.3.1
520
-     * @return array
521
-     */
522
-    private function _parse_from()
523
-    {
524
-        if (strpos($this->_from, '<') !== false) {
525
-            $from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
526
-            $from_name = str_replace('"', '', $from_name);
527
-            $from_name = trim($from_name);
528
-
529
-            $from_email = substr($this->_from, strpos($this->_from, '<') + 1);
530
-            $from_email = str_replace('>', '', $from_email);
531
-            $from_email = trim($from_email);
532
-        } elseif (trim($this->_from) !== '') {
533
-            $from_name  = '';
534
-            $from_email = trim($this->_from);
535
-        } else {
536
-            $from_name = $from_email = '';
537
-        }
538
-        return array($from_name, $from_email);
539
-    }
540
-
541
-
542
-    /**
543
-     * Callback for the wp_mail_from filter.
544
-     *
545
-     * @since 4.3.1
546
-     * @param string $from_email What the original from_email is.
547
-     * @return string
548
-     */
549
-    public function set_from_address($from_email)
550
-    {
551
-        $parsed_from = $this->_parse_from();
552
-        //includes fallback if the parsing failed.
553
-        $from_email = is_array($parsed_from) && ! empty($parsed_from[1])
554
-            ? $parsed_from[1]
555
-            : get_bloginfo('admin_email');
556
-        return $from_email;
557
-    }
558
-
559
-
560
-    /**
561
-     * Callback fro the wp_mail_from_name filter.
562
-     *
563
-     * @since 4.3.1
564
-     * @param string $from_name The original from_name.
565
-     * @return string
566
-     */
567
-    public function set_from_name($from_name)
568
-    {
569
-        $parsed_from = $this->_parse_from();
570
-        if (is_array($parsed_from) && ! empty($parsed_from[0])) {
571
-            $from_name = $parsed_from[0];
572
-        }
573
-
574
-        //if from name is "WordPress" let's sub in the site name instead (more friendly!)
575
-        $from_name = $from_name == 'WordPress' ? get_bloginfo() : $from_name;
576
-
577
-        return stripslashes_deep(html_entity_decode($from_name, ENT_QUOTES, "UTF-8"));
578
-    }
579
-
580
-
581
-    /**
582
-     * setup body for email
583
-     *
584
-     * @param bool $preview will determine whether this is preview template or not.
585
-     * @return string formatted body for email.
586
-     * @throws EE_Error
587
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
588
-     */
589
-    protected function _body($preview = false)
590
-    {
591
-        //setup template args!
592
-        $this->_template_args = array(
593
-            'subject'   => $this->_subject,
594
-            'from'      => $this->_from,
595
-            'main_body' => wpautop(
596
-                stripslashes_deep(
597
-                    html_entity_decode($this->_content, ENT_QUOTES, "UTF-8")
598
-                )
599
-            ),
600
-        );
601
-        $body                 = $this->_get_main_template($preview);
602
-
603
-        /**
604
-         * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
605
-         *
606
-         * @type    bool $preview Indicates whether a preview is being generated or not.
607
-         * @return  bool    true  indicates to use the inliner, false bypasses it.
608
-         */
609
-        if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
610
-            //require CssToInlineStyles library and its dependencies via composer autoloader
611
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
612
-
613
-            //now if this isn't a preview, let's setup the body so it has inline styles
614
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
615
-                $style = file_get_contents(
616
-                    $this->get_variation(
617
-                        $this->_tmp_pack,
618
-                        $this->_incoming_message_type->name,
619
-                        false,
620
-                        'main',
621
-                        $this->_variation
622
-                    ),
623
-                    true
624
-                );
625
-                $CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
626
-                //for some reason the library has a bracket and new line at the beginning.  This takes care of that.
627
-                $body  = ltrim($CSS->convert(true), ">\n");
628
-                //see https://events.codebasehq.com/projects/event-espresso/tickets/8609
629
-                $body  = ltrim($body, "<?");
630
-            }
631
-
632
-        }
633
-        return $body;
634
-    }
635
-
636
-
637
-    /**
638
-     * This just returns any existing test settings that might be saved in the database
639
-     *
640
-     * @access public
641
-     * @return array
642
-     */
643
-    public function get_existing_test_settings()
644
-    {
645
-        $settings = parent::get_existing_test_settings();
646
-        //override subject if present because we always want it to be fresh.
647
-        if (is_array($settings) && ! empty($settings['subject'])) {
648
-            $settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
649
-        }
650
-        return $settings;
651
-    }
11
+	/**
12
+	 * To field for email
13
+	 * @var string
14
+	 */
15
+	protected $_to = '';
16
+
17
+
18
+	/**
19
+	 * CC field for email.
20
+	 * @var string
21
+	 */
22
+	protected $_cc = '';
23
+
24
+	/**
25
+	 * From field for email
26
+	 * @var string
27
+	 */
28
+	protected $_from = '';
29
+
30
+
31
+	/**
32
+	 * Subject field for email
33
+	 * @var string
34
+	 */
35
+	protected $_subject = '';
36
+
37
+
38
+	/**
39
+	 * Content field for email
40
+	 * @var string
41
+	 */
42
+	protected $_content = '';
43
+
44
+
45
+	/**
46
+	 * constructor
47
+	 *
48
+	 * @access public
49
+	 */
50
+	public function __construct()
51
+	{
52
+		//set name and description properties
53
+		$this->name                = 'email';
54
+		$this->description         = sprintf(
55
+			esc_html__(
56
+				'This messenger delivers messages via email using the built-in %s function included with WordPress',
57
+				'event_espresso'
58
+			),
59
+			'<code>wp_mail</code>'
60
+		);
61
+		$this->label               = array(
62
+			'singular' => esc_html__('email', 'event_espresso'),
63
+			'plural'   => esc_html__('emails', 'event_espresso'),
64
+		);
65
+		$this->activate_on_install = true;
66
+
67
+		//we're using defaults so let's call parent constructor that will take care of setting up all the other
68
+		// properties
69
+		parent::__construct();
70
+	}
71
+
72
+
73
+	/**
74
+	 * see abstract declaration in parent class for details.
75
+	 */
76
+	protected function _set_admin_pages()
77
+	{
78
+		$this->admin_registered_pages = array(
79
+			'events_edit' => true,
80
+		);
81
+	}
82
+
83
+
84
+	/**
85
+	 * see abstract declaration in parent class for details
86
+	 */
87
+	protected function _set_valid_shortcodes()
88
+	{
89
+		//remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
90
+		// message type.
91
+		$this->_valid_shortcodes = array(
92
+			'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
93
+			'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
94
+			'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
95
+		);
96
+	}
97
+
98
+
99
+	/**
100
+	 * see abstract declaration in parent class for details
101
+	 *
102
+	 * @access protected
103
+	 * @return void
104
+	 */
105
+	protected function _set_validator_config()
106
+	{
107
+		$valid_shortcodes = $this->get_valid_shortcodes();
108
+
109
+		$this->_validator_config = array(
110
+			'to'            => array(
111
+				'shortcodes' => $valid_shortcodes['to'],
112
+				'type'       => 'email',
113
+			),
114
+			'cc' => array(
115
+				'shortcodes' => $valid_shortcodes['to'],
116
+				'type' => 'email',
117
+			),
118
+			'from'          => array(
119
+				'shortcodes' => $valid_shortcodes['from'],
120
+				'type'       => 'email',
121
+			),
122
+			'subject'       => array(
123
+				'shortcodes' => array(
124
+					'organization',
125
+					'primary_registration_details',
126
+					'event_author',
127
+					'primary_registration_details',
128
+					'recipient_details',
129
+				),
130
+			),
131
+			'content'       => array(
132
+				'shortcodes' => array(
133
+					'event_list',
134
+					'attendee_list',
135
+					'ticket_list',
136
+					'organization',
137
+					'primary_registration_details',
138
+					'primary_registration_list',
139
+					'event_author',
140
+					'recipient_details',
141
+					'recipient_list',
142
+					'transaction',
143
+					'messenger',
144
+				),
145
+			),
146
+			'attendee_list' => array(
147
+				'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
148
+				'required'   => array('[ATTENDEE_LIST]'),
149
+			),
150
+			'event_list'    => array(
151
+				'shortcodes' => array(
152
+					'event',
153
+					'attendee_list',
154
+					'ticket_list',
155
+					'venue',
156
+					'datetime_list',
157
+					'attendee',
158
+					'primary_registration_details',
159
+					'primary_registration_list',
160
+					'event_author',
161
+					'recipient_details',
162
+					'recipient_list',
163
+				),
164
+				'required'   => array('[EVENT_LIST]'),
165
+			),
166
+			'ticket_list'   => array(
167
+				'shortcodes' => array(
168
+					'event_list',
169
+					'attendee_list',
170
+					'ticket',
171
+					'datetime_list',
172
+					'primary_registration_details',
173
+					'recipient_details',
174
+				),
175
+				'required'   => array('[TICKET_LIST]'),
176
+			),
177
+			'datetime_list' => array(
178
+				'shortcodes' => array('datetime'),
179
+				'required'   => array('[DATETIME_LIST]'),
180
+			),
181
+		);
182
+	}
183
+
184
+
185
+	/**
186
+	 * @see   parent EE_messenger class for docs
187
+	 * @since 4.5.0
188
+	 */
189
+	public function do_secondary_messenger_hooks($sending_messenger_name)
190
+	{
191
+		if ($sending_messenger_name = 'html') {
192
+			add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
193
+		}
194
+	}
195
+
196
+
197
+	public function add_email_css(
198
+		$variation_path,
199
+		$messenger,
200
+		$message_type,
201
+		$type,
202
+		$variation,
203
+		$file_extension,
204
+		$url,
205
+		EE_Messages_Template_Pack $template_pack
206
+	) {
207
+		//prevent recursion on this callback.
208
+		remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
209
+		$variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
210
+
211
+		add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
212
+		return $variation;
213
+	}
214
+
215
+
216
+	/**
217
+	 * See parent for details
218
+	 *
219
+	 * @access protected
220
+	 * @return void
221
+	 */
222
+	protected function _set_test_settings_fields()
223
+	{
224
+		$this->_test_settings_fields = array(
225
+			'to'      => array(
226
+				'input'      => 'text',
227
+				'label'      => esc_html__('Send a test email to', 'event_espresso'),
228
+				'type'       => 'email',
229
+				'required'   => true,
230
+				'validation' => true,
231
+				'css_class'  => 'large-text',
232
+				'format'     => '%s',
233
+				'default'    => get_bloginfo('admin_email'),
234
+			),
235
+			'subject' => array(
236
+				'input'      => 'hidden',
237
+				'label'      => '',
238
+				'type'       => 'string',
239
+				'required'   => false,
240
+				'validation' => false,
241
+				'format'     => '%s',
242
+				'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
243
+				'default'    => '',
244
+				'css_class'  => '',
245
+			),
246
+		);
247
+	}
248
+
249
+
250
+	/**
251
+	 * _set_template_fields
252
+	 * This sets up the fields that a messenger requires for the message to go out.
253
+	 *
254
+	 * @access  protected
255
+	 * @return void
256
+	 */
257
+	protected function _set_template_fields()
258
+	{
259
+		// any extra template fields that are NOT used by the messenger but will get used by a messenger field for
260
+		// shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
261
+		// they relate to.  This is important for the Messages_admin to know what fields to display to the user.
262
+		//  Also, notice that the "values" are equal to the field type that messages admin will use to know what
263
+		// kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
264
+		// indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
265
+		// displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
266
+		// will not be displayed/parsed.
267
+		$this->_template_fields = array(
268
+			'to'      => array(
269
+				'input'      => 'text',
270
+				'label'      => esc_html_x(
271
+					'To',
272
+					'Label for the "To" field for email addresses',
273
+					'event_espresso'
274
+				),
275
+				'type'       => 'string',
276
+				'required'   => true,
277
+				'validation' => true,
278
+				'css_class'  => 'large-text',
279
+				'format'     => '%s',
280
+			),
281
+			'cc'      => array(
282
+				'input'      => 'text',
283
+				'label'      => esc_html_x(
284
+					'CC',
285
+					'Label for the "Carbon Copy" field used for additional email addresses',
286
+					'event_espresso'
287
+				),
288
+				'type'       => 'string',
289
+				'required'   => false,
290
+				'validation' => true,
291
+				'css_class'  => 'large-text',
292
+				'format'     => '%s',
293
+			),
294
+			'from'    => array(
295
+				'input'      => 'text',
296
+				'label'      => esc_html_x(
297
+					'From',
298
+					'Label for the "From" field for email addresses.',
299
+					'event_espresso'
300
+				),
301
+				'type'       => 'string',
302
+				'required'   => true,
303
+				'validation' => true,
304
+				'css_class'  => 'large-text',
305
+				'format'     => '%s',
306
+			),
307
+			'subject' => array(
308
+				'input'      => 'text',
309
+				'label'      => esc_html_x(
310
+					'Subject',
311
+					'Label for the "Subject" field (short description of contents) for emails.',
312
+					'event_espresso'
313
+				),
314
+				'type'       => 'string',
315
+				'required'   => true,
316
+				'validation' => true,
317
+				'css_class'  => 'large-text',
318
+				'format'     => '%s',
319
+			),
320
+			'content' => '',
321
+			//left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
322
+			'extra'   => array(
323
+				'content' => array(
324
+					'main'          => array(
325
+						'input'      => 'wp_editor',
326
+						'label'      => esc_html__('Main Content', 'event_espresso'),
327
+						'type'       => 'string',
328
+						'required'   => true,
329
+						'validation' => true,
330
+						'format'     => '%s',
331
+						'rows'       => '15',
332
+					),
333
+					'event_list'    => array(
334
+						'input'               => 'wp_editor',
335
+						'label'               => '[EVENT_LIST]',
336
+						'type'                => 'string',
337
+						'required'            => true,
338
+						'validation'          => true,
339
+						'format'              => '%s',
340
+						'rows'                => '15',
341
+						'shortcodes_required' => array('[EVENT_LIST]'),
342
+					),
343
+					'attendee_list' => array(
344
+						'input'               => 'textarea',
345
+						'label'               => '[ATTENDEE_LIST]',
346
+						'type'                => 'string',
347
+						'required'            => true,
348
+						'validation'          => true,
349
+						'format'              => '%s',
350
+						'css_class'           => 'large-text',
351
+						'rows'                => '5',
352
+						'shortcodes_required' => array('[ATTENDEE_LIST]'),
353
+					),
354
+					'ticket_list'   => array(
355
+						'input'               => 'textarea',
356
+						'label'               => '[TICKET_LIST]',
357
+						'type'                => 'string',
358
+						'required'            => true,
359
+						'validation'          => true,
360
+						'format'              => '%s',
361
+						'css_class'           => 'large-text',
362
+						'rows'                => '10',
363
+						'shortcodes_required' => array('[TICKET_LIST]'),
364
+					),
365
+					'datetime_list' => array(
366
+						'input'               => 'textarea',
367
+						'label'               => '[DATETIME_LIST]',
368
+						'type'                => 'string',
369
+						'required'            => true,
370
+						'validation'          => true,
371
+						'format'              => '%s',
372
+						'css_class'           => 'large-text',
373
+						'rows'                => '10',
374
+						'shortcodes_required' => array('[DATETIME_LIST]'),
375
+					),
376
+				),
377
+			),
378
+		);
379
+	}
380
+
381
+
382
+	/**
383
+	 * See definition of this class in parent
384
+	 */
385
+	protected function _set_default_message_types()
386
+	{
387
+		$this->_default_message_types = array(
388
+			'payment',
389
+			'payment_refund',
390
+			'registration',
391
+			'not_approved_registration',
392
+			'pending_approval',
393
+		);
394
+	}
395
+
396
+
397
+	/**
398
+	 * @see   definition of this class in parent
399
+	 * @since 4.5.0
400
+	 */
401
+	protected function _set_valid_message_types()
402
+	{
403
+		$this->_valid_message_types = array(
404
+			'payment',
405
+			'registration',
406
+			'not_approved_registration',
407
+			'declined_registration',
408
+			'cancelled_registration',
409
+			'pending_approval',
410
+			'registration_summary',
411
+			'payment_reminder',
412
+			'payment_declined',
413
+			'payment_refund',
414
+		);
415
+	}
416
+
417
+
418
+	/**
419
+	 * setting up admin_settings_fields for messenger.
420
+	 */
421
+	protected function _set_admin_settings_fields()
422
+	{
423
+	}
424
+
425
+	/**
426
+	 * We just deliver the messages don't kill us!!
427
+	 *
428
+	 * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
429
+	 *              present.
430
+	 * @throws EE_Error
431
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
432
+	 */
433
+	protected function _send_message()
434
+	{
435
+		$success = wp_mail(
436
+			html_entity_decode($this->_to, ENT_QUOTES, "UTF-8"),
437
+			stripslashes(html_entity_decode($this->_subject, ENT_QUOTES, "UTF-8")),
438
+			$this->_body(),
439
+			$this->_headers()
440
+		);
441
+		if (! $success) {
442
+			EE_Error::add_error(
443
+				sprintf(
444
+					esc_html__(
445
+						'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
446
+						'event_espresso'
447
+					),
448
+					$this->_to,
449
+					$this->_from,
450
+					'<br />'
451
+				),
452
+				__FILE__,
453
+				__FUNCTION__,
454
+				__LINE__
455
+			);
456
+		}
457
+		return $success;
458
+	}
459
+
460
+
461
+	/**
462
+	 * see parent for definition
463
+	 *
464
+	 * @return string html body of the message content and the related css.
465
+	 * @throws EE_Error
466
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
467
+	 */
468
+	protected function _preview()
469
+	{
470
+		return $this->_body(true);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Setup headers for email
476
+	 *
477
+	 * @access protected
478
+	 * @return string formatted header for email
479
+	 */
480
+	protected function _headers()
481
+	{
482
+		$this->_ensure_has_from_email_address();
483
+		$from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
484
+		$headers = array(
485
+			'From:' . $from,
486
+			'Reply-To:' . $from,
487
+			'Content-Type:text/html; charset=utf-8',
488
+		);
489
+
490
+		if (! empty($this->_cc)) {
491
+			$headers[] = 'cc: ' . $this->_cc;
492
+		}
493
+
494
+		//but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
495
+		// header.
496
+		add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
497
+		add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
498
+		return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
499
+	}
500
+
501
+
502
+	/**
503
+	 * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
504
+	 * address for the from address to avoid problems with sending emails.
505
+	 */
506
+	protected function _ensure_has_from_email_address()
507
+	{
508
+		if (empty($this->_from)) {
509
+			$this->_from = get_bloginfo('admin_email');
510
+		}
511
+	}
512
+
513
+
514
+	/**
515
+	 * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
516
+	 * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
517
+	 * be empty
518
+	 *
519
+	 * @since 4.3.1
520
+	 * @return array
521
+	 */
522
+	private function _parse_from()
523
+	{
524
+		if (strpos($this->_from, '<') !== false) {
525
+			$from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
526
+			$from_name = str_replace('"', '', $from_name);
527
+			$from_name = trim($from_name);
528
+
529
+			$from_email = substr($this->_from, strpos($this->_from, '<') + 1);
530
+			$from_email = str_replace('>', '', $from_email);
531
+			$from_email = trim($from_email);
532
+		} elseif (trim($this->_from) !== '') {
533
+			$from_name  = '';
534
+			$from_email = trim($this->_from);
535
+		} else {
536
+			$from_name = $from_email = '';
537
+		}
538
+		return array($from_name, $from_email);
539
+	}
540
+
541
+
542
+	/**
543
+	 * Callback for the wp_mail_from filter.
544
+	 *
545
+	 * @since 4.3.1
546
+	 * @param string $from_email What the original from_email is.
547
+	 * @return string
548
+	 */
549
+	public function set_from_address($from_email)
550
+	{
551
+		$parsed_from = $this->_parse_from();
552
+		//includes fallback if the parsing failed.
553
+		$from_email = is_array($parsed_from) && ! empty($parsed_from[1])
554
+			? $parsed_from[1]
555
+			: get_bloginfo('admin_email');
556
+		return $from_email;
557
+	}
558
+
559
+
560
+	/**
561
+	 * Callback fro the wp_mail_from_name filter.
562
+	 *
563
+	 * @since 4.3.1
564
+	 * @param string $from_name The original from_name.
565
+	 * @return string
566
+	 */
567
+	public function set_from_name($from_name)
568
+	{
569
+		$parsed_from = $this->_parse_from();
570
+		if (is_array($parsed_from) && ! empty($parsed_from[0])) {
571
+			$from_name = $parsed_from[0];
572
+		}
573
+
574
+		//if from name is "WordPress" let's sub in the site name instead (more friendly!)
575
+		$from_name = $from_name == 'WordPress' ? get_bloginfo() : $from_name;
576
+
577
+		return stripslashes_deep(html_entity_decode($from_name, ENT_QUOTES, "UTF-8"));
578
+	}
579
+
580
+
581
+	/**
582
+	 * setup body for email
583
+	 *
584
+	 * @param bool $preview will determine whether this is preview template or not.
585
+	 * @return string formatted body for email.
586
+	 * @throws EE_Error
587
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
588
+	 */
589
+	protected function _body($preview = false)
590
+	{
591
+		//setup template args!
592
+		$this->_template_args = array(
593
+			'subject'   => $this->_subject,
594
+			'from'      => $this->_from,
595
+			'main_body' => wpautop(
596
+				stripslashes_deep(
597
+					html_entity_decode($this->_content, ENT_QUOTES, "UTF-8")
598
+				)
599
+			),
600
+		);
601
+		$body                 = $this->_get_main_template($preview);
602
+
603
+		/**
604
+		 * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
605
+		 *
606
+		 * @type    bool $preview Indicates whether a preview is being generated or not.
607
+		 * @return  bool    true  indicates to use the inliner, false bypasses it.
608
+		 */
609
+		if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
610
+			//require CssToInlineStyles library and its dependencies via composer autoloader
611
+			require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
612
+
613
+			//now if this isn't a preview, let's setup the body so it has inline styles
614
+			if (! $preview || ($preview && defined('DOING_AJAX'))) {
615
+				$style = file_get_contents(
616
+					$this->get_variation(
617
+						$this->_tmp_pack,
618
+						$this->_incoming_message_type->name,
619
+						false,
620
+						'main',
621
+						$this->_variation
622
+					),
623
+					true
624
+				);
625
+				$CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
626
+				//for some reason the library has a bracket and new line at the beginning.  This takes care of that.
627
+				$body  = ltrim($CSS->convert(true), ">\n");
628
+				//see https://events.codebasehq.com/projects/event-espresso/tickets/8609
629
+				$body  = ltrim($body, "<?");
630
+			}
631
+
632
+		}
633
+		return $body;
634
+	}
635
+
636
+
637
+	/**
638
+	 * This just returns any existing test settings that might be saved in the database
639
+	 *
640
+	 * @access public
641
+	 * @return array
642
+	 */
643
+	public function get_existing_test_settings()
644
+	{
645
+		$settings = parent::get_existing_test_settings();
646
+		//override subject if present because we always want it to be fresh.
647
+		if (is_array($settings) && ! empty($settings['subject'])) {
648
+			$settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
649
+		}
650
+		return $settings;
651
+	}
652 652
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
             ),
59 59
             '<code>wp_mail</code>'
60 60
         );
61
-        $this->label               = array(
61
+        $this->label = array(
62 62
             'singular' => esc_html__('email', 'event_espresso'),
63 63
             'plural'   => esc_html__('emails', 'event_espresso'),
64 64
         );
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
             $this->_body(),
439 439
             $this->_headers()
440 440
         );
441
-        if (! $success) {
441
+        if ( ! $success) {
442 442
             EE_Error::add_error(
443 443
                 sprintf(
444 444
                     esc_html__(
@@ -482,13 +482,13 @@  discard block
 block discarded – undo
482 482
         $this->_ensure_has_from_email_address();
483 483
         $from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
484 484
         $headers = array(
485
-            'From:' . $from,
486
-            'Reply-To:' . $from,
485
+            'From:'.$from,
486
+            'Reply-To:'.$from,
487 487
             'Content-Type:text/html; charset=utf-8',
488 488
         );
489 489
 
490
-        if (! empty($this->_cc)) {
491
-            $headers[] = 'cc: ' . $this->_cc;
490
+        if ( ! empty($this->_cc)) {
491
+            $headers[] = 'cc: '.$this->_cc;
492 492
         }
493 493
 
494 494
         //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
                 )
599 599
             ),
600 600
         );
601
-        $body                 = $this->_get_main_template($preview);
601
+        $body = $this->_get_main_template($preview);
602 602
 
603 603
         /**
604 604
          * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
@@ -608,10 +608,10 @@  discard block
 block discarded – undo
608 608
          */
609 609
         if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
610 610
             //require CssToInlineStyles library and its dependencies via composer autoloader
611
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
611
+            require_once EE_THIRD_PARTY.'cssinliner/vendor/autoload.php';
612 612
 
613 613
             //now if this isn't a preview, let's setup the body so it has inline styles
614
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
614
+            if ( ! $preview || ($preview && defined('DOING_AJAX'))) {
615 615
                 $style = file_get_contents(
616 616
                     $this->get_variation(
617 617
                         $this->_tmp_pack,
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 3 patches
Doc Comments   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1164,7 +1164,7 @@  discard block
 block discarded – undo
1164 1164
      * Sets deleted
1165 1165
      *
1166 1166
      * @param boolean $deleted
1167
-     * @return bool
1167
+     * @return boolean|null
1168 1168
      * @throws EE_Error
1169 1169
      * @throws RuntimeException
1170 1170
      */
@@ -1222,6 +1222,7 @@  discard block
 block discarded – undo
1222 1222
      * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1223 1223
      * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1224 1224
      *                                          consider registration status as well as datetime access.
1225
+     * @param integer $DTT_OR_ID
1225 1226
      * @return bool
1226 1227
      * @throws EE_Error
1227 1228
      */
@@ -1392,7 +1393,7 @@  discard block
 block discarded – undo
1392 1393
      * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1393 1394
      * "Latest" is defined by the `DTT_EVT_start` column.
1394 1395
      *
1395
-     * @return EE_Datetime|null
1396
+     * @return null|EE_Base_Class
1396 1397
      * @throws EE_Error
1397 1398
      */
1398 1399
     public function get_latest_related_datetime()
@@ -1688,7 +1689,7 @@  discard block
 block discarded – undo
1688 1689
      * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1689 1690
      * Note: if there are no payments on the registration there will be no payment method returned.
1690 1691
      *
1691
-     * @return EE_Payment_Method|null
1692
+     * @return null|EE_Base_Class
1692 1693
      */
1693 1694
     public function payment_method()
1694 1695
     {
Please login to merge, or discard this patch.
Indentation   +1860 added lines, -1860 removed lines patch added patch discarded remove patch
@@ -15,1866 +15,1866 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * Used to reference when a registration has never been checked in.
20
-     *
21
-     * @type int
22
-     */
23
-    const checkin_status_never = 2;
24
-
25
-    /**
26
-     * Used to reference when a registration has been checked in.
27
-     *
28
-     * @type int
29
-     */
30
-    const checkin_status_in = 1;
31
-
32
-
33
-    /**
34
-     * Used to reference when a registration has been checked out.
35
-     *
36
-     * @type int
37
-     */
38
-    const checkin_status_out = 0;
39
-
40
-
41
-    /**
42
-     * extra meta key for tracking reg status os trashed registrations
43
-     *
44
-     * @type string
45
-     */
46
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
47
-
48
-
49
-    /**
50
-     * extra meta key for tracking if registration has reserved ticket
51
-     *
52
-     * @type string
53
-     */
54
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values          incoming values
59
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
60
-     *                                        used.)
61
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
62
-     *                                        date_format and the second value is the time format
63
-     * @return EE_Registration
64
-     * @throws EE_Error
65
-     */
66
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
67
-    {
68
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
69
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
70
-    }
71
-
72
-
73
-    /**
74
-     * @param array  $props_n_values  incoming values from the database
75
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
76
-     *                                the website will be used.
77
-     * @return EE_Registration
78
-     */
79
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
80
-    {
81
-        return new self($props_n_values, true, $timezone);
82
-    }
83
-
84
-
85
-    /**
86
-     *        Set Event ID
87
-     *
88
-     * @param        int $EVT_ID Event ID
89
-     * @throws EE_Error
90
-     * @throws RuntimeException
91
-     */
92
-    public function set_event($EVT_ID = 0)
93
-    {
94
-        $this->set('EVT_ID', $EVT_ID);
95
-    }
96
-
97
-
98
-    /**
99
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
100
-     * be routed to internal methods
101
-     *
102
-     * @param string $field_name
103
-     * @param mixed  $field_value
104
-     * @param bool   $use_default
105
-     *
106
-     * @throws EE_Error
107
-     * @throws RuntimeException
108
-     */
109
-    public function set($field_name, $field_value, $use_default = false)
110
-    {
111
-        switch ($field_name) {
112
-            case 'REG_code':
113
-                if (! empty($field_value) && $this->reg_code() === null) {
114
-                    $this->set_reg_code($field_value, $use_default);
115
-                }
116
-                break;
117
-            case 'STS_ID':
118
-                $this->set_status($field_value, $use_default);
119
-                break;
120
-            default:
121
-                parent::set($field_name, $field_value, $use_default);
122
-        }
123
-    }
124
-
125
-
126
-    /**
127
-     * Set Status ID
128
-     * updates the registration status and ALSO...
129
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
130
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
131
-     *
132
-     * @param string  $new_STS_ID
133
-     * @param boolean $use_default
134
-     *
135
-     * @return bool
136
-     * @throws RuntimeException
137
-     * @throws EE_Error
138
-     */
139
-    public function set_status($new_STS_ID = null, $use_default = false)
140
-    {
141
-        // get current REG_Status
142
-        $old_STS_ID = $this->status_ID();
143
-        // if status has changed
144
-        if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
145
-            && ! empty($old_STS_ID) // and that old status is actually set
146
-            && ! empty($new_STS_ID) // as well as the new status
147
-            && $this->ID() // ensure registration is in the db
148
-        ) {
149
-            // TO approved
150
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
151
-                // reserve a space by incrementing ticket and datetime sold values
152
-                $this->_reserve_registration_space();
153
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID);
154
-                // OR FROM  approved
155
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
156
-                // release a space by decrementing ticket and datetime sold values
157
-                $this->_release_registration_space();
158
-                do_action('AHEE__EE_Registration__set_status__from_approved', $this, $old_STS_ID, $new_STS_ID);
159
-            }
160
-            // update status
161
-            parent::set('STS_ID', $new_STS_ID, $use_default);
162
-            $this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID);
163
-            /** @type EE_Transaction_Payments $transaction_payments */
164
-            $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
165
-            $transaction_payments->recalculate_transaction_total($this->transaction(), false);
166
-            $this->transaction()->update_status_based_on_total_paid(true);
167
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID);
168
-            return true;
169
-        }
170
-        //even though the old value matches the new value, it's still good to
171
-        //allow the parent set method to have a say
172
-        parent::set('STS_ID', $new_STS_ID, $use_default);
173
-        return true;
174
-    }
175
-
176
-
177
-    /**
178
-     * update REGs and TXN when cancelled or declined registrations involved
179
-     *
180
-     * @param string $new_STS_ID
181
-     * @param string $old_STS_ID
182
-     *
183
-     * @throws EE_Error
184
-     */
185
-    private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID)
186
-    {
187
-        // these reg statuses should not be considered in any calculations involving monies owing
188
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
189
-        // true if registration has been cancelled or declined
190
-        if (in_array($new_STS_ID, $closed_reg_statuses, true)
191
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
192
-        ) {
193
-            /** @type EE_Registration_Processor $registration_processor */
194
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
195
-            /** @type EE_Transaction_Processor $transaction_processor */
196
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
197
-            // cancelled or declined registration
198
-            $registration_processor->update_registration_after_being_canceled_or_declined(
199
-                $this,
200
-                $closed_reg_statuses
201
-            );
202
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
203
-                $this,
204
-                $closed_reg_statuses,
205
-                false
206
-            );
207
-            do_action('AHEE__EE_Registration__set_status__canceled_or_declined', $this, $old_STS_ID, $new_STS_ID);
208
-            return;
209
-        }
210
-        // true if reinstating cancelled or declined registration
211
-        if (in_array($old_STS_ID, $closed_reg_statuses, true)
212
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
213
-        ) {
214
-            /** @type EE_Registration_Processor $registration_processor */
215
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
216
-            /** @type EE_Transaction_Processor $transaction_processor */
217
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
218
-            // reinstating cancelled or declined registration
219
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
220
-                $this,
221
-                $closed_reg_statuses
222
-            );
223
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
224
-                $this,
225
-                $closed_reg_statuses,
226
-                false
227
-            );
228
-            do_action('AHEE__EE_Registration__set_status__after_reinstated', $this, $old_STS_ID, $new_STS_ID);
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     *        get Status ID
235
-     */
236
-    public function status_ID()
237
-    {
238
-        return $this->get('STS_ID');
239
-    }
240
-
241
-
242
-    /**
243
-     * increments this registration's related ticket sold and corresponding datetime sold values
244
-     *
245
-     * @return void
246
-     * @throws EE_Error
247
-     * @throws EntityNotFoundException
248
-     */
249
-    private function _reserve_registration_space()
250
-    {
251
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
252
-        // so stop tracking that this reg has a ticket reserved
253
-        $this->release_reserved_ticket();
254
-        $ticket = $this->ticket();
255
-        $ticket->increase_sold();
256
-        $ticket->save();
257
-        // possibly set event status to sold out
258
-        $this->event()->perform_sold_out_status_check();
259
-    }
260
-
261
-
262
-    /**
263
-     * Gets the ticket this registration is for
264
-     *
265
-     * @param boolean $include_archived whether to include archived tickets or not.
266
-     *
267
-     * @return EE_Ticket|EE_Base_Class
268
-     * @throws EE_Error
269
-     */
270
-    public function ticket($include_archived = true)
271
-    {
272
-        $query_params = array();
273
-        if ($include_archived) {
274
-            $query_params['default_where_conditions'] = 'none';
275
-        }
276
-        return $this->get_first_related('Ticket', $query_params);
277
-    }
278
-
279
-
280
-    /**
281
-     * Gets the event this registration is for
282
-     *
283
-     * @return EE_Event
284
-     * @throws EE_Error
285
-     * @throws EntityNotFoundException
286
-     */
287
-    public function event()
288
-    {
289
-        $event = $this->get_first_related('Event');
290
-        if (! $event instanceof \EE_Event) {
291
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
292
-        }
293
-        return $event;
294
-    }
295
-
296
-
297
-    /**
298
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
299
-     * with the author of the event this registration is for.
300
-     *
301
-     * @since 4.5.0
302
-     * @return int
303
-     * @throws EE_Error
304
-     * @throws EntityNotFoundException
305
-     */
306
-    public function wp_user()
307
-    {
308
-        $event = $this->event();
309
-        if ($event instanceof EE_Event) {
310
-            return $event->wp_user();
311
-        }
312
-        return 0;
313
-    }
314
-
315
-
316
-    /**
317
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
318
-     *
319
-     * @return void
320
-     * @throws EE_Error
321
-     */
322
-    private function _release_registration_space()
323
-    {
324
-        $ticket = $this->ticket();
325
-        $ticket->decrease_sold();
326
-        $ticket->save();
327
-    }
328
-
329
-
330
-    /**
331
-     * tracks this registration's ticket reservation in extra meta
332
-     * and can increment related ticket reserved and corresponding datetime reserved values
333
-     *
334
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
335
-     *
336
-     * @return void
337
-     * @throws EE_Error
338
-     */
339
-    public function reserve_ticket($update_ticket = false)
340
-    {
341
-        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) === false) {
342
-            // PLZ NOTE: although checking $update_ticket first would be more efficient,
343
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
344
-            if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) && $update_ticket) {
345
-                $ticket = $this->ticket();
346
-                $ticket->increase_reserved();
347
-                $ticket->save();
348
-            }
349
-        }
350
-    }
351
-
352
-
353
-    /**
354
-     * stops tracking this registration's ticket reservation in extra meta
355
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
356
-     *
357
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
358
-     *
359
-     * @return void
360
-     * @throws EE_Error
361
-     */
362
-    public function release_reserved_ticket($update_ticket = false)
363
-    {
364
-        if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) !== false) {
365
-            // PLZ NOTE: although checking $update_ticket first would be more efficient,
366
-            // we NEED to ALWAYS call delete_extra_meta(), which is why that is done first
367
-            if ($this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY) && $update_ticket) {
368
-                $ticket = $this->ticket();
369
-                $ticket->decrease_reserved();
370
-                $ticket->save();
371
-            }
372
-        }
373
-    }
374
-
375
-
376
-    /**
377
-     * Set Attendee ID
378
-     *
379
-     * @param        int $ATT_ID Attendee ID
380
-     * @throws EE_Error
381
-     * @throws RuntimeException
382
-     */
383
-    public function set_attendee_id($ATT_ID = 0)
384
-    {
385
-        $this->set('ATT_ID', $ATT_ID);
386
-    }
387
-
388
-
389
-    /**
390
-     *        Set Transaction ID
391
-     *
392
-     * @param        int $TXN_ID Transaction ID
393
-     * @throws EE_Error
394
-     * @throws RuntimeException
395
-     */
396
-    public function set_transaction_id($TXN_ID = 0)
397
-    {
398
-        $this->set('TXN_ID', $TXN_ID);
399
-    }
400
-
401
-
402
-    /**
403
-     *        Set Session
404
-     *
405
-     * @param    string $REG_session PHP Session ID
406
-     * @throws EE_Error
407
-     * @throws RuntimeException
408
-     */
409
-    public function set_session($REG_session = '')
410
-    {
411
-        $this->set('REG_session', $REG_session);
412
-    }
413
-
414
-
415
-    /**
416
-     *        Set Registration URL Link
417
-     *
418
-     * @param    string $REG_url_link Registration URL Link
419
-     * @throws EE_Error
420
-     * @throws RuntimeException
421
-     */
422
-    public function set_reg_url_link($REG_url_link = '')
423
-    {
424
-        $this->set('REG_url_link', $REG_url_link);
425
-    }
426
-
427
-
428
-    /**
429
-     *        Set Attendee Counter
430
-     *
431
-     * @param        int $REG_count Primary Attendee
432
-     * @throws EE_Error
433
-     * @throws RuntimeException
434
-     */
435
-    public function set_count($REG_count = 1)
436
-    {
437
-        $this->set('REG_count', $REG_count);
438
-    }
439
-
440
-
441
-    /**
442
-     *        Set Group Size
443
-     *
444
-     * @param        boolean $REG_group_size Group Registration
445
-     * @throws EE_Error
446
-     * @throws RuntimeException
447
-     */
448
-    public function set_group_size($REG_group_size = false)
449
-    {
450
-        $this->set('REG_group_size', $REG_group_size);
451
-    }
452
-
453
-
454
-    /**
455
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
456
-     *    EEM_Registration::status_id_not_approved
457
-     *
458
-     * @return        boolean
459
-     */
460
-    public function is_not_approved()
461
-    {
462
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
463
-    }
464
-
465
-
466
-    /**
467
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
468
-     *    EEM_Registration::status_id_pending_payment
469
-     *
470
-     * @return        boolean
471
-     */
472
-    public function is_pending_payment()
473
-    {
474
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
475
-    }
476
-
477
-
478
-    /**
479
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
480
-     *
481
-     * @return        boolean
482
-     */
483
-    public function is_approved()
484
-    {
485
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
486
-    }
487
-
488
-
489
-    /**
490
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
491
-     *
492
-     * @return        boolean
493
-     */
494
-    public function is_cancelled()
495
-    {
496
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
497
-    }
498
-
499
-
500
-    /**
501
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
502
-     *
503
-     * @return        boolean
504
-     */
505
-    public function is_declined()
506
-    {
507
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
508
-    }
509
-
510
-
511
-    /**
512
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
513
-     *    EEM_Registration::status_id_incomplete
514
-     *
515
-     * @return        boolean
516
-     */
517
-    public function is_incomplete()
518
-    {
519
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
520
-    }
521
-
522
-
523
-    /**
524
-     *        Set Registration Date
525
-     *
526
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
527
-     *                                                 Date
528
-     * @throws EE_Error
529
-     * @throws RuntimeException
530
-     */
531
-    public function set_reg_date($REG_date = false)
532
-    {
533
-        $this->set('REG_date', $REG_date);
534
-    }
535
-
536
-
537
-    /**
538
-     *    Set final price owing for this registration after all ticket/price modifications
539
-     *
540
-     * @access    public
541
-     * @param    float $REG_final_price
542
-     * @throws EE_Error
543
-     * @throws RuntimeException
544
-     */
545
-    public function set_final_price($REG_final_price = 0.00)
546
-    {
547
-        $this->set('REG_final_price', $REG_final_price);
548
-    }
549
-
550
-
551
-    /**
552
-     *    Set amount paid towards this registration's final price
553
-     *
554
-     * @access    public
555
-     * @param    float $REG_paid
556
-     * @throws EE_Error
557
-     * @throws RuntimeException
558
-     */
559
-    public function set_paid($REG_paid = 0.00)
560
-    {
561
-        $this->set('REG_paid', $REG_paid);
562
-    }
563
-
564
-
565
-    /**
566
-     *        Attendee Is Going
567
-     *
568
-     * @param        boolean $REG_att_is_going Attendee Is Going
569
-     * @throws EE_Error
570
-     * @throws RuntimeException
571
-     */
572
-    public function set_att_is_going($REG_att_is_going = false)
573
-    {
574
-        $this->set('REG_att_is_going', $REG_att_is_going);
575
-    }
576
-
577
-
578
-    /**
579
-     * Gets the related attendee
580
-     *
581
-     * @return EE_Attendee
582
-     * @throws EE_Error
583
-     */
584
-    public function attendee()
585
-    {
586
-        return $this->get_first_related('Attendee');
587
-    }
588
-
589
-
590
-    /**
591
-     *        get Event ID
592
-     */
593
-    public function event_ID()
594
-    {
595
-        return $this->get('EVT_ID');
596
-    }
597
-
598
-
599
-    /**
600
-     *        get Event ID
601
-     */
602
-    public function event_name()
603
-    {
604
-        $event = $this->event_obj();
605
-        if ($event) {
606
-            return $event->name();
607
-        } else {
608
-            return null;
609
-        }
610
-    }
611
-
612
-
613
-    /**
614
-     * Fetches the event this registration is for
615
-     *
616
-     * @return EE_Event
617
-     * @throws EE_Error
618
-     */
619
-    public function event_obj()
620
-    {
621
-        return $this->get_first_related('Event');
622
-    }
623
-
624
-
625
-    /**
626
-     *        get Attendee ID
627
-     */
628
-    public function attendee_ID()
629
-    {
630
-        return $this->get('ATT_ID');
631
-    }
632
-
633
-
634
-    /**
635
-     *        get PHP Session ID
636
-     */
637
-    public function session_ID()
638
-    {
639
-        return $this->get('REG_session');
640
-    }
641
-
642
-
643
-    /**
644
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
645
-     *
646
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
647
-     * @return string
648
-     */
649
-    public function receipt_url($messenger = 'html')
650
-    {
651
-
652
-        /**
653
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
654
-         * already in use on old system.  If there is then we just return the standard url for it.
655
-         *
656
-         * @since 4.5.0
657
-         */
658
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
659
-        $has_custom             = EEH_Template::locate_template(
660
-            $template_relative_path,
661
-            array(),
662
-            true,
663
-            true,
664
-            true
665
-        );
666
-
667
-        if ($has_custom) {
668
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
669
-        }
670
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
671
-    }
672
-
673
-
674
-    /**
675
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
676
-     *
677
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
678
-     * @return string
679
-     * @throws EE_Error
680
-     */
681
-    public function invoice_url($messenger = 'html')
682
-    {
683
-        /**
684
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
685
-         * already in use on old system.  If there is then we just return the standard url for it.
686
-         *
687
-         * @since 4.5.0
688
-         */
689
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
690
-        $has_custom             = EEH_Template::locate_template(
691
-            $template_relative_path,
692
-            array(),
693
-            true,
694
-            true,
695
-            true
696
-        );
697
-
698
-        if ($has_custom) {
699
-            if ($messenger == 'html') {
700
-                return $this->invoice_url('launch');
701
-            }
702
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
703
-
704
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
705
-            if ($messenger == 'html') {
706
-                $query_args['html'] = true;
707
-            }
708
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
709
-        }
710
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
711
-    }
712
-
713
-
714
-    /**
715
-     * get Registration URL Link
716
-     *
717
-     * @access public
718
-     * @return string
719
-     * @throws EE_Error
720
-     */
721
-    public function reg_url_link()
722
-    {
723
-        return (string) $this->get('REG_url_link');
724
-    }
725
-
726
-
727
-    /**
728
-     * Echoes out invoice_url()
729
-     *
730
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
731
-     * @return void
732
-     * @throws EE_Error
733
-     */
734
-    public function e_invoice_url($type = 'launch')
735
-    {
736
-        echo $this->invoice_url($type);
737
-    }
738
-
739
-
740
-    /**
741
-     * Echoes out payment_overview_url
742
-     */
743
-    public function e_payment_overview_url()
744
-    {
745
-        echo $this->payment_overview_url();
746
-    }
747
-
748
-
749
-    /**
750
-     * Gets the URL of the thank you page with this registration REG_url_link added as
751
-     * a query parameter
752
-     *
753
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
754
-     *                            payment overview url.
755
-     * @return string
756
-     * @throws EE_Error
757
-     */
758
-    public function payment_overview_url($clear_session = false)
759
-    {
760
-        return add_query_arg(array(
761
-            'e_reg_url_link' => $this->reg_url_link(),
762
-            'step'           => 'payment_options',
763
-            'revisit'        => true,
764
-            'clear_session' => (bool) $clear_session
765
-        ), EE_Registry::instance()->CFG->core->reg_page_url());
766
-    }
767
-
768
-
769
-    /**
770
-     * Gets the URL of the thank you page with this registration REG_url_link added as
771
-     * a query parameter
772
-     *
773
-     * @return string
774
-     * @throws EE_Error
775
-     */
776
-    public function edit_attendee_information_url()
777
-    {
778
-        return add_query_arg(array(
779
-            'e_reg_url_link' => $this->reg_url_link(),
780
-            'step'           => 'attendee_information',
781
-            'revisit'        => true,
782
-        ), EE_Registry::instance()->CFG->core->reg_page_url());
783
-    }
784
-
785
-
786
-    /**
787
-     * Simply generates and returns the appropriate admin_url link to edit this registration
788
-     *
789
-     * @return string
790
-     * @throws EE_Error
791
-     */
792
-    public function get_admin_edit_url()
793
-    {
794
-        return EEH_URL::add_query_args_and_nonce(array(
795
-            'page'    => 'espresso_registrations',
796
-            'action'  => 'view_registration',
797
-            '_REG_ID' => $this->ID(),
798
-        ), admin_url('admin.php'));
799
-    }
800
-
801
-
802
-    /**
803
-     *    is_primary_registrant?
804
-     */
805
-    public function is_primary_registrant()
806
-    {
807
-        return $this->get('REG_count') == 1 ? true : false;
808
-    }
809
-
810
-
811
-    /**
812
-     * This returns the primary registration object for this registration group (which may be this object).
813
-     *
814
-     * @return EE_Registration
815
-     * @throws EE_Error
816
-     */
817
-    public function get_primary_registration()
818
-    {
819
-        if ($this->is_primary_registrant()) {
820
-            return $this;
821
-        }
822
-
823
-        //k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
824
-        /** @var EE_Registration $primary_registrant */
825
-        $primary_registrant = EEM_Registration::instance()->get_one(array(
826
-            array(
827
-                'TXN_ID'    => $this->transaction_ID(),
828
-                'REG_count' => 1,
829
-            ),
830
-        ));
831
-        return $primary_registrant;
832
-    }
833
-
834
-
835
-    /**
836
-     *        get  Attendee Number
837
-     *
838
-     * @access        public
839
-     */
840
-    public function count()
841
-    {
842
-        return $this->get('REG_count');
843
-    }
844
-
845
-
846
-    /**
847
-     *        get Group Size
848
-     */
849
-    public function group_size()
850
-    {
851
-        return $this->get('REG_group_size');
852
-    }
853
-
854
-
855
-    /**
856
-     *        get Registration Date
857
-     */
858
-    public function date()
859
-    {
860
-        return $this->get('REG_date');
861
-    }
862
-
863
-
864
-    /**
865
-     * gets a pretty date
866
-     *
867
-     * @param string $date_format
868
-     * @param string $time_format
869
-     * @return string
870
-     * @throws EE_Error
871
-     */
872
-    public function pretty_date($date_format = null, $time_format = null)
873
-    {
874
-        return $this->get_datetime('REG_date', $date_format, $time_format);
875
-    }
876
-
877
-
878
-    /**
879
-     * final_price
880
-     * the registration's share of the transaction total, so that the
881
-     * sum of all the transaction's REG_final_prices equal the transaction's total
882
-     *
883
-     * @return float
884
-     * @throws EE_Error
885
-     */
886
-    public function final_price()
887
-    {
888
-        return $this->get('REG_final_price');
889
-    }
890
-
891
-
892
-    /**
893
-     * pretty_final_price
894
-     *  final price as formatted string, with correct decimal places and currency symbol
895
-     *
896
-     * @return string
897
-     * @throws EE_Error
898
-     */
899
-    public function pretty_final_price()
900
-    {
901
-        return $this->get_pretty('REG_final_price');
902
-    }
903
-
904
-
905
-    /**
906
-     * get paid (yeah)
907
-     *
908
-     * @return float
909
-     * @throws EE_Error
910
-     */
911
-    public function paid()
912
-    {
913
-        return $this->get('REG_paid');
914
-    }
915
-
916
-
917
-    /**
918
-     * pretty_paid
919
-     *
920
-     * @return float
921
-     * @throws EE_Error
922
-     */
923
-    public function pretty_paid()
924
-    {
925
-        return $this->get_pretty('REG_paid');
926
-    }
927
-
928
-
929
-    /**
930
-     * owes_monies_and_can_pay
931
-     * whether or not this registration has monies owing and it's' status allows payment
932
-     *
933
-     * @param array $requires_payment
934
-     * @return bool
935
-     * @throws EE_Error
936
-     */
937
-    public function owes_monies_and_can_pay($requires_payment = array())
938
-    {
939
-        // these reg statuses require payment (if event is not free)
940
-        $requires_payment = ! empty($requires_payment)
941
-            ? $requires_payment
942
-            : EEM_Registration::reg_statuses_that_allow_payment();
943
-        if (in_array($this->status_ID(), $requires_payment) &&
944
-            $this->final_price() != 0 &&
945
-            $this->final_price() != $this->paid()
946
-        ) {
947
-            return true;
948
-        } else {
949
-            return false;
950
-        }
951
-    }
952
-
953
-
954
-    /**
955
-     * Prints out the return value of $this->pretty_status()
956
-     *
957
-     * @param bool $show_icons
958
-     * @return void
959
-     * @throws EE_Error
960
-     */
961
-    public function e_pretty_status($show_icons = false)
962
-    {
963
-        echo $this->pretty_status($show_icons);
964
-    }
965
-
966
-
967
-    /**
968
-     * Returns a nice version of the status for displaying to customers
969
-     *
970
-     * @param bool $show_icons
971
-     * @return string
972
-     * @throws EE_Error
973
-     */
974
-    public function pretty_status($show_icons = false)
975
-    {
976
-        $status = EEM_Status::instance()->localized_status(
977
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
978
-            false,
979
-            'sentence'
980
-        );
981
-        $icon   = '';
982
-        switch ($this->status_ID()) {
983
-            case EEM_Registration::status_id_approved:
984
-                $icon = $show_icons
985
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
986
-                    : '';
987
-                break;
988
-            case EEM_Registration::status_id_pending_payment:
989
-                $icon = $show_icons
990
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
991
-                    : '';
992
-                break;
993
-            case EEM_Registration::status_id_not_approved:
994
-                $icon = $show_icons
995
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
996
-                    : '';
997
-                break;
998
-            case EEM_Registration::status_id_cancelled:
999
-                $icon = $show_icons
1000
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1001
-                    : '';
1002
-                break;
1003
-            case EEM_Registration::status_id_incomplete:
1004
-                $icon = $show_icons
1005
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1006
-                    : '';
1007
-                break;
1008
-            case EEM_Registration::status_id_declined:
1009
-                $icon = $show_icons
1010
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1011
-                    : '';
1012
-                break;
1013
-            case EEM_Registration::status_id_wait_list:
1014
-                $icon = $show_icons
1015
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1016
-                    : '';
1017
-                break;
1018
-        }
1019
-        return $icon . $status[$this->status_ID()];
1020
-    }
1021
-
1022
-
1023
-    /**
1024
-     *        get Attendee Is Going
1025
-     */
1026
-    public function att_is_going()
1027
-    {
1028
-        return $this->get('REG_att_is_going');
1029
-    }
1030
-
1031
-
1032
-    /**
1033
-     * Gets related answers
1034
-     *
1035
-     * @param array $query_params like EEM_Base::get_all
1036
-     * @return EE_Answer[]
1037
-     * @throws EE_Error
1038
-     */
1039
-    public function answers($query_params = null)
1040
-    {
1041
-        return $this->get_many_related('Answer', $query_params);
1042
-    }
1043
-
1044
-
1045
-    /**
1046
-     * Gets the registration's answer value to the specified question
1047
-     * (either the question's ID or a question object)
1048
-     *
1049
-     * @param EE_Question|int $question
1050
-     * @param bool            $pretty_value
1051
-     * @return array|string if pretty_value= true, the result will always be a string
1052
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1053
-     * will convert it into some kind of string)
1054
-     * @throws EE_Error
1055
-     */
1056
-    public function answer_value_to_question($question, $pretty_value = true)
1057
-    {
1058
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1059
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * question_groups
1065
-     * returns an array of EE_Question_Group objects for this registration
1066
-     *
1067
-     * @return EE_Question_Group[]
1068
-     * @throws EE_Error
1069
-     * @throws EntityNotFoundException
1070
-     */
1071
-    public function question_groups()
1072
-    {
1073
-        $question_groups = array();
1074
-        if ($this->event() instanceof EE_Event) {
1075
-            $question_groups = $this->event()->question_groups(
1076
-                array(
1077
-                    array(
1078
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1079
-                    ),
1080
-                    'order_by' => array('QSG_order' => 'ASC'),
1081
-                )
1082
-            );
1083
-        }
1084
-        return $question_groups;
1085
-    }
1086
-
1087
-
1088
-    /**
1089
-     * count_question_groups
1090
-     * returns a count of the number of EE_Question_Group objects for this registration
1091
-     *
1092
-     * @return int
1093
-     * @throws EE_Error
1094
-     * @throws EntityNotFoundException
1095
-     */
1096
-    public function count_question_groups()
1097
-    {
1098
-        $qg_count = 0;
1099
-        if ($this->event() instanceof EE_Event) {
1100
-            $qg_count = $this->event()->count_related(
1101
-                'Question_Group',
1102
-                array(
1103
-                    array(
1104
-                        'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1105
-                    ),
1106
-                )
1107
-            );
1108
-        }
1109
-        return $qg_count;
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * Returns the registration date in the 'standard' string format
1115
-     * (function may be improved in the future to allow for different formats and timezones)
1116
-     *
1117
-     * @return string
1118
-     * @throws EE_Error
1119
-     */
1120
-    public function reg_date()
1121
-    {
1122
-        return $this->get_datetime('REG_date');
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1128
-     * the ticket this registration purchased, or the datetime they have registered
1129
-     * to attend)
1130
-     *
1131
-     * @return EE_Datetime_Ticket
1132
-     * @throws EE_Error
1133
-     */
1134
-    public function datetime_ticket()
1135
-    {
1136
-        return $this->get_first_related('Datetime_Ticket');
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * Sets the registration's datetime_ticket.
1142
-     *
1143
-     * @param EE_Datetime_Ticket $datetime_ticket
1144
-     * @return EE_Datetime_Ticket
1145
-     * @throws EE_Error
1146
-     */
1147
-    public function set_datetime_ticket($datetime_ticket)
1148
-    {
1149
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1150
-    }
1151
-
1152
-    /**
1153
-     * Gets deleted
1154
-     *
1155
-     * @return bool
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function deleted()
1159
-    {
1160
-        return $this->get('REG_deleted');
1161
-    }
1162
-
1163
-    /**
1164
-     * Sets deleted
1165
-     *
1166
-     * @param boolean $deleted
1167
-     * @return bool
1168
-     * @throws EE_Error
1169
-     * @throws RuntimeException
1170
-     */
1171
-    public function set_deleted($deleted)
1172
-    {
1173
-        if ($deleted) {
1174
-            $this->delete();
1175
-        } else {
1176
-            $this->restore();
1177
-        }
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * Get the status object of this object
1183
-     *
1184
-     * @return EE_Status
1185
-     * @throws EE_Error
1186
-     */
1187
-    public function status_obj()
1188
-    {
1189
-        return $this->get_first_related('Status');
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * Returns the number of times this registration has checked into any of the datetimes
1195
-     * its available for
1196
-     *
1197
-     * @return int
1198
-     * @throws EE_Error
1199
-     */
1200
-    public function count_checkins()
1201
-    {
1202
-        return $this->get_model()->count_related($this, 'Checkin');
1203
-    }
1204
-
1205
-
1206
-    /**
1207
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1208
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1209
-     *
1210
-     * @return int
1211
-     * @throws EE_Error
1212
-     */
1213
-    public function count_checkins_not_checkedout()
1214
-    {
1215
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1216
-    }
1217
-
1218
-
1219
-    /**
1220
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1221
-     *
1222
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1223
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1224
-     *                                          consider registration status as well as datetime access.
1225
-     * @return bool
1226
-     * @throws EE_Error
1227
-     */
1228
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1229
-    {
1230
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1231
-
1232
-        //first check registration status
1233
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1234
-            return false;
1235
-        }
1236
-        //is there a datetime ticket that matches this dtt_ID?
1237
-        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1238
-            array(
1239
-                'TKT_ID' => $this->get('TKT_ID'),
1240
-                'DTT_ID' => $DTT_ID,
1241
-            ),
1242
-        )))
1243
-        ) {
1244
-            return false;
1245
-        }
1246
-
1247
-        //final check is against TKT_uses
1248
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1254
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1255
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1256
-     * then return false.  Otherwise return true.
1257
-     *
1258
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1259
-     * @return bool true means can checkin.  false means cannot checkin.
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1263
-    {
1264
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1265
-
1266
-        if (! $DTT_ID) {
1267
-            return false;
1268
-        }
1269
-
1270
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1271
-
1272
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1273
-        // check-in or not.
1274
-        if (! $max_uses || $max_uses === EE_INF) {
1275
-            return true;
1276
-        }
1277
-
1278
-        //does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1279
-        //go ahead and toggle.
1280
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1281
-            return true;
1282
-        }
1283
-
1284
-        //made it here so the last check is whether the number of checkins per unique datetime on this registration
1285
-        //disallows further check-ins.
1286
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1287
-            array(
1288
-                'REG_ID' => $this->ID(),
1289
-                'CHK_in' => true,
1290
-            ),
1291
-        ), 'DTT_ID', true);
1292
-        // checkins have already reached their max number of uses
1293
-        // so registrant can NOT checkin
1294
-        if ($count_unique_dtt_checkins >= $max_uses) {
1295
-            EE_Error::add_error(
1296
-                esc_html__(
1297
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1298
-                    'event_espresso'
1299
-                ),
1300
-                __FILE__,
1301
-                __FUNCTION__,
1302
-                __LINE__
1303
-            );
1304
-            return false;
1305
-        }
1306
-        return true;
1307
-    }
1308
-
1309
-
1310
-    /**
1311
-     * toggle Check-in status for this registration
1312
-     * Check-ins are toggled in the following order:
1313
-     * never checked in -> checked in
1314
-     * checked in -> checked out
1315
-     * checked out -> checked in
1316
-     *
1317
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1318
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1319
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1320
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1321
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1322
-     * @throws EE_Error
1323
-     */
1324
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1325
-    {
1326
-        if (empty($DTT_ID)) {
1327
-            $datetime = $this->get_latest_related_datetime();
1328
-            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1329
-            // verify the registration can checkin for the given DTT_ID
1330
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1331
-            EE_Error::add_error(
1332
-                sprintf(
1333
-                    esc_html__(
1334
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1335
-                        'event_espresso'
1336
-                    ),
1337
-                    $this->ID(),
1338
-                    $DTT_ID
1339
-                ),
1340
-                __FILE__,
1341
-                __FUNCTION__,
1342
-                __LINE__
1343
-            );
1344
-            return false;
1345
-        }
1346
-        $status_paths = array(
1347
-            EE_Registration::checkin_status_never => EE_Registration::checkin_status_in,
1348
-            EE_Registration::checkin_status_in    => EE_Registration::checkin_status_out,
1349
-            EE_Registration::checkin_status_out   => EE_Registration::checkin_status_in,
1350
-        );
1351
-        //start by getting the current status so we know what status we'll be changing to.
1352
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1353
-        $status_to  = $status_paths[$cur_status];
1354
-        // database only records true for checked IN or false for checked OUT
1355
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1356
-        $new_status = $status_to === EE_Registration::checkin_status_in ? true : false;
1357
-        // add relation - note Check-ins are always creating new rows
1358
-        // because we are keeping track of Check-ins over time.
1359
-        // Eventually we'll probably want to show a list table
1360
-        // for the individual Check-ins so that they can be managed.
1361
-        $checkin = EE_Checkin::new_instance(array(
1362
-            'REG_ID' => $this->ID(),
1363
-            'DTT_ID' => $DTT_ID,
1364
-            'CHK_in' => $new_status,
1365
-        ));
1366
-        // if the record could not be saved then return false
1367
-        if ($checkin->save() === 0) {
1368
-            if (WP_DEBUG) {
1369
-                global $wpdb;
1370
-                $error = sprintf(
1371
-                    esc_html__(
1372
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1373
-                        'event_espresso'
1374
-                    ),
1375
-                    '<br />',
1376
-                    $wpdb->last_error
1377
-                );
1378
-            } else {
1379
-                $error = esc_html__(
1380
-                    'Registration check in update failed because of an unknown database error',
1381
-                    'event_espresso'
1382
-                );
1383
-            }
1384
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1385
-            return false;
1386
-        }
1387
-        return $status_to;
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1393
-     * "Latest" is defined by the `DTT_EVT_start` column.
1394
-     *
1395
-     * @return EE_Datetime|null
1396
-     * @throws EE_Error
1397
-     */
1398
-    public function get_latest_related_datetime()
1399
-    {
1400
-        return EEM_Datetime::instance()->get_one(
1401
-            array(
1402
-                array(
1403
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1404
-                ),
1405
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1406
-            )
1407
-        );
1408
-    }
1409
-
1410
-
1411
-    /**
1412
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1413
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1414
-     *
1415
-     * @throws EE_Error
1416
-     */
1417
-    public function get_earliest_related_datetime()
1418
-    {
1419
-        return EEM_Datetime::instance()->get_one(
1420
-            array(
1421
-                array(
1422
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1423
-                ),
1424
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1425
-            )
1426
-        );
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * This method simply returns the check-in status for this registration and the given datetime.
1432
-     * If neither the datetime nor the checkin values are provided as arguments,
1433
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1434
-     *
1435
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1436
-     *                            (if empty we'll get the primary datetime for
1437
-     *                            this registration (via event) and use it's ID);
1438
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1439
-     *
1440
-     * @return int                Integer representing Check-in status.
1441
-     * @throws EE_Error
1442
-     */
1443
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1444
-    {
1445
-        $checkin_query_params = array(
1446
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1447
-        );
1448
-
1449
-        if ($DTT_ID > 0) {
1450
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1451
-        }
1452
-
1453
-        //get checkin object (if exists)
1454
-        $checkin = $checkin instanceof EE_Checkin
1455
-            ? $checkin
1456
-            : $this->get_first_related('Checkin', $checkin_query_params);
1457
-        if ($checkin instanceof EE_Checkin) {
1458
-            if ($checkin->get('CHK_in')) {
1459
-                return EE_Registration::checkin_status_in; //checked in
1460
-            }
1461
-            return EE_Registration::checkin_status_out; //had checked in but is now checked out.
1462
-        }
1463
-        return EE_Registration::checkin_status_never; //never been checked in
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This method returns a localized message for the toggled Check-in message.
1469
-     *
1470
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1471
-     *                     then it is assumed Check-in for primary datetime was toggled.
1472
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1473
-     *                     message can be customized with the attendee name.
1474
-     * @return string internationalized message
1475
-     * @throws EE_Error
1476
-     */
1477
-    public function get_checkin_msg($DTT_ID, $error = false)
1478
-    {
1479
-        //let's get the attendee first so we can include the name of the attendee
1480
-        $attendee = $this->get_first_related('Attendee');
1481
-        if ($attendee instanceof EE_Attendee) {
1482
-            if ($error) {
1483
-                return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1484
-            }
1485
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1486
-            //what is the status message going to be?
1487
-            switch ($cur_status) {
1488
-                case EE_Registration::checkin_status_never:
1489
-                    return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1490
-                        $attendee->full_name());
1491
-                    break;
1492
-                case EE_Registration::checkin_status_in:
1493
-                    return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1494
-                    break;
1495
-                case EE_Registration::checkin_status_out:
1496
-                    return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1497
-                    break;
1498
-            }
1499
-        }
1500
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * Returns the related EE_Transaction to this registration
1506
-     *
1507
-     * @return EE_Transaction
1508
-     * @throws EE_Error
1509
-     * @throws EntityNotFoundException
1510
-     */
1511
-    public function transaction()
1512
-    {
1513
-        $transaction = $this->get_first_related('Transaction');
1514
-        if (! $transaction instanceof \EE_Transaction) {
1515
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1516
-        }
1517
-        return $transaction;
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     *        get Registration Code
1523
-     */
1524
-    public function reg_code()
1525
-    {
1526
-        return $this->get('REG_code');
1527
-    }
1528
-
1529
-
1530
-    /**
1531
-     *        get Transaction ID
1532
-     */
1533
-    public function transaction_ID()
1534
-    {
1535
-        return $this->get('TXN_ID');
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * @return int
1541
-     * @throws EE_Error
1542
-     */
1543
-    public function ticket_ID()
1544
-    {
1545
-        return $this->get('TKT_ID');
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     *        Set Registration Code
1551
-     *
1552
-     * @access    public
1553
-     * @param    string  $REG_code Registration Code
1554
-     * @param    boolean $use_default
1555
-     * @throws EE_Error
1556
-     */
1557
-    public function set_reg_code($REG_code, $use_default = false)
1558
-    {
1559
-        if (empty($REG_code)) {
1560
-            EE_Error::add_error(
1561
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1562
-                __FILE__,
1563
-                __FUNCTION__,
1564
-                __LINE__
1565
-            );
1566
-            return;
1567
-        }
1568
-        if (! $this->reg_code()) {
1569
-            parent::set('REG_code', $REG_code, $use_default);
1570
-        } else {
1571
-            EE_Error::doing_it_wrong(
1572
-                __CLASS__ . '::' . __FUNCTION__,
1573
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1574
-                '4.6.0'
1575
-            );
1576
-        }
1577
-    }
1578
-
1579
-
1580
-    /**
1581
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1582
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1583
-     *    $registration->transaction()->registrations();
1584
-     *
1585
-     * @since 4.5.0
1586
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1587
-     * @throws EE_Error
1588
-     */
1589
-    public function get_all_other_registrations_in_group()
1590
-    {
1591
-        if ($this->group_size() < 2) {
1592
-            return array();
1593
-        }
1594
-
1595
-        $query[0] = array(
1596
-            'TXN_ID' => $this->transaction_ID(),
1597
-            'REG_ID' => array('!=', $this->ID()),
1598
-            'TKT_ID' => $this->ticket_ID(),
1599
-        );
1600
-        /** @var EE_Registration[] $registrations */
1601
-        $registrations = $this->get_model()->get_all($query);
1602
-        return $registrations;
1603
-    }
1604
-
1605
-    /**
1606
-     * Return the link to the admin details for the object.
1607
-     *
1608
-     * @return string
1609
-     * @throws EE_Error
1610
-     */
1611
-    public function get_admin_details_link()
1612
-    {
1613
-        EE_Registry::instance()->load_helper('URL');
1614
-        return EEH_URL::add_query_args_and_nonce(
1615
-            array(
1616
-                'page'    => 'espresso_registrations',
1617
-                'action'  => 'view_registration',
1618
-                '_REG_ID' => $this->ID(),
1619
-            ),
1620
-            admin_url('admin.php')
1621
-        );
1622
-    }
1623
-
1624
-    /**
1625
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1626
-     *
1627
-     * @return string
1628
-     * @throws EE_Error
1629
-     */
1630
-    public function get_admin_edit_link()
1631
-    {
1632
-        return $this->get_admin_details_link();
1633
-    }
1634
-
1635
-    /**
1636
-     * Returns the link to a settings page for the object.
1637
-     *
1638
-     * @return string
1639
-     * @throws EE_Error
1640
-     */
1641
-    public function get_admin_settings_link()
1642
-    {
1643
-        return $this->get_admin_details_link();
1644
-    }
1645
-
1646
-    /**
1647
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1648
-     *
1649
-     * @return string
1650
-     */
1651
-    public function get_admin_overview_link()
1652
-    {
1653
-        EE_Registry::instance()->load_helper('URL');
1654
-        return EEH_URL::add_query_args_and_nonce(
1655
-            array(
1656
-                'page' => 'espresso_registrations',
1657
-            ),
1658
-            admin_url('admin.php')
1659
-        );
1660
-    }
1661
-
1662
-
1663
-    /**
1664
-     * @param array $query_params
1665
-     *
1666
-     * @return \EE_Registration[]
1667
-     * @throws EE_Error
1668
-     */
1669
-    public function payments($query_params = array())
1670
-    {
1671
-        return $this->get_many_related('Payment', $query_params);
1672
-    }
1673
-
1674
-
1675
-    /**
1676
-     * @param array $query_params
1677
-     *
1678
-     * @return \EE_Registration_Payment[]
1679
-     * @throws EE_Error
1680
-     */
1681
-    public function registration_payments($query_params = array())
1682
-    {
1683
-        return $this->get_many_related('Registration_Payment', $query_params);
1684
-    }
1685
-
1686
-
1687
-    /**
1688
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1689
-     * Note: if there are no payments on the registration there will be no payment method returned.
1690
-     *
1691
-     * @return EE_Payment_Method|null
1692
-     */
1693
-    public function payment_method()
1694
-    {
1695
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1696
-    }
1697
-
1698
-
1699
-    /**
1700
-     * @return \EE_Line_Item
1701
-     * @throws EntityNotFoundException
1702
-     * @throws EE_Error
1703
-     */
1704
-    public function ticket_line_item()
1705
-    {
1706
-        $ticket            = $this->ticket();
1707
-        $transaction       = $this->transaction();
1708
-        $line_item         = null;
1709
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1710
-            $transaction->total_line_item(),
1711
-            'Ticket',
1712
-            array($ticket->ID())
1713
-        );
1714
-        foreach ($ticket_line_items as $ticket_line_item) {
1715
-            if (
1716
-                $ticket_line_item instanceof \EE_Line_Item
1717
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1718
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1719
-            ) {
1720
-                $line_item = $ticket_line_item;
1721
-                break;
1722
-            }
1723
-        }
1724
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1725
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1726
-        }
1727
-        return $line_item;
1728
-    }
1729
-
1730
-
1731
-    /**
1732
-     * Soft Deletes this model object.
1733
-     *
1734
-     * @return boolean | int
1735
-     * @throws RuntimeException
1736
-     * @throws EE_Error
1737
-     */
1738
-    public function delete()
1739
-    {
1740
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1741
-            $this->set_status(EEM_Registration::status_id_cancelled);
1742
-        }
1743
-        return parent::delete();
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1749
-     *
1750
-     * @throws EE_Error
1751
-     * @throws RuntimeException
1752
-     */
1753
-    public function restore()
1754
-    {
1755
-        $previous_status = $this->get_extra_meta(
1756
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1757
-            true,
1758
-            EEM_Registration::status_id_cancelled
1759
-        );
1760
-        if ($previous_status) {
1761
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1762
-            $this->set_status($previous_status);
1763
-        }
1764
-        return parent::restore();
1765
-    }
1766
-
1767
-
1768
-    /**
1769
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1770
-     *
1771
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1772
-     *                                           depending on whether the reg status changes to or from "Approved"
1773
-     * @return boolean whether the Registration status was updated
1774
-     * @throws EE_Error
1775
-     * @throws RuntimeException
1776
-     */
1777
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1778
-    {
1779
-        $paid = $this->paid();
1780
-        $price = $this->final_price();
1781
-        switch(true) {
1782
-            // overpaid or paid
1783
-            case EEH_Money::compare_floats($paid, $price, '>'):
1784
-            case EEH_Money::compare_floats($paid, $price):
1785
-                $new_status = EEM_Registration::status_id_approved;
1786
-                break;
1787
-            //  underpaid
1788
-            case EEH_Money::compare_floats($paid, $price, '<'):
1789
-                $new_status = EEM_Registration::status_id_pending_payment;
1790
-                break;
1791
-            // uhhh Houston...
1792
-            default:
1793
-                throw new RuntimeException(
1794
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1795
-                );
1796
-        }
1797
-        if ($new_status !== $this->status_ID()) {
1798
-            if ($trigger_set_status_logic) {
1799
-                return $this->set_status($new_status);
1800
-            }
1801
-            parent::set('STS_ID', $new_status);
1802
-            return true;
1803
-        }
1804
-        return false;
1805
-    }
1806
-
1807
-
1808
-    /*************************** DEPRECATED ***************************/
1809
-
1810
-
1811
-    /**
1812
-     * @deprecated
1813
-     * @since     4.7.0
1814
-     * @access    public
1815
-     */
1816
-    public function price_paid()
1817
-    {
1818
-        EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1819
-            esc_html__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1820
-            '4.7.0');
1821
-        return $this->final_price();
1822
-    }
1823
-
1824
-
1825
-    /**
1826
-     * @deprecated
1827
-     * @since     4.7.0
1828
-     * @access    public
1829
-     * @param    float $REG_final_price
1830
-     * @throws EE_Error
1831
-     * @throws RuntimeException
1832
-     */
1833
-    public function set_price_paid($REG_final_price = 0.00)
1834
-    {
1835
-        EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
1836
-            esc_html__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
1837
-            '4.7.0');
1838
-        $this->set_final_price($REG_final_price);
1839
-    }
1840
-
1841
-
1842
-    /**
1843
-     * @deprecated
1844
-     * @since 4.7.0
1845
-     * @return string
1846
-     * @throws EE_Error
1847
-     */
1848
-    public function pretty_price_paid()
1849
-    {
1850
-        EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
1851
-            esc_html__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
1852
-                'event_espresso'), '4.7.0');
1853
-        return $this->pretty_final_price();
1854
-    }
1855
-
1856
-
1857
-    /**
1858
-     * Gets the primary datetime related to this registration via the related Event to this registration
1859
-     *
1860
-     * @deprecated 4.9.17
1861
-     * @return EE_Datetime
1862
-     * @throws EE_Error
1863
-     * @throws EntityNotFoundException
1864
-     */
1865
-    public function get_related_primary_datetime()
1866
-    {
1867
-        EE_Error::doing_it_wrong(
1868
-            __METHOD__,
1869
-            esc_html__(
1870
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
1871
-                'event_espresso'
1872
-            ),
1873
-            '4.9.17',
1874
-            '5.0.0'
1875
-        );
1876
-        return $this->event()->primary_datetime();
1877
-    }
18
+	/**
19
+	 * Used to reference when a registration has never been checked in.
20
+	 *
21
+	 * @type int
22
+	 */
23
+	const checkin_status_never = 2;
24
+
25
+	/**
26
+	 * Used to reference when a registration has been checked in.
27
+	 *
28
+	 * @type int
29
+	 */
30
+	const checkin_status_in = 1;
31
+
32
+
33
+	/**
34
+	 * Used to reference when a registration has been checked out.
35
+	 *
36
+	 * @type int
37
+	 */
38
+	const checkin_status_out = 0;
39
+
40
+
41
+	/**
42
+	 * extra meta key for tracking reg status os trashed registrations
43
+	 *
44
+	 * @type string
45
+	 */
46
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
47
+
48
+
49
+	/**
50
+	 * extra meta key for tracking if registration has reserved ticket
51
+	 *
52
+	 * @type string
53
+	 */
54
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values          incoming values
59
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
60
+	 *                                        used.)
61
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
62
+	 *                                        date_format and the second value is the time format
63
+	 * @return EE_Registration
64
+	 * @throws EE_Error
65
+	 */
66
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
67
+	{
68
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
69
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
70
+	}
71
+
72
+
73
+	/**
74
+	 * @param array  $props_n_values  incoming values from the database
75
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
76
+	 *                                the website will be used.
77
+	 * @return EE_Registration
78
+	 */
79
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
80
+	{
81
+		return new self($props_n_values, true, $timezone);
82
+	}
83
+
84
+
85
+	/**
86
+	 *        Set Event ID
87
+	 *
88
+	 * @param        int $EVT_ID Event ID
89
+	 * @throws EE_Error
90
+	 * @throws RuntimeException
91
+	 */
92
+	public function set_event($EVT_ID = 0)
93
+	{
94
+		$this->set('EVT_ID', $EVT_ID);
95
+	}
96
+
97
+
98
+	/**
99
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
100
+	 * be routed to internal methods
101
+	 *
102
+	 * @param string $field_name
103
+	 * @param mixed  $field_value
104
+	 * @param bool   $use_default
105
+	 *
106
+	 * @throws EE_Error
107
+	 * @throws RuntimeException
108
+	 */
109
+	public function set($field_name, $field_value, $use_default = false)
110
+	{
111
+		switch ($field_name) {
112
+			case 'REG_code':
113
+				if (! empty($field_value) && $this->reg_code() === null) {
114
+					$this->set_reg_code($field_value, $use_default);
115
+				}
116
+				break;
117
+			case 'STS_ID':
118
+				$this->set_status($field_value, $use_default);
119
+				break;
120
+			default:
121
+				parent::set($field_name, $field_value, $use_default);
122
+		}
123
+	}
124
+
125
+
126
+	/**
127
+	 * Set Status ID
128
+	 * updates the registration status and ALSO...
129
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
130
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
131
+	 *
132
+	 * @param string  $new_STS_ID
133
+	 * @param boolean $use_default
134
+	 *
135
+	 * @return bool
136
+	 * @throws RuntimeException
137
+	 * @throws EE_Error
138
+	 */
139
+	public function set_status($new_STS_ID = null, $use_default = false)
140
+	{
141
+		// get current REG_Status
142
+		$old_STS_ID = $this->status_ID();
143
+		// if status has changed
144
+		if ($old_STS_ID !== $new_STS_ID // and that status has actually changed
145
+			&& ! empty($old_STS_ID) // and that old status is actually set
146
+			&& ! empty($new_STS_ID) // as well as the new status
147
+			&& $this->ID() // ensure registration is in the db
148
+		) {
149
+			// TO approved
150
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
151
+				// reserve a space by incrementing ticket and datetime sold values
152
+				$this->_reserve_registration_space();
153
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID);
154
+				// OR FROM  approved
155
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
156
+				// release a space by decrementing ticket and datetime sold values
157
+				$this->_release_registration_space();
158
+				do_action('AHEE__EE_Registration__set_status__from_approved', $this, $old_STS_ID, $new_STS_ID);
159
+			}
160
+			// update status
161
+			parent::set('STS_ID', $new_STS_ID, $use_default);
162
+			$this->_update_if_canceled_or_declined($new_STS_ID, $old_STS_ID);
163
+			/** @type EE_Transaction_Payments $transaction_payments */
164
+			$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
165
+			$transaction_payments->recalculate_transaction_total($this->transaction(), false);
166
+			$this->transaction()->update_status_based_on_total_paid(true);
167
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID);
168
+			return true;
169
+		}
170
+		//even though the old value matches the new value, it's still good to
171
+		//allow the parent set method to have a say
172
+		parent::set('STS_ID', $new_STS_ID, $use_default);
173
+		return true;
174
+	}
175
+
176
+
177
+	/**
178
+	 * update REGs and TXN when cancelled or declined registrations involved
179
+	 *
180
+	 * @param string $new_STS_ID
181
+	 * @param string $old_STS_ID
182
+	 *
183
+	 * @throws EE_Error
184
+	 */
185
+	private function _update_if_canceled_or_declined($new_STS_ID, $old_STS_ID)
186
+	{
187
+		// these reg statuses should not be considered in any calculations involving monies owing
188
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
189
+		// true if registration has been cancelled or declined
190
+		if (in_array($new_STS_ID, $closed_reg_statuses, true)
191
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
192
+		) {
193
+			/** @type EE_Registration_Processor $registration_processor */
194
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
195
+			/** @type EE_Transaction_Processor $transaction_processor */
196
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
197
+			// cancelled or declined registration
198
+			$registration_processor->update_registration_after_being_canceled_or_declined(
199
+				$this,
200
+				$closed_reg_statuses
201
+			);
202
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
203
+				$this,
204
+				$closed_reg_statuses,
205
+				false
206
+			);
207
+			do_action('AHEE__EE_Registration__set_status__canceled_or_declined', $this, $old_STS_ID, $new_STS_ID);
208
+			return;
209
+		}
210
+		// true if reinstating cancelled or declined registration
211
+		if (in_array($old_STS_ID, $closed_reg_statuses, true)
212
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
213
+		) {
214
+			/** @type EE_Registration_Processor $registration_processor */
215
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
216
+			/** @type EE_Transaction_Processor $transaction_processor */
217
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
218
+			// reinstating cancelled or declined registration
219
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
220
+				$this,
221
+				$closed_reg_statuses
222
+			);
223
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
224
+				$this,
225
+				$closed_reg_statuses,
226
+				false
227
+			);
228
+			do_action('AHEE__EE_Registration__set_status__after_reinstated', $this, $old_STS_ID, $new_STS_ID);
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 *        get Status ID
235
+	 */
236
+	public function status_ID()
237
+	{
238
+		return $this->get('STS_ID');
239
+	}
240
+
241
+
242
+	/**
243
+	 * increments this registration's related ticket sold and corresponding datetime sold values
244
+	 *
245
+	 * @return void
246
+	 * @throws EE_Error
247
+	 * @throws EntityNotFoundException
248
+	 */
249
+	private function _reserve_registration_space()
250
+	{
251
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
252
+		// so stop tracking that this reg has a ticket reserved
253
+		$this->release_reserved_ticket();
254
+		$ticket = $this->ticket();
255
+		$ticket->increase_sold();
256
+		$ticket->save();
257
+		// possibly set event status to sold out
258
+		$this->event()->perform_sold_out_status_check();
259
+	}
260
+
261
+
262
+	/**
263
+	 * Gets the ticket this registration is for
264
+	 *
265
+	 * @param boolean $include_archived whether to include archived tickets or not.
266
+	 *
267
+	 * @return EE_Ticket|EE_Base_Class
268
+	 * @throws EE_Error
269
+	 */
270
+	public function ticket($include_archived = true)
271
+	{
272
+		$query_params = array();
273
+		if ($include_archived) {
274
+			$query_params['default_where_conditions'] = 'none';
275
+		}
276
+		return $this->get_first_related('Ticket', $query_params);
277
+	}
278
+
279
+
280
+	/**
281
+	 * Gets the event this registration is for
282
+	 *
283
+	 * @return EE_Event
284
+	 * @throws EE_Error
285
+	 * @throws EntityNotFoundException
286
+	 */
287
+	public function event()
288
+	{
289
+		$event = $this->get_first_related('Event');
290
+		if (! $event instanceof \EE_Event) {
291
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
292
+		}
293
+		return $event;
294
+	}
295
+
296
+
297
+	/**
298
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
299
+	 * with the author of the event this registration is for.
300
+	 *
301
+	 * @since 4.5.0
302
+	 * @return int
303
+	 * @throws EE_Error
304
+	 * @throws EntityNotFoundException
305
+	 */
306
+	public function wp_user()
307
+	{
308
+		$event = $this->event();
309
+		if ($event instanceof EE_Event) {
310
+			return $event->wp_user();
311
+		}
312
+		return 0;
313
+	}
314
+
315
+
316
+	/**
317
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
318
+	 *
319
+	 * @return void
320
+	 * @throws EE_Error
321
+	 */
322
+	private function _release_registration_space()
323
+	{
324
+		$ticket = $this->ticket();
325
+		$ticket->decrease_sold();
326
+		$ticket->save();
327
+	}
328
+
329
+
330
+	/**
331
+	 * tracks this registration's ticket reservation in extra meta
332
+	 * and can increment related ticket reserved and corresponding datetime reserved values
333
+	 *
334
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
335
+	 *
336
+	 * @return void
337
+	 * @throws EE_Error
338
+	 */
339
+	public function reserve_ticket($update_ticket = false)
340
+	{
341
+		if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) === false) {
342
+			// PLZ NOTE: although checking $update_ticket first would be more efficient,
343
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
344
+			if ($this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) && $update_ticket) {
345
+				$ticket = $this->ticket();
346
+				$ticket->increase_reserved();
347
+				$ticket->save();
348
+			}
349
+		}
350
+	}
351
+
352
+
353
+	/**
354
+	 * stops tracking this registration's ticket reservation in extra meta
355
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
356
+	 *
357
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
358
+	 *
359
+	 * @return void
360
+	 * @throws EE_Error
361
+	 */
362
+	public function release_reserved_ticket($update_ticket = false)
363
+	{
364
+		if ($this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true, false) !== false) {
365
+			// PLZ NOTE: although checking $update_ticket first would be more efficient,
366
+			// we NEED to ALWAYS call delete_extra_meta(), which is why that is done first
367
+			if ($this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY) && $update_ticket) {
368
+				$ticket = $this->ticket();
369
+				$ticket->decrease_reserved();
370
+				$ticket->save();
371
+			}
372
+		}
373
+	}
374
+
375
+
376
+	/**
377
+	 * Set Attendee ID
378
+	 *
379
+	 * @param        int $ATT_ID Attendee ID
380
+	 * @throws EE_Error
381
+	 * @throws RuntimeException
382
+	 */
383
+	public function set_attendee_id($ATT_ID = 0)
384
+	{
385
+		$this->set('ATT_ID', $ATT_ID);
386
+	}
387
+
388
+
389
+	/**
390
+	 *        Set Transaction ID
391
+	 *
392
+	 * @param        int $TXN_ID Transaction ID
393
+	 * @throws EE_Error
394
+	 * @throws RuntimeException
395
+	 */
396
+	public function set_transaction_id($TXN_ID = 0)
397
+	{
398
+		$this->set('TXN_ID', $TXN_ID);
399
+	}
400
+
401
+
402
+	/**
403
+	 *        Set Session
404
+	 *
405
+	 * @param    string $REG_session PHP Session ID
406
+	 * @throws EE_Error
407
+	 * @throws RuntimeException
408
+	 */
409
+	public function set_session($REG_session = '')
410
+	{
411
+		$this->set('REG_session', $REG_session);
412
+	}
413
+
414
+
415
+	/**
416
+	 *        Set Registration URL Link
417
+	 *
418
+	 * @param    string $REG_url_link Registration URL Link
419
+	 * @throws EE_Error
420
+	 * @throws RuntimeException
421
+	 */
422
+	public function set_reg_url_link($REG_url_link = '')
423
+	{
424
+		$this->set('REG_url_link', $REG_url_link);
425
+	}
426
+
427
+
428
+	/**
429
+	 *        Set Attendee Counter
430
+	 *
431
+	 * @param        int $REG_count Primary Attendee
432
+	 * @throws EE_Error
433
+	 * @throws RuntimeException
434
+	 */
435
+	public function set_count($REG_count = 1)
436
+	{
437
+		$this->set('REG_count', $REG_count);
438
+	}
439
+
440
+
441
+	/**
442
+	 *        Set Group Size
443
+	 *
444
+	 * @param        boolean $REG_group_size Group Registration
445
+	 * @throws EE_Error
446
+	 * @throws RuntimeException
447
+	 */
448
+	public function set_group_size($REG_group_size = false)
449
+	{
450
+		$this->set('REG_group_size', $REG_group_size);
451
+	}
452
+
453
+
454
+	/**
455
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
456
+	 *    EEM_Registration::status_id_not_approved
457
+	 *
458
+	 * @return        boolean
459
+	 */
460
+	public function is_not_approved()
461
+	{
462
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
463
+	}
464
+
465
+
466
+	/**
467
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
468
+	 *    EEM_Registration::status_id_pending_payment
469
+	 *
470
+	 * @return        boolean
471
+	 */
472
+	public function is_pending_payment()
473
+	{
474
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
475
+	}
476
+
477
+
478
+	/**
479
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
480
+	 *
481
+	 * @return        boolean
482
+	 */
483
+	public function is_approved()
484
+	{
485
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
486
+	}
487
+
488
+
489
+	/**
490
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
491
+	 *
492
+	 * @return        boolean
493
+	 */
494
+	public function is_cancelled()
495
+	{
496
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
497
+	}
498
+
499
+
500
+	/**
501
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
502
+	 *
503
+	 * @return        boolean
504
+	 */
505
+	public function is_declined()
506
+	{
507
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
508
+	}
509
+
510
+
511
+	/**
512
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
513
+	 *    EEM_Registration::status_id_incomplete
514
+	 *
515
+	 * @return        boolean
516
+	 */
517
+	public function is_incomplete()
518
+	{
519
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
520
+	}
521
+
522
+
523
+	/**
524
+	 *        Set Registration Date
525
+	 *
526
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
527
+	 *                                                 Date
528
+	 * @throws EE_Error
529
+	 * @throws RuntimeException
530
+	 */
531
+	public function set_reg_date($REG_date = false)
532
+	{
533
+		$this->set('REG_date', $REG_date);
534
+	}
535
+
536
+
537
+	/**
538
+	 *    Set final price owing for this registration after all ticket/price modifications
539
+	 *
540
+	 * @access    public
541
+	 * @param    float $REG_final_price
542
+	 * @throws EE_Error
543
+	 * @throws RuntimeException
544
+	 */
545
+	public function set_final_price($REG_final_price = 0.00)
546
+	{
547
+		$this->set('REG_final_price', $REG_final_price);
548
+	}
549
+
550
+
551
+	/**
552
+	 *    Set amount paid towards this registration's final price
553
+	 *
554
+	 * @access    public
555
+	 * @param    float $REG_paid
556
+	 * @throws EE_Error
557
+	 * @throws RuntimeException
558
+	 */
559
+	public function set_paid($REG_paid = 0.00)
560
+	{
561
+		$this->set('REG_paid', $REG_paid);
562
+	}
563
+
564
+
565
+	/**
566
+	 *        Attendee Is Going
567
+	 *
568
+	 * @param        boolean $REG_att_is_going Attendee Is Going
569
+	 * @throws EE_Error
570
+	 * @throws RuntimeException
571
+	 */
572
+	public function set_att_is_going($REG_att_is_going = false)
573
+	{
574
+		$this->set('REG_att_is_going', $REG_att_is_going);
575
+	}
576
+
577
+
578
+	/**
579
+	 * Gets the related attendee
580
+	 *
581
+	 * @return EE_Attendee
582
+	 * @throws EE_Error
583
+	 */
584
+	public function attendee()
585
+	{
586
+		return $this->get_first_related('Attendee');
587
+	}
588
+
589
+
590
+	/**
591
+	 *        get Event ID
592
+	 */
593
+	public function event_ID()
594
+	{
595
+		return $this->get('EVT_ID');
596
+	}
597
+
598
+
599
+	/**
600
+	 *        get Event ID
601
+	 */
602
+	public function event_name()
603
+	{
604
+		$event = $this->event_obj();
605
+		if ($event) {
606
+			return $event->name();
607
+		} else {
608
+			return null;
609
+		}
610
+	}
611
+
612
+
613
+	/**
614
+	 * Fetches the event this registration is for
615
+	 *
616
+	 * @return EE_Event
617
+	 * @throws EE_Error
618
+	 */
619
+	public function event_obj()
620
+	{
621
+		return $this->get_first_related('Event');
622
+	}
623
+
624
+
625
+	/**
626
+	 *        get Attendee ID
627
+	 */
628
+	public function attendee_ID()
629
+	{
630
+		return $this->get('ATT_ID');
631
+	}
632
+
633
+
634
+	/**
635
+	 *        get PHP Session ID
636
+	 */
637
+	public function session_ID()
638
+	{
639
+		return $this->get('REG_session');
640
+	}
641
+
642
+
643
+	/**
644
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
645
+	 *
646
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
647
+	 * @return string
648
+	 */
649
+	public function receipt_url($messenger = 'html')
650
+	{
651
+
652
+		/**
653
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
654
+		 * already in use on old system.  If there is then we just return the standard url for it.
655
+		 *
656
+		 * @since 4.5.0
657
+		 */
658
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
659
+		$has_custom             = EEH_Template::locate_template(
660
+			$template_relative_path,
661
+			array(),
662
+			true,
663
+			true,
664
+			true
665
+		);
666
+
667
+		if ($has_custom) {
668
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
669
+		}
670
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
671
+	}
672
+
673
+
674
+	/**
675
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
676
+	 *
677
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
678
+	 * @return string
679
+	 * @throws EE_Error
680
+	 */
681
+	public function invoice_url($messenger = 'html')
682
+	{
683
+		/**
684
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
685
+		 * already in use on old system.  If there is then we just return the standard url for it.
686
+		 *
687
+		 * @since 4.5.0
688
+		 */
689
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
690
+		$has_custom             = EEH_Template::locate_template(
691
+			$template_relative_path,
692
+			array(),
693
+			true,
694
+			true,
695
+			true
696
+		);
697
+
698
+		if ($has_custom) {
699
+			if ($messenger == 'html') {
700
+				return $this->invoice_url('launch');
701
+			}
702
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
703
+
704
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
705
+			if ($messenger == 'html') {
706
+				$query_args['html'] = true;
707
+			}
708
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
709
+		}
710
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
711
+	}
712
+
713
+
714
+	/**
715
+	 * get Registration URL Link
716
+	 *
717
+	 * @access public
718
+	 * @return string
719
+	 * @throws EE_Error
720
+	 */
721
+	public function reg_url_link()
722
+	{
723
+		return (string) $this->get('REG_url_link');
724
+	}
725
+
726
+
727
+	/**
728
+	 * Echoes out invoice_url()
729
+	 *
730
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
731
+	 * @return void
732
+	 * @throws EE_Error
733
+	 */
734
+	public function e_invoice_url($type = 'launch')
735
+	{
736
+		echo $this->invoice_url($type);
737
+	}
738
+
739
+
740
+	/**
741
+	 * Echoes out payment_overview_url
742
+	 */
743
+	public function e_payment_overview_url()
744
+	{
745
+		echo $this->payment_overview_url();
746
+	}
747
+
748
+
749
+	/**
750
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
751
+	 * a query parameter
752
+	 *
753
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
754
+	 *                            payment overview url.
755
+	 * @return string
756
+	 * @throws EE_Error
757
+	 */
758
+	public function payment_overview_url($clear_session = false)
759
+	{
760
+		return add_query_arg(array(
761
+			'e_reg_url_link' => $this->reg_url_link(),
762
+			'step'           => 'payment_options',
763
+			'revisit'        => true,
764
+			'clear_session' => (bool) $clear_session
765
+		), EE_Registry::instance()->CFG->core->reg_page_url());
766
+	}
767
+
768
+
769
+	/**
770
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
771
+	 * a query parameter
772
+	 *
773
+	 * @return string
774
+	 * @throws EE_Error
775
+	 */
776
+	public function edit_attendee_information_url()
777
+	{
778
+		return add_query_arg(array(
779
+			'e_reg_url_link' => $this->reg_url_link(),
780
+			'step'           => 'attendee_information',
781
+			'revisit'        => true,
782
+		), EE_Registry::instance()->CFG->core->reg_page_url());
783
+	}
784
+
785
+
786
+	/**
787
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
788
+	 *
789
+	 * @return string
790
+	 * @throws EE_Error
791
+	 */
792
+	public function get_admin_edit_url()
793
+	{
794
+		return EEH_URL::add_query_args_and_nonce(array(
795
+			'page'    => 'espresso_registrations',
796
+			'action'  => 'view_registration',
797
+			'_REG_ID' => $this->ID(),
798
+		), admin_url('admin.php'));
799
+	}
800
+
801
+
802
+	/**
803
+	 *    is_primary_registrant?
804
+	 */
805
+	public function is_primary_registrant()
806
+	{
807
+		return $this->get('REG_count') == 1 ? true : false;
808
+	}
809
+
810
+
811
+	/**
812
+	 * This returns the primary registration object for this registration group (which may be this object).
813
+	 *
814
+	 * @return EE_Registration
815
+	 * @throws EE_Error
816
+	 */
817
+	public function get_primary_registration()
818
+	{
819
+		if ($this->is_primary_registrant()) {
820
+			return $this;
821
+		}
822
+
823
+		//k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
824
+		/** @var EE_Registration $primary_registrant */
825
+		$primary_registrant = EEM_Registration::instance()->get_one(array(
826
+			array(
827
+				'TXN_ID'    => $this->transaction_ID(),
828
+				'REG_count' => 1,
829
+			),
830
+		));
831
+		return $primary_registrant;
832
+	}
833
+
834
+
835
+	/**
836
+	 *        get  Attendee Number
837
+	 *
838
+	 * @access        public
839
+	 */
840
+	public function count()
841
+	{
842
+		return $this->get('REG_count');
843
+	}
844
+
845
+
846
+	/**
847
+	 *        get Group Size
848
+	 */
849
+	public function group_size()
850
+	{
851
+		return $this->get('REG_group_size');
852
+	}
853
+
854
+
855
+	/**
856
+	 *        get Registration Date
857
+	 */
858
+	public function date()
859
+	{
860
+		return $this->get('REG_date');
861
+	}
862
+
863
+
864
+	/**
865
+	 * gets a pretty date
866
+	 *
867
+	 * @param string $date_format
868
+	 * @param string $time_format
869
+	 * @return string
870
+	 * @throws EE_Error
871
+	 */
872
+	public function pretty_date($date_format = null, $time_format = null)
873
+	{
874
+		return $this->get_datetime('REG_date', $date_format, $time_format);
875
+	}
876
+
877
+
878
+	/**
879
+	 * final_price
880
+	 * the registration's share of the transaction total, so that the
881
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
882
+	 *
883
+	 * @return float
884
+	 * @throws EE_Error
885
+	 */
886
+	public function final_price()
887
+	{
888
+		return $this->get('REG_final_price');
889
+	}
890
+
891
+
892
+	/**
893
+	 * pretty_final_price
894
+	 *  final price as formatted string, with correct decimal places and currency symbol
895
+	 *
896
+	 * @return string
897
+	 * @throws EE_Error
898
+	 */
899
+	public function pretty_final_price()
900
+	{
901
+		return $this->get_pretty('REG_final_price');
902
+	}
903
+
904
+
905
+	/**
906
+	 * get paid (yeah)
907
+	 *
908
+	 * @return float
909
+	 * @throws EE_Error
910
+	 */
911
+	public function paid()
912
+	{
913
+		return $this->get('REG_paid');
914
+	}
915
+
916
+
917
+	/**
918
+	 * pretty_paid
919
+	 *
920
+	 * @return float
921
+	 * @throws EE_Error
922
+	 */
923
+	public function pretty_paid()
924
+	{
925
+		return $this->get_pretty('REG_paid');
926
+	}
927
+
928
+
929
+	/**
930
+	 * owes_monies_and_can_pay
931
+	 * whether or not this registration has monies owing and it's' status allows payment
932
+	 *
933
+	 * @param array $requires_payment
934
+	 * @return bool
935
+	 * @throws EE_Error
936
+	 */
937
+	public function owes_monies_and_can_pay($requires_payment = array())
938
+	{
939
+		// these reg statuses require payment (if event is not free)
940
+		$requires_payment = ! empty($requires_payment)
941
+			? $requires_payment
942
+			: EEM_Registration::reg_statuses_that_allow_payment();
943
+		if (in_array($this->status_ID(), $requires_payment) &&
944
+			$this->final_price() != 0 &&
945
+			$this->final_price() != $this->paid()
946
+		) {
947
+			return true;
948
+		} else {
949
+			return false;
950
+		}
951
+	}
952
+
953
+
954
+	/**
955
+	 * Prints out the return value of $this->pretty_status()
956
+	 *
957
+	 * @param bool $show_icons
958
+	 * @return void
959
+	 * @throws EE_Error
960
+	 */
961
+	public function e_pretty_status($show_icons = false)
962
+	{
963
+		echo $this->pretty_status($show_icons);
964
+	}
965
+
966
+
967
+	/**
968
+	 * Returns a nice version of the status for displaying to customers
969
+	 *
970
+	 * @param bool $show_icons
971
+	 * @return string
972
+	 * @throws EE_Error
973
+	 */
974
+	public function pretty_status($show_icons = false)
975
+	{
976
+		$status = EEM_Status::instance()->localized_status(
977
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
978
+			false,
979
+			'sentence'
980
+		);
981
+		$icon   = '';
982
+		switch ($this->status_ID()) {
983
+			case EEM_Registration::status_id_approved:
984
+				$icon = $show_icons
985
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
986
+					: '';
987
+				break;
988
+			case EEM_Registration::status_id_pending_payment:
989
+				$icon = $show_icons
990
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
991
+					: '';
992
+				break;
993
+			case EEM_Registration::status_id_not_approved:
994
+				$icon = $show_icons
995
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
996
+					: '';
997
+				break;
998
+			case EEM_Registration::status_id_cancelled:
999
+				$icon = $show_icons
1000
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1001
+					: '';
1002
+				break;
1003
+			case EEM_Registration::status_id_incomplete:
1004
+				$icon = $show_icons
1005
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1006
+					: '';
1007
+				break;
1008
+			case EEM_Registration::status_id_declined:
1009
+				$icon = $show_icons
1010
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1011
+					: '';
1012
+				break;
1013
+			case EEM_Registration::status_id_wait_list:
1014
+				$icon = $show_icons
1015
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1016
+					: '';
1017
+				break;
1018
+		}
1019
+		return $icon . $status[$this->status_ID()];
1020
+	}
1021
+
1022
+
1023
+	/**
1024
+	 *        get Attendee Is Going
1025
+	 */
1026
+	public function att_is_going()
1027
+	{
1028
+		return $this->get('REG_att_is_going');
1029
+	}
1030
+
1031
+
1032
+	/**
1033
+	 * Gets related answers
1034
+	 *
1035
+	 * @param array $query_params like EEM_Base::get_all
1036
+	 * @return EE_Answer[]
1037
+	 * @throws EE_Error
1038
+	 */
1039
+	public function answers($query_params = null)
1040
+	{
1041
+		return $this->get_many_related('Answer', $query_params);
1042
+	}
1043
+
1044
+
1045
+	/**
1046
+	 * Gets the registration's answer value to the specified question
1047
+	 * (either the question's ID or a question object)
1048
+	 *
1049
+	 * @param EE_Question|int $question
1050
+	 * @param bool            $pretty_value
1051
+	 * @return array|string if pretty_value= true, the result will always be a string
1052
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1053
+	 * will convert it into some kind of string)
1054
+	 * @throws EE_Error
1055
+	 */
1056
+	public function answer_value_to_question($question, $pretty_value = true)
1057
+	{
1058
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1059
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * question_groups
1065
+	 * returns an array of EE_Question_Group objects for this registration
1066
+	 *
1067
+	 * @return EE_Question_Group[]
1068
+	 * @throws EE_Error
1069
+	 * @throws EntityNotFoundException
1070
+	 */
1071
+	public function question_groups()
1072
+	{
1073
+		$question_groups = array();
1074
+		if ($this->event() instanceof EE_Event) {
1075
+			$question_groups = $this->event()->question_groups(
1076
+				array(
1077
+					array(
1078
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1079
+					),
1080
+					'order_by' => array('QSG_order' => 'ASC'),
1081
+				)
1082
+			);
1083
+		}
1084
+		return $question_groups;
1085
+	}
1086
+
1087
+
1088
+	/**
1089
+	 * count_question_groups
1090
+	 * returns a count of the number of EE_Question_Group objects for this registration
1091
+	 *
1092
+	 * @return int
1093
+	 * @throws EE_Error
1094
+	 * @throws EntityNotFoundException
1095
+	 */
1096
+	public function count_question_groups()
1097
+	{
1098
+		$qg_count = 0;
1099
+		if ($this->event() instanceof EE_Event) {
1100
+			$qg_count = $this->event()->count_related(
1101
+				'Question_Group',
1102
+				array(
1103
+					array(
1104
+						'Event_Question_Group.EQG_primary' => $this->count() == 1 ? true : false,
1105
+					),
1106
+				)
1107
+			);
1108
+		}
1109
+		return $qg_count;
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * Returns the registration date in the 'standard' string format
1115
+	 * (function may be improved in the future to allow for different formats and timezones)
1116
+	 *
1117
+	 * @return string
1118
+	 * @throws EE_Error
1119
+	 */
1120
+	public function reg_date()
1121
+	{
1122
+		return $this->get_datetime('REG_date');
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1128
+	 * the ticket this registration purchased, or the datetime they have registered
1129
+	 * to attend)
1130
+	 *
1131
+	 * @return EE_Datetime_Ticket
1132
+	 * @throws EE_Error
1133
+	 */
1134
+	public function datetime_ticket()
1135
+	{
1136
+		return $this->get_first_related('Datetime_Ticket');
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * Sets the registration's datetime_ticket.
1142
+	 *
1143
+	 * @param EE_Datetime_Ticket $datetime_ticket
1144
+	 * @return EE_Datetime_Ticket
1145
+	 * @throws EE_Error
1146
+	 */
1147
+	public function set_datetime_ticket($datetime_ticket)
1148
+	{
1149
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1150
+	}
1151
+
1152
+	/**
1153
+	 * Gets deleted
1154
+	 *
1155
+	 * @return bool
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function deleted()
1159
+	{
1160
+		return $this->get('REG_deleted');
1161
+	}
1162
+
1163
+	/**
1164
+	 * Sets deleted
1165
+	 *
1166
+	 * @param boolean $deleted
1167
+	 * @return bool
1168
+	 * @throws EE_Error
1169
+	 * @throws RuntimeException
1170
+	 */
1171
+	public function set_deleted($deleted)
1172
+	{
1173
+		if ($deleted) {
1174
+			$this->delete();
1175
+		} else {
1176
+			$this->restore();
1177
+		}
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * Get the status object of this object
1183
+	 *
1184
+	 * @return EE_Status
1185
+	 * @throws EE_Error
1186
+	 */
1187
+	public function status_obj()
1188
+	{
1189
+		return $this->get_first_related('Status');
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * Returns the number of times this registration has checked into any of the datetimes
1195
+	 * its available for
1196
+	 *
1197
+	 * @return int
1198
+	 * @throws EE_Error
1199
+	 */
1200
+	public function count_checkins()
1201
+	{
1202
+		return $this->get_model()->count_related($this, 'Checkin');
1203
+	}
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1208
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1209
+	 *
1210
+	 * @return int
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	public function count_checkins_not_checkedout()
1214
+	{
1215
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1216
+	}
1217
+
1218
+
1219
+	/**
1220
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1221
+	 *
1222
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1223
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1224
+	 *                                          consider registration status as well as datetime access.
1225
+	 * @return bool
1226
+	 * @throws EE_Error
1227
+	 */
1228
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1229
+	{
1230
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1231
+
1232
+		//first check registration status
1233
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1234
+			return false;
1235
+		}
1236
+		//is there a datetime ticket that matches this dtt_ID?
1237
+		if (! (EEM_Datetime_Ticket::instance()->exists(array(
1238
+			array(
1239
+				'TKT_ID' => $this->get('TKT_ID'),
1240
+				'DTT_ID' => $DTT_ID,
1241
+			),
1242
+		)))
1243
+		) {
1244
+			return false;
1245
+		}
1246
+
1247
+		//final check is against TKT_uses
1248
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1254
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1255
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1256
+	 * then return false.  Otherwise return true.
1257
+	 *
1258
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1259
+	 * @return bool true means can checkin.  false means cannot checkin.
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1263
+	{
1264
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1265
+
1266
+		if (! $DTT_ID) {
1267
+			return false;
1268
+		}
1269
+
1270
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1271
+
1272
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1273
+		// check-in or not.
1274
+		if (! $max_uses || $max_uses === EE_INF) {
1275
+			return true;
1276
+		}
1277
+
1278
+		//does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1279
+		//go ahead and toggle.
1280
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1281
+			return true;
1282
+		}
1283
+
1284
+		//made it here so the last check is whether the number of checkins per unique datetime on this registration
1285
+		//disallows further check-ins.
1286
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(array(
1287
+			array(
1288
+				'REG_ID' => $this->ID(),
1289
+				'CHK_in' => true,
1290
+			),
1291
+		), 'DTT_ID', true);
1292
+		// checkins have already reached their max number of uses
1293
+		// so registrant can NOT checkin
1294
+		if ($count_unique_dtt_checkins >= $max_uses) {
1295
+			EE_Error::add_error(
1296
+				esc_html__(
1297
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1298
+					'event_espresso'
1299
+				),
1300
+				__FILE__,
1301
+				__FUNCTION__,
1302
+				__LINE__
1303
+			);
1304
+			return false;
1305
+		}
1306
+		return true;
1307
+	}
1308
+
1309
+
1310
+	/**
1311
+	 * toggle Check-in status for this registration
1312
+	 * Check-ins are toggled in the following order:
1313
+	 * never checked in -> checked in
1314
+	 * checked in -> checked out
1315
+	 * checked out -> checked in
1316
+	 *
1317
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1318
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1319
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1320
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1321
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1322
+	 * @throws EE_Error
1323
+	 */
1324
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1325
+	{
1326
+		if (empty($DTT_ID)) {
1327
+			$datetime = $this->get_latest_related_datetime();
1328
+			$DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1329
+			// verify the registration can checkin for the given DTT_ID
1330
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1331
+			EE_Error::add_error(
1332
+				sprintf(
1333
+					esc_html__(
1334
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1335
+						'event_espresso'
1336
+					),
1337
+					$this->ID(),
1338
+					$DTT_ID
1339
+				),
1340
+				__FILE__,
1341
+				__FUNCTION__,
1342
+				__LINE__
1343
+			);
1344
+			return false;
1345
+		}
1346
+		$status_paths = array(
1347
+			EE_Registration::checkin_status_never => EE_Registration::checkin_status_in,
1348
+			EE_Registration::checkin_status_in    => EE_Registration::checkin_status_out,
1349
+			EE_Registration::checkin_status_out   => EE_Registration::checkin_status_in,
1350
+		);
1351
+		//start by getting the current status so we know what status we'll be changing to.
1352
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1353
+		$status_to  = $status_paths[$cur_status];
1354
+		// database only records true for checked IN or false for checked OUT
1355
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1356
+		$new_status = $status_to === EE_Registration::checkin_status_in ? true : false;
1357
+		// add relation - note Check-ins are always creating new rows
1358
+		// because we are keeping track of Check-ins over time.
1359
+		// Eventually we'll probably want to show a list table
1360
+		// for the individual Check-ins so that they can be managed.
1361
+		$checkin = EE_Checkin::new_instance(array(
1362
+			'REG_ID' => $this->ID(),
1363
+			'DTT_ID' => $DTT_ID,
1364
+			'CHK_in' => $new_status,
1365
+		));
1366
+		// if the record could not be saved then return false
1367
+		if ($checkin->save() === 0) {
1368
+			if (WP_DEBUG) {
1369
+				global $wpdb;
1370
+				$error = sprintf(
1371
+					esc_html__(
1372
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1373
+						'event_espresso'
1374
+					),
1375
+					'<br />',
1376
+					$wpdb->last_error
1377
+				);
1378
+			} else {
1379
+				$error = esc_html__(
1380
+					'Registration check in update failed because of an unknown database error',
1381
+					'event_espresso'
1382
+				);
1383
+			}
1384
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1385
+			return false;
1386
+		}
1387
+		return $status_to;
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1393
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1394
+	 *
1395
+	 * @return EE_Datetime|null
1396
+	 * @throws EE_Error
1397
+	 */
1398
+	public function get_latest_related_datetime()
1399
+	{
1400
+		return EEM_Datetime::instance()->get_one(
1401
+			array(
1402
+				array(
1403
+					'Ticket.Registration.REG_ID' => $this->ID(),
1404
+				),
1405
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1406
+			)
1407
+		);
1408
+	}
1409
+
1410
+
1411
+	/**
1412
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1413
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1414
+	 *
1415
+	 * @throws EE_Error
1416
+	 */
1417
+	public function get_earliest_related_datetime()
1418
+	{
1419
+		return EEM_Datetime::instance()->get_one(
1420
+			array(
1421
+				array(
1422
+					'Ticket.Registration.REG_ID' => $this->ID(),
1423
+				),
1424
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1425
+			)
1426
+		);
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * This method simply returns the check-in status for this registration and the given datetime.
1432
+	 * If neither the datetime nor the checkin values are provided as arguments,
1433
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1434
+	 *
1435
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1436
+	 *                            (if empty we'll get the primary datetime for
1437
+	 *                            this registration (via event) and use it's ID);
1438
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1439
+	 *
1440
+	 * @return int                Integer representing Check-in status.
1441
+	 * @throws EE_Error
1442
+	 */
1443
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1444
+	{
1445
+		$checkin_query_params = array(
1446
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1447
+		);
1448
+
1449
+		if ($DTT_ID > 0) {
1450
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1451
+		}
1452
+
1453
+		//get checkin object (if exists)
1454
+		$checkin = $checkin instanceof EE_Checkin
1455
+			? $checkin
1456
+			: $this->get_first_related('Checkin', $checkin_query_params);
1457
+		if ($checkin instanceof EE_Checkin) {
1458
+			if ($checkin->get('CHK_in')) {
1459
+				return EE_Registration::checkin_status_in; //checked in
1460
+			}
1461
+			return EE_Registration::checkin_status_out; //had checked in but is now checked out.
1462
+		}
1463
+		return EE_Registration::checkin_status_never; //never been checked in
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This method returns a localized message for the toggled Check-in message.
1469
+	 *
1470
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1471
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1472
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1473
+	 *                     message can be customized with the attendee name.
1474
+	 * @return string internationalized message
1475
+	 * @throws EE_Error
1476
+	 */
1477
+	public function get_checkin_msg($DTT_ID, $error = false)
1478
+	{
1479
+		//let's get the attendee first so we can include the name of the attendee
1480
+		$attendee = $this->get_first_related('Attendee');
1481
+		if ($attendee instanceof EE_Attendee) {
1482
+			if ($error) {
1483
+				return sprintf(__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1484
+			}
1485
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1486
+			//what is the status message going to be?
1487
+			switch ($cur_status) {
1488
+				case EE_Registration::checkin_status_never:
1489
+					return sprintf(__("%s has been removed from Check-in records", "event_espresso"),
1490
+						$attendee->full_name());
1491
+					break;
1492
+				case EE_Registration::checkin_status_in:
1493
+					return sprintf(__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1494
+					break;
1495
+				case EE_Registration::checkin_status_out:
1496
+					return sprintf(__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1497
+					break;
1498
+			}
1499
+		}
1500
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * Returns the related EE_Transaction to this registration
1506
+	 *
1507
+	 * @return EE_Transaction
1508
+	 * @throws EE_Error
1509
+	 * @throws EntityNotFoundException
1510
+	 */
1511
+	public function transaction()
1512
+	{
1513
+		$transaction = $this->get_first_related('Transaction');
1514
+		if (! $transaction instanceof \EE_Transaction) {
1515
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1516
+		}
1517
+		return $transaction;
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 *        get Registration Code
1523
+	 */
1524
+	public function reg_code()
1525
+	{
1526
+		return $this->get('REG_code');
1527
+	}
1528
+
1529
+
1530
+	/**
1531
+	 *        get Transaction ID
1532
+	 */
1533
+	public function transaction_ID()
1534
+	{
1535
+		return $this->get('TXN_ID');
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * @return int
1541
+	 * @throws EE_Error
1542
+	 */
1543
+	public function ticket_ID()
1544
+	{
1545
+		return $this->get('TKT_ID');
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 *        Set Registration Code
1551
+	 *
1552
+	 * @access    public
1553
+	 * @param    string  $REG_code Registration Code
1554
+	 * @param    boolean $use_default
1555
+	 * @throws EE_Error
1556
+	 */
1557
+	public function set_reg_code($REG_code, $use_default = false)
1558
+	{
1559
+		if (empty($REG_code)) {
1560
+			EE_Error::add_error(
1561
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1562
+				__FILE__,
1563
+				__FUNCTION__,
1564
+				__LINE__
1565
+			);
1566
+			return;
1567
+		}
1568
+		if (! $this->reg_code()) {
1569
+			parent::set('REG_code', $REG_code, $use_default);
1570
+		} else {
1571
+			EE_Error::doing_it_wrong(
1572
+				__CLASS__ . '::' . __FUNCTION__,
1573
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1574
+				'4.6.0'
1575
+			);
1576
+		}
1577
+	}
1578
+
1579
+
1580
+	/**
1581
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1582
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1583
+	 *    $registration->transaction()->registrations();
1584
+	 *
1585
+	 * @since 4.5.0
1586
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1587
+	 * @throws EE_Error
1588
+	 */
1589
+	public function get_all_other_registrations_in_group()
1590
+	{
1591
+		if ($this->group_size() < 2) {
1592
+			return array();
1593
+		}
1594
+
1595
+		$query[0] = array(
1596
+			'TXN_ID' => $this->transaction_ID(),
1597
+			'REG_ID' => array('!=', $this->ID()),
1598
+			'TKT_ID' => $this->ticket_ID(),
1599
+		);
1600
+		/** @var EE_Registration[] $registrations */
1601
+		$registrations = $this->get_model()->get_all($query);
1602
+		return $registrations;
1603
+	}
1604
+
1605
+	/**
1606
+	 * Return the link to the admin details for the object.
1607
+	 *
1608
+	 * @return string
1609
+	 * @throws EE_Error
1610
+	 */
1611
+	public function get_admin_details_link()
1612
+	{
1613
+		EE_Registry::instance()->load_helper('URL');
1614
+		return EEH_URL::add_query_args_and_nonce(
1615
+			array(
1616
+				'page'    => 'espresso_registrations',
1617
+				'action'  => 'view_registration',
1618
+				'_REG_ID' => $this->ID(),
1619
+			),
1620
+			admin_url('admin.php')
1621
+		);
1622
+	}
1623
+
1624
+	/**
1625
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1626
+	 *
1627
+	 * @return string
1628
+	 * @throws EE_Error
1629
+	 */
1630
+	public function get_admin_edit_link()
1631
+	{
1632
+		return $this->get_admin_details_link();
1633
+	}
1634
+
1635
+	/**
1636
+	 * Returns the link to a settings page for the object.
1637
+	 *
1638
+	 * @return string
1639
+	 * @throws EE_Error
1640
+	 */
1641
+	public function get_admin_settings_link()
1642
+	{
1643
+		return $this->get_admin_details_link();
1644
+	}
1645
+
1646
+	/**
1647
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1648
+	 *
1649
+	 * @return string
1650
+	 */
1651
+	public function get_admin_overview_link()
1652
+	{
1653
+		EE_Registry::instance()->load_helper('URL');
1654
+		return EEH_URL::add_query_args_and_nonce(
1655
+			array(
1656
+				'page' => 'espresso_registrations',
1657
+			),
1658
+			admin_url('admin.php')
1659
+		);
1660
+	}
1661
+
1662
+
1663
+	/**
1664
+	 * @param array $query_params
1665
+	 *
1666
+	 * @return \EE_Registration[]
1667
+	 * @throws EE_Error
1668
+	 */
1669
+	public function payments($query_params = array())
1670
+	{
1671
+		return $this->get_many_related('Payment', $query_params);
1672
+	}
1673
+
1674
+
1675
+	/**
1676
+	 * @param array $query_params
1677
+	 *
1678
+	 * @return \EE_Registration_Payment[]
1679
+	 * @throws EE_Error
1680
+	 */
1681
+	public function registration_payments($query_params = array())
1682
+	{
1683
+		return $this->get_many_related('Registration_Payment', $query_params);
1684
+	}
1685
+
1686
+
1687
+	/**
1688
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1689
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1690
+	 *
1691
+	 * @return EE_Payment_Method|null
1692
+	 */
1693
+	public function payment_method()
1694
+	{
1695
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1696
+	}
1697
+
1698
+
1699
+	/**
1700
+	 * @return \EE_Line_Item
1701
+	 * @throws EntityNotFoundException
1702
+	 * @throws EE_Error
1703
+	 */
1704
+	public function ticket_line_item()
1705
+	{
1706
+		$ticket            = $this->ticket();
1707
+		$transaction       = $this->transaction();
1708
+		$line_item         = null;
1709
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1710
+			$transaction->total_line_item(),
1711
+			'Ticket',
1712
+			array($ticket->ID())
1713
+		);
1714
+		foreach ($ticket_line_items as $ticket_line_item) {
1715
+			if (
1716
+				$ticket_line_item instanceof \EE_Line_Item
1717
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1718
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1719
+			) {
1720
+				$line_item = $ticket_line_item;
1721
+				break;
1722
+			}
1723
+		}
1724
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1725
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1726
+		}
1727
+		return $line_item;
1728
+	}
1729
+
1730
+
1731
+	/**
1732
+	 * Soft Deletes this model object.
1733
+	 *
1734
+	 * @return boolean | int
1735
+	 * @throws RuntimeException
1736
+	 * @throws EE_Error
1737
+	 */
1738
+	public function delete()
1739
+	{
1740
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1741
+			$this->set_status(EEM_Registration::status_id_cancelled);
1742
+		}
1743
+		return parent::delete();
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1749
+	 *
1750
+	 * @throws EE_Error
1751
+	 * @throws RuntimeException
1752
+	 */
1753
+	public function restore()
1754
+	{
1755
+		$previous_status = $this->get_extra_meta(
1756
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1757
+			true,
1758
+			EEM_Registration::status_id_cancelled
1759
+		);
1760
+		if ($previous_status) {
1761
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1762
+			$this->set_status($previous_status);
1763
+		}
1764
+		return parent::restore();
1765
+	}
1766
+
1767
+
1768
+	/**
1769
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1770
+	 *
1771
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1772
+	 *                                           depending on whether the reg status changes to or from "Approved"
1773
+	 * @return boolean whether the Registration status was updated
1774
+	 * @throws EE_Error
1775
+	 * @throws RuntimeException
1776
+	 */
1777
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
1778
+	{
1779
+		$paid = $this->paid();
1780
+		$price = $this->final_price();
1781
+		switch(true) {
1782
+			// overpaid or paid
1783
+			case EEH_Money::compare_floats($paid, $price, '>'):
1784
+			case EEH_Money::compare_floats($paid, $price):
1785
+				$new_status = EEM_Registration::status_id_approved;
1786
+				break;
1787
+			//  underpaid
1788
+			case EEH_Money::compare_floats($paid, $price, '<'):
1789
+				$new_status = EEM_Registration::status_id_pending_payment;
1790
+				break;
1791
+			// uhhh Houston...
1792
+			default:
1793
+				throw new RuntimeException(
1794
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
1795
+				);
1796
+		}
1797
+		if ($new_status !== $this->status_ID()) {
1798
+			if ($trigger_set_status_logic) {
1799
+				return $this->set_status($new_status);
1800
+			}
1801
+			parent::set('STS_ID', $new_status);
1802
+			return true;
1803
+		}
1804
+		return false;
1805
+	}
1806
+
1807
+
1808
+	/*************************** DEPRECATED ***************************/
1809
+
1810
+
1811
+	/**
1812
+	 * @deprecated
1813
+	 * @since     4.7.0
1814
+	 * @access    public
1815
+	 */
1816
+	public function price_paid()
1817
+	{
1818
+		EE_Error::doing_it_wrong('EE_Registration::price_paid()',
1819
+			esc_html__('This method is deprecated, please use EE_Registration::final_price() instead.', 'event_espresso'),
1820
+			'4.7.0');
1821
+		return $this->final_price();
1822
+	}
1823
+
1824
+
1825
+	/**
1826
+	 * @deprecated
1827
+	 * @since     4.7.0
1828
+	 * @access    public
1829
+	 * @param    float $REG_final_price
1830
+	 * @throws EE_Error
1831
+	 * @throws RuntimeException
1832
+	 */
1833
+	public function set_price_paid($REG_final_price = 0.00)
1834
+	{
1835
+		EE_Error::doing_it_wrong('EE_Registration::set_price_paid()',
1836
+			esc_html__('This method is deprecated, please use EE_Registration::set_final_price() instead.', 'event_espresso'),
1837
+			'4.7.0');
1838
+		$this->set_final_price($REG_final_price);
1839
+	}
1840
+
1841
+
1842
+	/**
1843
+	 * @deprecated
1844
+	 * @since 4.7.0
1845
+	 * @return string
1846
+	 * @throws EE_Error
1847
+	 */
1848
+	public function pretty_price_paid()
1849
+	{
1850
+		EE_Error::doing_it_wrong('EE_Registration::pretty_price_paid()',
1851
+			esc_html__('This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
1852
+				'event_espresso'), '4.7.0');
1853
+		return $this->pretty_final_price();
1854
+	}
1855
+
1856
+
1857
+	/**
1858
+	 * Gets the primary datetime related to this registration via the related Event to this registration
1859
+	 *
1860
+	 * @deprecated 4.9.17
1861
+	 * @return EE_Datetime
1862
+	 * @throws EE_Error
1863
+	 * @throws EntityNotFoundException
1864
+	 */
1865
+	public function get_related_primary_datetime()
1866
+	{
1867
+		EE_Error::doing_it_wrong(
1868
+			__METHOD__,
1869
+			esc_html__(
1870
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
1871
+				'event_espresso'
1872
+			),
1873
+			'4.9.17',
1874
+			'5.0.0'
1875
+		);
1876
+		return $this->event()->primary_datetime();
1877
+	}
1878 1878
 
1879 1879
 
1880 1880
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
     {
111 111
         switch ($field_name) {
112 112
             case 'REG_code':
113
-                if (! empty($field_value) && $this->reg_code() === null) {
113
+                if ( ! empty($field_value) && $this->reg_code() === null) {
114 114
                     $this->set_reg_code($field_value, $use_default);
115 115
                 }
116 116
                 break;
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
     public function event()
288 288
     {
289 289
         $event = $this->get_first_related('Event');
290
-        if (! $event instanceof \EE_Event) {
290
+        if ( ! $event instanceof \EE_Event) {
291 291
             throw new EntityNotFoundException('Event ID', $this->event_ID());
292 292
         }
293 293
         return $event;
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
             false,
979 979
             'sentence'
980 980
         );
981
-        $icon   = '';
981
+        $icon = '';
982 982
         switch ($this->status_ID()) {
983 983
             case EEM_Registration::status_id_approved:
984 984
                 $icon = $show_icons
@@ -1016,7 +1016,7 @@  discard block
 block discarded – undo
1016 1016
                     : '';
1017 1017
                 break;
1018 1018
         }
1019
-        return $icon . $status[$this->status_ID()];
1019
+        return $icon.$status[$this->status_ID()];
1020 1020
     }
1021 1021
 
1022 1022
 
@@ -1234,7 +1234,7 @@  discard block
 block discarded – undo
1234 1234
             return false;
1235 1235
         }
1236 1236
         //is there a datetime ticket that matches this dtt_ID?
1237
-        if (! (EEM_Datetime_Ticket::instance()->exists(array(
1237
+        if ( ! (EEM_Datetime_Ticket::instance()->exists(array(
1238 1238
             array(
1239 1239
                 'TKT_ID' => $this->get('TKT_ID'),
1240 1240
                 'DTT_ID' => $DTT_ID,
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
     {
1264 1264
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1265 1265
 
1266
-        if (! $DTT_ID) {
1266
+        if ( ! $DTT_ID) {
1267 1267
             return false;
1268 1268
         }
1269 1269
 
@@ -1271,7 +1271,7 @@  discard block
 block discarded – undo
1271 1271
 
1272 1272
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1273 1273
         // check-in or not.
1274
-        if (! $max_uses || $max_uses === EE_INF) {
1274
+        if ( ! $max_uses || $max_uses === EE_INF) {
1275 1275
             return true;
1276 1276
         }
1277 1277
 
@@ -1327,7 +1327,7 @@  discard block
 block discarded – undo
1327 1327
             $datetime = $this->get_latest_related_datetime();
1328 1328
             $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1329 1329
             // verify the registration can checkin for the given DTT_ID
1330
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1330
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1331 1331
             EE_Error::add_error(
1332 1332
                 sprintf(
1333 1333
                     esc_html__(
@@ -1511,7 +1511,7 @@  discard block
 block discarded – undo
1511 1511
     public function transaction()
1512 1512
     {
1513 1513
         $transaction = $this->get_first_related('Transaction');
1514
-        if (! $transaction instanceof \EE_Transaction) {
1514
+        if ( ! $transaction instanceof \EE_Transaction) {
1515 1515
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1516 1516
         }
1517 1517
         return $transaction;
@@ -1565,11 +1565,11 @@  discard block
 block discarded – undo
1565 1565
             );
1566 1566
             return;
1567 1567
         }
1568
-        if (! $this->reg_code()) {
1568
+        if ( ! $this->reg_code()) {
1569 1569
             parent::set('REG_code', $REG_code, $use_default);
1570 1570
         } else {
1571 1571
             EE_Error::doing_it_wrong(
1572
-                __CLASS__ . '::' . __FUNCTION__,
1572
+                __CLASS__.'::'.__FUNCTION__,
1573 1573
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1574 1574
                 '4.6.0'
1575 1575
             );
@@ -1721,7 +1721,7 @@  discard block
 block discarded – undo
1721 1721
                 break;
1722 1722
             }
1723 1723
         }
1724
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1724
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1725 1725
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1726 1726
         }
1727 1727
         return $line_item;
@@ -1778,7 +1778,7 @@  discard block
 block discarded – undo
1778 1778
     {
1779 1779
         $paid = $this->paid();
1780 1780
         $price = $this->final_price();
1781
-        switch(true) {
1781
+        switch (true) {
1782 1782
             // overpaid or paid
1783 1783
             case EEH_Money::compare_floats($paid, $price, '>'):
1784 1784
             case EEH_Money::compare_floats($paid, $price):
Please login to merge, or discard this patch.
attendee_information/EE_SPCO_Reg_Step_Attendee_Information.class.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -569,6 +569,7 @@
 block discarded – undo
569 569
      * @param EE_Registration $registration
570 570
      * @param EE_Question     $question
571 571
      * @param                 mixed EE_Answer|NULL      $answer
572
+     * @param EE_Answer $answer
572 573
      * @return EE_Form_Input_Base
573 574
      * @throws \EE_Error
574 575
      */
Please login to merge, or discard this patch.
Indentation   +1237 added lines, -1237 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\commands\attendee\CreateAttendeeCommand;
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 
7 7
 /**
@@ -16,1246 +16,1246 @@  discard block
 block discarded – undo
16 16
 class EE_SPCO_Reg_Step_Attendee_Information extends EE_SPCO_Reg_Step
17 17
 {
18 18
 
19
-    /**
20
-     * @type bool $_print_copy_info
21
-     */
22
-    private $_print_copy_info = false;
23
-
24
-    /**
25
-     * @type array $_attendee_data
26
-     */
27
-    private $_attendee_data = array();
28
-
29
-    /**
30
-     * @type array $_required_questions
31
-     */
32
-    private $_required_questions = array();
33
-
34
-    /**
35
-     * @type array $_registration_answers
36
-     */
37
-    private $_registration_answers = array();
38
-
39
-
40
-    /**
41
-     *    class constructor
42
-     *
43
-     * @access    public
44
-     * @param    EE_Checkout $checkout
45
-     */
46
-    public function __construct(EE_Checkout $checkout)
47
-    {
48
-        $this->_slug     = 'attendee_information';
49
-        $this->_name     = __('Attendee Information', 'event_espresso');
50
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'attendee_info_main.template.php';
51
-        $this->checkout  = $checkout;
52
-        $this->_reset_success_message();
53
-        $this->set_instructions(
54
-            __('Please answer the following registration questions before proceeding.', 'event_espresso')
55
-        );
56
-    }
57
-
58
-
59
-    public function translate_js_strings()
60
-    {
61
-        EE_Registry::$i18n_js_strings['required_field']            = __(' is a required question.', 'event_espresso');
62
-        EE_Registry::$i18n_js_strings['required_multi_field']      = __(
63
-            ' is a required question. Please enter a value for at least one of the options.',
64
-            'event_espresso'
65
-        );
66
-        EE_Registry::$i18n_js_strings['answer_required_questions'] = __(
67
-            'Please answer all required questions correctly before proceeding.',
68
-            'event_espresso'
69
-        );
70
-        EE_Registry::$i18n_js_strings['attendee_info_copied']      = sprintf(
71
-            __(
72
-                'The attendee information was successfully copied.%sPlease ensure the rest of the registration form is completed before proceeding.',
73
-                'event_espresso'
74
-            ),
75
-            '<br/>'
76
-        );
77
-        EE_Registry::$i18n_js_strings['attendee_info_copy_error']  = __(
78
-            'An unknown error occurred on the server while attempting to copy the attendee information. Please refresh the page and try again.',
79
-            'event_espresso'
80
-        );
81
-        EE_Registry::$i18n_js_strings['enter_valid_email']         = __(
82
-            'You must enter a valid email address.',
83
-            'event_espresso'
84
-        );
85
-        EE_Registry::$i18n_js_strings['valid_email_and_questions'] = __(
86
-            'You must enter a valid email address and answer all other required questions before you can proceed.',
87
-            'event_espresso'
88
-        );
89
-    }
90
-
91
-
92
-    public function enqueue_styles_and_scripts()
93
-    {
94
-
95
-    }
96
-
97
-
98
-    /**
99
-     * @return boolean
100
-     */
101
-    public function initialize_reg_step()
102
-    {
103
-        return true;
104
-    }
105
-
106
-
107
-    /**
108
-     * @return EE_Form_Section_Proper
109
-     * @throws \EE_Error
110
-     */
111
-    public function generate_reg_form()
112
-    {
113
-        $this->_print_copy_info = false;
114
-        $primary_registrant     = null;
115
-        // autoload Line_Item_Display classes
116
-        EEH_Autoloader::register_line_item_display_autoloaders();
117
-        $Line_Item_Display = new EE_Line_Item_Display();
118
-        // calculate taxes
119
-        $Line_Item_Display->display_line_item(
120
-            $this->checkout->cart->get_grand_total(),
121
-            array('set_tax_rate' => true)
122
-        );
123
-        /** @var $subsections EE_Form_Section_Proper[] */
124
-        $subsections   = array(
125
-            'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
126
-        );
127
-        $template_args = array(
128
-            'revisit'       => $this->checkout->revisit,
129
-            'registrations' => array(),
130
-            'ticket_count'  => array(),
131
-        );
132
-        // grab the saved registrations from the transaction
133
-        $registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
134
-        if ($registrations) {
135
-            foreach ($registrations as $registration) {
136
-                // can this registration be processed during this visit ?
137
-                if (
138
-                    $registration instanceof EE_Registration
139
-                    && $this->checkout->visit_allows_processing_of_this_registration($registration)
140
-                ) {
141
-                    $subsections[$registration->reg_url_link()] = $this->_registrations_reg_form($registration);
142
-                    if (! $this->checkout->admin_request) {
143
-                        $template_args['registrations'][$registration->reg_url_link()]    = $registration;
144
-                        $template_args['ticket_count'][$registration->ticket()->ID()]     = isset(
145
-                            $template_args['ticket_count'][$registration->ticket()->ID()]
146
-                        )
147
-                            ? $template_args['ticket_count'][$registration->ticket()->ID()] + 1
148
-                            : 1;
149
-                        $ticket_line_item                                                 = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
150
-                            $this->checkout->cart->get_grand_total(),
151
-                            'Ticket',
152
-                            array($registration->ticket()->ID())
153
-                        );
154
-                        $ticket_line_item                                                 = is_array($ticket_line_item)
155
-                            ? reset($ticket_line_item)
156
-                            : $ticket_line_item;
157
-                        $template_args['ticket_line_item'][$registration->ticket()->ID()] =
158
-                            $Line_Item_Display->display_line_item($ticket_line_item);
159
-                    }
160
-                    if ($registration->is_primary_registrant()) {
161
-                        $primary_registrant = $registration->reg_url_link();
162
-                    }
163
-                }
164
-            }
165
-            // print_copy_info ?
166
-            if ($primary_registrant && ! $this->checkout->admin_request && count($registrations) > 1) {
167
-                // TODO: add admin option for toggling copy attendee info, then use that value to change $this->_print_copy_info
168
-                $copy_options['spco_copy_attendee_chk'] = $this->_print_copy_info
169
-                    ? $this->_copy_attendee_info_form()
170
-                    : $this->_auto_copy_attendee_info();
171
-                // generate hidden input
172
-                if (
173
-                    isset($subsections[$primary_registrant])
174
-                    && $subsections[$primary_registrant] instanceof EE_Form_Section_Proper
175
-                ) {
176
-                    $subsections[$primary_registrant]->add_subsections($copy_options, 'primary_registrant', false);
177
-                }
178
-            }
179
-
180
-        }
181
-
182
-        return new EE_Form_Section_Proper(
183
-            array(
184
-                'name'            => $this->reg_form_name(),
185
-                'html_id'         => $this->reg_form_name(),
186
-                'subsections'     => $subsections,
187
-                'layout_strategy' => $this->checkout->admin_request ?
188
-                    new EE_Div_Per_Section_Layout() :
189
-                    new EE_Template_Layout(
190
-                        array(
191
-                            'layout_template_file' => $this->_template, // layout_template
192
-                            'template_args'        => $template_args,
193
-                        )
194
-                    ),
195
-            )
196
-        );
197
-
198
-    }
199
-
200
-
201
-    /**
202
-     * @param EE_Registration $registration
203
-     * @return EE_Form_Section_Base
204
-     * @throws \EE_Error
205
-     */
206
-    private function _registrations_reg_form(EE_Registration $registration)
207
-    {
208
-        static $attendee_nmbr = 1;
209
-        $form_args = array();
210
-        // verify that registration has valid event
211
-        if ($registration->event() instanceof EE_Event) {
212
-            $question_groups = $registration->event()->question_groups(
213
-                array(
214
-                    array(
215
-                        'Event.EVT_ID'                     => $registration->event()->ID(),
216
-                        'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false,
217
-                    ),
218
-                    'order_by' => array('QSG_order' => 'ASC'),
219
-                )
220
-            );
221
-            if ($question_groups) {
222
-                // array of params to pass to parent constructor
223
-                $form_args = array(
224
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
225
-                    'html_class'      => 'ee-reg-form-attendee-dv',
226
-                    'html_style'      => $this->checkout->admin_request
227
-                        ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
228
-                        : '',
229
-                    'subsections'     => array(),
230
-                    'layout_strategy' => new EE_Fieldset_Section_Layout(
231
-                        array(
232
-                            'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
233
-                            'legend_text'  => sprintf(__('Attendee %d', 'event_espresso'), $attendee_nmbr),
234
-                        )
235
-                    ),
236
-                );
237
-                foreach ($question_groups as $question_group) {
238
-                    if ($question_group instanceof EE_Question_Group) {
239
-                        $form_args['subsections'][$question_group->identifier()] = $this->_question_group_reg_form(
240
-                            $registration,
241
-                            $question_group
242
-                        );
243
-                    }
244
-                }
245
-                // add hidden input
246
-                $form_args['subsections']['additional_attendee_reg_info'] = $this->_additional_attendee_reg_info_input(
247
-                    $registration
248
-                );
249
-                // if we have question groups for additional attendees, then display the copy options
250
-                $this->_print_copy_info = $attendee_nmbr > 1 ? true : $this->_print_copy_info;
251
-                if ($registration->is_primary_registrant()) {
252
-                    // generate hidden input
253
-                    $form_args['subsections']['primary_registrant'] = $this->_additional_primary_registrant_inputs($registration);
254
-                }
255
-            }
256
-        }
257
-        $attendee_nmbr++;
258
-        return ! empty($form_args) ? new EE_Form_Section_Proper($form_args) : new EE_Form_Section_HTML();
259
-    }
260
-
261
-
262
-    /**
263
-     * _additional_attendee_reg_info_input
264
-     *
265
-     * @access public
266
-     * @param EE_Registration $registration
267
-     * @param bool            $additional_attendee_reg_info
268
-     * @return    EE_Form_Input_Base
269
-     * @throws \EE_Error
270
-     */
271
-    private function _additional_attendee_reg_info_input(
272
-        EE_Registration $registration,
273
-        $additional_attendee_reg_info = true
274
-    ) {
275
-        // generate hidden input
276
-        return new EE_Hidden_Input(
277
-            array(
278
-                'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
279
-                'default' => $additional_attendee_reg_info,
280
-            )
281
-        );
282
-    }
283
-
284
-
285
-    /**
286
-     * @param EE_Registration   $registration
287
-     * @param EE_Question_Group $question_group
288
-     * @return EE_Form_Section_Proper
289
-     * @throws \EE_Error
290
-     */
291
-    private function _question_group_reg_form(EE_Registration $registration, EE_Question_Group $question_group)
292
-    {
293
-        // array of params to pass to parent constructor
294
-        $form_args = array(
295
-            'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier(),
296
-            'html_class'      => $this->checkout->admin_request
297
-                ? 'form-table ee-reg-form-qstn-grp-dv'
298
-                : 'ee-reg-form-qstn-grp-dv',
299
-            'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-lbl',
300
-            'subsections'     => array(
301
-                'reg_form_qstn_grp_hdr' => $this->_question_group_header($question_group),
302
-            ),
303
-            'layout_strategy' => $this->checkout->admin_request
304
-                ? new EE_Admin_Two_Column_Layout()
305
-                : new EE_Div_Per_Section_Layout(),
306
-        );
307
-        // where params
308
-        $query_params = array('QST_deleted' => 0);
309
-        // don't load admin only questions on the frontend
310
-        if (! $this->checkout->admin_request) {
311
-            $query_params['QST_admin_only'] = array('!=', true);
312
-        }
313
-        $questions = $question_group->get_many_related(
314
-            'Question',
315
-            array(
316
-                $query_params,
317
-                'order_by' => array(
318
-                    'Question_Group_Question.QGQ_order' => 'ASC',
319
-                ),
320
-            )
321
-        );
322
-        // filter for additional content before questions
323
-        $form_args['subsections']['reg_form_questions_before'] = new EE_Form_Section_HTML(
324
-            apply_filters(
325
-                'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions',
326
-                '',
327
-                $registration,
328
-                $question_group,
329
-                $this
330
-            )
331
-        );
332
-        // loop thru questions
333
-        foreach ($questions as $question) {
334
-            if ($question instanceof EE_Question) {
335
-                $identifier                            = $question->is_system_question() ? $question->system_ID() : $question->ID();
336
-                $form_args['subsections'][$identifier] = $this->reg_form_question($registration, $question);
337
-            }
338
-        }
339
-        $form_args['subsections'] = apply_filters(
340
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information__question_group_reg_form__subsections_array',
341
-            $form_args['subsections'],
342
-            $registration,
343
-            $question_group,
344
-            $this
345
-        );
346
-        // filter for additional content after questions
347
-        $form_args['subsections']['reg_form_questions_after'] = new EE_Form_Section_HTML(
348
-            apply_filters(
349
-                'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions',
350
-                '',
351
-                $registration,
352
-                $question_group,
353
-                $this
354
-            )
355
-        );
19
+	/**
20
+	 * @type bool $_print_copy_info
21
+	 */
22
+	private $_print_copy_info = false;
23
+
24
+	/**
25
+	 * @type array $_attendee_data
26
+	 */
27
+	private $_attendee_data = array();
28
+
29
+	/**
30
+	 * @type array $_required_questions
31
+	 */
32
+	private $_required_questions = array();
33
+
34
+	/**
35
+	 * @type array $_registration_answers
36
+	 */
37
+	private $_registration_answers = array();
38
+
39
+
40
+	/**
41
+	 *    class constructor
42
+	 *
43
+	 * @access    public
44
+	 * @param    EE_Checkout $checkout
45
+	 */
46
+	public function __construct(EE_Checkout $checkout)
47
+	{
48
+		$this->_slug     = 'attendee_information';
49
+		$this->_name     = __('Attendee Information', 'event_espresso');
50
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'attendee_info_main.template.php';
51
+		$this->checkout  = $checkout;
52
+		$this->_reset_success_message();
53
+		$this->set_instructions(
54
+			__('Please answer the following registration questions before proceeding.', 'event_espresso')
55
+		);
56
+	}
57
+
58
+
59
+	public function translate_js_strings()
60
+	{
61
+		EE_Registry::$i18n_js_strings['required_field']            = __(' is a required question.', 'event_espresso');
62
+		EE_Registry::$i18n_js_strings['required_multi_field']      = __(
63
+			' is a required question. Please enter a value for at least one of the options.',
64
+			'event_espresso'
65
+		);
66
+		EE_Registry::$i18n_js_strings['answer_required_questions'] = __(
67
+			'Please answer all required questions correctly before proceeding.',
68
+			'event_espresso'
69
+		);
70
+		EE_Registry::$i18n_js_strings['attendee_info_copied']      = sprintf(
71
+			__(
72
+				'The attendee information was successfully copied.%sPlease ensure the rest of the registration form is completed before proceeding.',
73
+				'event_espresso'
74
+			),
75
+			'<br/>'
76
+		);
77
+		EE_Registry::$i18n_js_strings['attendee_info_copy_error']  = __(
78
+			'An unknown error occurred on the server while attempting to copy the attendee information. Please refresh the page and try again.',
79
+			'event_espresso'
80
+		);
81
+		EE_Registry::$i18n_js_strings['enter_valid_email']         = __(
82
+			'You must enter a valid email address.',
83
+			'event_espresso'
84
+		);
85
+		EE_Registry::$i18n_js_strings['valid_email_and_questions'] = __(
86
+			'You must enter a valid email address and answer all other required questions before you can proceed.',
87
+			'event_espresso'
88
+		);
89
+	}
90
+
91
+
92
+	public function enqueue_styles_and_scripts()
93
+	{
94
+
95
+	}
96
+
97
+
98
+	/**
99
+	 * @return boolean
100
+	 */
101
+	public function initialize_reg_step()
102
+	{
103
+		return true;
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return EE_Form_Section_Proper
109
+	 * @throws \EE_Error
110
+	 */
111
+	public function generate_reg_form()
112
+	{
113
+		$this->_print_copy_info = false;
114
+		$primary_registrant     = null;
115
+		// autoload Line_Item_Display classes
116
+		EEH_Autoloader::register_line_item_display_autoloaders();
117
+		$Line_Item_Display = new EE_Line_Item_Display();
118
+		// calculate taxes
119
+		$Line_Item_Display->display_line_item(
120
+			$this->checkout->cart->get_grand_total(),
121
+			array('set_tax_rate' => true)
122
+		);
123
+		/** @var $subsections EE_Form_Section_Proper[] */
124
+		$subsections   = array(
125
+			'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
126
+		);
127
+		$template_args = array(
128
+			'revisit'       => $this->checkout->revisit,
129
+			'registrations' => array(),
130
+			'ticket_count'  => array(),
131
+		);
132
+		// grab the saved registrations from the transaction
133
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
134
+		if ($registrations) {
135
+			foreach ($registrations as $registration) {
136
+				// can this registration be processed during this visit ?
137
+				if (
138
+					$registration instanceof EE_Registration
139
+					&& $this->checkout->visit_allows_processing_of_this_registration($registration)
140
+				) {
141
+					$subsections[$registration->reg_url_link()] = $this->_registrations_reg_form($registration);
142
+					if (! $this->checkout->admin_request) {
143
+						$template_args['registrations'][$registration->reg_url_link()]    = $registration;
144
+						$template_args['ticket_count'][$registration->ticket()->ID()]     = isset(
145
+							$template_args['ticket_count'][$registration->ticket()->ID()]
146
+						)
147
+							? $template_args['ticket_count'][$registration->ticket()->ID()] + 1
148
+							: 1;
149
+						$ticket_line_item                                                 = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
150
+							$this->checkout->cart->get_grand_total(),
151
+							'Ticket',
152
+							array($registration->ticket()->ID())
153
+						);
154
+						$ticket_line_item                                                 = is_array($ticket_line_item)
155
+							? reset($ticket_line_item)
156
+							: $ticket_line_item;
157
+						$template_args['ticket_line_item'][$registration->ticket()->ID()] =
158
+							$Line_Item_Display->display_line_item($ticket_line_item);
159
+					}
160
+					if ($registration->is_primary_registrant()) {
161
+						$primary_registrant = $registration->reg_url_link();
162
+					}
163
+				}
164
+			}
165
+			// print_copy_info ?
166
+			if ($primary_registrant && ! $this->checkout->admin_request && count($registrations) > 1) {
167
+				// TODO: add admin option for toggling copy attendee info, then use that value to change $this->_print_copy_info
168
+				$copy_options['spco_copy_attendee_chk'] = $this->_print_copy_info
169
+					? $this->_copy_attendee_info_form()
170
+					: $this->_auto_copy_attendee_info();
171
+				// generate hidden input
172
+				if (
173
+					isset($subsections[$primary_registrant])
174
+					&& $subsections[$primary_registrant] instanceof EE_Form_Section_Proper
175
+				) {
176
+					$subsections[$primary_registrant]->add_subsections($copy_options, 'primary_registrant', false);
177
+				}
178
+			}
179
+
180
+		}
181
+
182
+		return new EE_Form_Section_Proper(
183
+			array(
184
+				'name'            => $this->reg_form_name(),
185
+				'html_id'         => $this->reg_form_name(),
186
+				'subsections'     => $subsections,
187
+				'layout_strategy' => $this->checkout->admin_request ?
188
+					new EE_Div_Per_Section_Layout() :
189
+					new EE_Template_Layout(
190
+						array(
191
+							'layout_template_file' => $this->_template, // layout_template
192
+							'template_args'        => $template_args,
193
+						)
194
+					),
195
+			)
196
+		);
197
+
198
+	}
199
+
200
+
201
+	/**
202
+	 * @param EE_Registration $registration
203
+	 * @return EE_Form_Section_Base
204
+	 * @throws \EE_Error
205
+	 */
206
+	private function _registrations_reg_form(EE_Registration $registration)
207
+	{
208
+		static $attendee_nmbr = 1;
209
+		$form_args = array();
210
+		// verify that registration has valid event
211
+		if ($registration->event() instanceof EE_Event) {
212
+			$question_groups = $registration->event()->question_groups(
213
+				array(
214
+					array(
215
+						'Event.EVT_ID'                     => $registration->event()->ID(),
216
+						'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false,
217
+					),
218
+					'order_by' => array('QSG_order' => 'ASC'),
219
+				)
220
+			);
221
+			if ($question_groups) {
222
+				// array of params to pass to parent constructor
223
+				$form_args = array(
224
+					'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
225
+					'html_class'      => 'ee-reg-form-attendee-dv',
226
+					'html_style'      => $this->checkout->admin_request
227
+						? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
228
+						: '',
229
+					'subsections'     => array(),
230
+					'layout_strategy' => new EE_Fieldset_Section_Layout(
231
+						array(
232
+							'legend_class' => 'spco-attendee-lgnd smaller-text lt-grey-text',
233
+							'legend_text'  => sprintf(__('Attendee %d', 'event_espresso'), $attendee_nmbr),
234
+						)
235
+					),
236
+				);
237
+				foreach ($question_groups as $question_group) {
238
+					if ($question_group instanceof EE_Question_Group) {
239
+						$form_args['subsections'][$question_group->identifier()] = $this->_question_group_reg_form(
240
+							$registration,
241
+							$question_group
242
+						);
243
+					}
244
+				}
245
+				// add hidden input
246
+				$form_args['subsections']['additional_attendee_reg_info'] = $this->_additional_attendee_reg_info_input(
247
+					$registration
248
+				);
249
+				// if we have question groups for additional attendees, then display the copy options
250
+				$this->_print_copy_info = $attendee_nmbr > 1 ? true : $this->_print_copy_info;
251
+				if ($registration->is_primary_registrant()) {
252
+					// generate hidden input
253
+					$form_args['subsections']['primary_registrant'] = $this->_additional_primary_registrant_inputs($registration);
254
+				}
255
+			}
256
+		}
257
+		$attendee_nmbr++;
258
+		return ! empty($form_args) ? new EE_Form_Section_Proper($form_args) : new EE_Form_Section_HTML();
259
+	}
260
+
261
+
262
+	/**
263
+	 * _additional_attendee_reg_info_input
264
+	 *
265
+	 * @access public
266
+	 * @param EE_Registration $registration
267
+	 * @param bool            $additional_attendee_reg_info
268
+	 * @return    EE_Form_Input_Base
269
+	 * @throws \EE_Error
270
+	 */
271
+	private function _additional_attendee_reg_info_input(
272
+		EE_Registration $registration,
273
+		$additional_attendee_reg_info = true
274
+	) {
275
+		// generate hidden input
276
+		return new EE_Hidden_Input(
277
+			array(
278
+				'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
279
+				'default' => $additional_attendee_reg_info,
280
+			)
281
+		);
282
+	}
283
+
284
+
285
+	/**
286
+	 * @param EE_Registration   $registration
287
+	 * @param EE_Question_Group $question_group
288
+	 * @return EE_Form_Section_Proper
289
+	 * @throws \EE_Error
290
+	 */
291
+	private function _question_group_reg_form(EE_Registration $registration, EE_Question_Group $question_group)
292
+	{
293
+		// array of params to pass to parent constructor
294
+		$form_args = array(
295
+			'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier(),
296
+			'html_class'      => $this->checkout->admin_request
297
+				? 'form-table ee-reg-form-qstn-grp-dv'
298
+				: 'ee-reg-form-qstn-grp-dv',
299
+			'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-lbl',
300
+			'subsections'     => array(
301
+				'reg_form_qstn_grp_hdr' => $this->_question_group_header($question_group),
302
+			),
303
+			'layout_strategy' => $this->checkout->admin_request
304
+				? new EE_Admin_Two_Column_Layout()
305
+				: new EE_Div_Per_Section_Layout(),
306
+		);
307
+		// where params
308
+		$query_params = array('QST_deleted' => 0);
309
+		// don't load admin only questions on the frontend
310
+		if (! $this->checkout->admin_request) {
311
+			$query_params['QST_admin_only'] = array('!=', true);
312
+		}
313
+		$questions = $question_group->get_many_related(
314
+			'Question',
315
+			array(
316
+				$query_params,
317
+				'order_by' => array(
318
+					'Question_Group_Question.QGQ_order' => 'ASC',
319
+				),
320
+			)
321
+		);
322
+		// filter for additional content before questions
323
+		$form_args['subsections']['reg_form_questions_before'] = new EE_Form_Section_HTML(
324
+			apply_filters(
325
+				'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions',
326
+				'',
327
+				$registration,
328
+				$question_group,
329
+				$this
330
+			)
331
+		);
332
+		// loop thru questions
333
+		foreach ($questions as $question) {
334
+			if ($question instanceof EE_Question) {
335
+				$identifier                            = $question->is_system_question() ? $question->system_ID() : $question->ID();
336
+				$form_args['subsections'][$identifier] = $this->reg_form_question($registration, $question);
337
+			}
338
+		}
339
+		$form_args['subsections'] = apply_filters(
340
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information__question_group_reg_form__subsections_array',
341
+			$form_args['subsections'],
342
+			$registration,
343
+			$question_group,
344
+			$this
345
+		);
346
+		// filter for additional content after questions
347
+		$form_args['subsections']['reg_form_questions_after'] = new EE_Form_Section_HTML(
348
+			apply_filters(
349
+				'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions',
350
+				'',
351
+				$registration,
352
+				$question_group,
353
+				$this
354
+			)
355
+		);
356 356
 //		d( $form_args );
357
-        $question_group_reg_form = new EE_Form_Section_Proper($form_args);
358
-        return apply_filters(
359
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
360
-            $question_group_reg_form,
361
-            $registration,
362
-            $question_group,
363
-            $this
364
-        );
365
-    }
366
-
367
-
368
-    /**
369
-     * @access public
370
-     * @param EE_Question_Group $question_group
371
-     * @return    EE_Form_Section_HTML
372
-     */
373
-    private function _question_group_header(EE_Question_Group $question_group)
374
-    {
375
-        $html = '';
376
-        // group_name
377
-        if ($question_group->show_group_name() && $question_group->name() !== '') {
378
-            if ($this->checkout->admin_request) {
379
-                $html .= EEH_HTML::br();
380
-                $html .= EEH_HTML::h3(
381
-                    $question_group->name(),
382
-                    '', 'ee-reg-form-qstn-grp-title title', 'font-size: 1.3em; padding-left:0;'
383
-                );
384
-            } else {
385
-                $html .= EEH_HTML::h4(
386
-                    $question_group->name(),
387
-                    '', 'ee-reg-form-qstn-grp-title section-title'
388
-                );
389
-            }
390
-        }
391
-        // group_desc
392
-        if ($question_group->show_group_desc() && $question_group->desc() !== '') {
393
-            $html .= EEH_HTML::p(
394
-                $question_group->desc(),
395
-                '',
396
-                $this->checkout->admin_request
397
-                    ? 'ee-reg-form-qstn-grp-desc-pg'
398
-                    : 'ee-reg-form-qstn-grp-desc-pg small-text lt-grey-text'
399
-            );
400
-
401
-        }
402
-        return new EE_Form_Section_HTML($html);
403
-    }
404
-
405
-
406
-    /**
407
-     * @access public
408
-     * @return    EE_Form_Section_Proper
409
-     * @throws \EE_Error
410
-     */
411
-    private function _copy_attendee_info_form()
412
-    {
413
-        // array of params to pass to parent constructor
414
-        return new EE_Form_Section_Proper(
415
-            array(
416
-                'subsections'     => $this->_copy_attendee_info_inputs(),
417
-                'layout_strategy' => new EE_Template_Layout(
418
-                    array(
419
-                        'layout_template_file'     => SPCO_REG_STEPS_PATH . $this->_slug . DS . 'copy_attendee_info.template.php',
420
-                        'begin_template_file'      => null,
421
-                        'input_template_file'      => null,
422
-                        'subsection_template_file' => null,
423
-                        'end_template_file'        => null,
424
-                    )
425
-                ),
426
-            )
427
-        );
428
-    }
429
-
430
-
431
-    /**
432
-     * _auto_copy_attendee_info
433
-     *
434
-     * @access public
435
-     * @return EE_Form_Section_HTML
436
-     */
437
-    private function _auto_copy_attendee_info()
438
-    {
439
-        return new EE_Form_Section_HTML(
440
-            EEH_Template::locate_template(
441
-                SPCO_REG_STEPS_PATH . $this->_slug . DS . '_auto_copy_attendee_info.template.php',
442
-                apply_filters(
443
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information__auto_copy_attendee_info__template_args',
444
-                    array()
445
-                ),
446
-                true,
447
-                true
448
-            )
449
-        );
450
-    }
451
-
452
-
453
-    /**
454
-     * _copy_attendee_info_inputs
455
-     *
456
-     * @access public
457
-     * @return array
458
-     * @throws \EE_Error
459
-     */
460
-    private function _copy_attendee_info_inputs()
461
-    {
462
-        $copy_attendee_info_inputs = array();
463
-        $prev_ticket               = null;
464
-        // grab the saved registrations from the transaction
465
-        $registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
466
-        foreach ($registrations as $registration) {
467
-            // for all  attendees other than the primary attendee
468
-            if ($registration instanceof EE_Registration && ! $registration->is_primary_registrant()) {
469
-                // if this is a new ticket OR if this is the very first additional attendee after the primary attendee
470
-                if ($registration->ticket()->ID() !== $prev_ticket) {
471
-                    $item_name                                                                                         = $registration->ticket()->name();
472
-                    $item_name                                                                                         .= $registration->ticket()->description() !== ''
473
-                        ? ' - ' . $registration->ticket()->description()
474
-                        : '';
475
-                    $copy_attendee_info_inputs['spco_copy_attendee_chk[ticket-' . $registration->ticket()->ID() . ']'] = new EE_Form_Section_HTML(
476
-                        '<h6 class="spco-copy-attendee-event-hdr">' . $item_name . '</h6>'
477
-                    );
478
-                    $prev_ticket                                                                                       = $registration->ticket()->ID();
479
-                }
480
-
481
-                $copy_attendee_info_inputs['spco_copy_attendee_chk[' . $registration->ID() . ']'] = new
482
-                EE_Checkbox_Multi_Input(
483
-                    array(
484
-                        $registration->ID() => sprintf(
485
-                            __('Attendee #%s', 'event_espresso'),
486
-                            $registration->count()
487
-                        ),
488
-                    ),
489
-                    array(
490
-                        'html_id'                 => 'spco-copy-attendee-chk-' . $registration->reg_url_link(),
491
-                        'html_class'              => 'spco-copy-attendee-chk ee-do-not-validate',
492
-                        'display_html_label_text' => false,
493
-                    )
494
-                );
495
-            }
496
-        }
497
-        return $copy_attendee_info_inputs;
498
-    }
499
-
500
-
501
-    /**
502
-     * _additional_primary_registrant_inputs
503
-     *
504
-     * @access public
505
-     * @param EE_Registration $registration
506
-     * @return    EE_Form_Input_Base
507
-     * @throws \EE_Error
508
-     */
509
-    private function _additional_primary_registrant_inputs(EE_Registration $registration)
510
-    {
511
-        // generate hidden input
512
-        return new EE_Hidden_Input(
513
-            array(
514
-                'html_id' => 'primary_registrant',
515
-                'default' => $registration->reg_url_link(),
516
-            )
517
-        );
518
-    }
519
-
520
-
521
-    /**
522
-     * @access public
523
-     * @param EE_Registration $registration
524
-     * @param EE_Question     $question
525
-     * @return    EE_Form_Input_Base
526
-     * @throws \EE_Error
527
-     */
528
-    public function reg_form_question(EE_Registration $registration, EE_Question $question)
529
-    {
530
-
531
-        // if this question was for an attendee detail, then check for that answer
532
-        $answer_value = EEM_Answer::instance()->get_attendee_property_answer_value(
533
-            $registration,
534
-            $question->system_ID()
535
-        );
536
-        $answer       = $answer_value === null
537
-            ? EEM_Answer::instance()->get_one(
538
-                array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
539
-            )
540
-            : null;
541
-        // if NOT returning to edit an existing registration
542
-        // OR if this question is for an attendee property
543
-        // OR we still don't have an EE_Answer object
544
-        if ($answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link()) {
545
-            // create an EE_Answer object for storing everything in
546
-            $answer = EE_Answer::new_instance(array(
547
-                'QST_ID' => $question->ID(),
548
-                'REG_ID' => $registration->ID(),
549
-            ));
550
-        }
551
-        // verify instance
552
-        if ($answer instanceof EE_Answer) {
553
-            if (! empty($answer_value)) {
554
-                $answer->set('ANS_value', $answer_value);
555
-            }
556
-            $answer->cache('Question', $question);
557
-            //remember system ID had a bug where sometimes it could be null
558
-            $answer_cache_id = $question->is_system_question()
559
-                ? $question->system_ID() . '-' . $registration->reg_url_link()
560
-                : $question->ID() . '-' . $registration->reg_url_link();
561
-            $registration->cache('Answer', $answer, $answer_cache_id);
562
-        }
563
-        return $this->_generate_question_input($registration, $question, $answer);
564
-
565
-    }
566
-
567
-
568
-    /**
569
-     * @param EE_Registration $registration
570
-     * @param EE_Question     $question
571
-     * @param                 mixed EE_Answer|NULL      $answer
572
-     * @return EE_Form_Input_Base
573
-     * @throws \EE_Error
574
-     */
575
-    private function _generate_question_input(EE_Registration $registration, EE_Question $question, $answer)
576
-    {
577
-        $identifier                             = $question->is_system_question() ? $question->system_ID() : $question->ID();
578
-        $this->_required_questions[$identifier] = $question->required() ? true : false;
579
-        add_filter(
580
-            'FHEE__EE_Question__generate_form_input__country_options',
581
-            array($this, 'use_cached_countries_for_form_input'),
582
-            10,
583
-            4
584
-        );
585
-        add_filter(
586
-            'FHEE__EE_Question__generate_form_input__state_options',
587
-            array($this, 'use_cached_states_for_form_input'),
588
-            10,
589
-            4
590
-        );
591
-        $input_constructor_args                  = array(
592
-            'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
593
-            'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
594
-            'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
595
-            'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
596
-            'html_label_class' => 'ee-reg-qstn',
597
-        );
598
-        $input_constructor_args['html_label_id'] .= '-lbl';
599
-        if ($answer instanceof EE_Answer && $answer->ID()) {
600
-            $input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
601
-            $input_constructor_args['html_id']       .= '-' . $answer->ID();
602
-            $input_constructor_args['html_label_id'] .= '-' . $answer->ID();
603
-        }
604
-        $form_input = $question->generate_form_input(
605
-            $registration,
606
-            $answer,
607
-            $input_constructor_args
608
-        );
609
-        remove_filter(
610
-            'FHEE__EE_Question__generate_form_input__country_options',
611
-            array($this, 'use_cached_countries_for_form_input')
612
-        );
613
-        remove_filter(
614
-            'FHEE__EE_Question__generate_form_input__state_options',
615
-            array($this, 'use_cached_states_for_form_input')
616
-        );
617
-        return $form_input;
618
-    }
619
-
620
-
621
-    /**
622
-     * Gets the list of countries for the form input
623
-     *
624
-     * @param array|null       $countries_list
625
-     * @param \EE_Question     $question
626
-     * @param \EE_Registration $registration
627
-     * @param \EE_Answer       $answer
628
-     * @return array 2d keys are country IDs, values are their names
629
-     */
630
-    public function use_cached_countries_for_form_input(
631
-        $countries_list,
632
-        \EE_Question $question = null,
633
-        \EE_Registration $registration = null,
634
-        \EE_Answer $answer = null
635
-    ) {
636
-        $country_options = array('' => '');
637
-        // get possibly cached list of countries
638
-        $countries = $this->checkout->action === 'process_reg_step'
639
-            ? EEM_Country::instance()->get_all_countries()
640
-            : EEM_Country::instance()->get_all_active_countries();
641
-        if (! empty($countries)) {
642
-            foreach ($countries as $country) {
643
-                if ($country instanceof EE_Country) {
644
-                    $country_options[$country->ID()] = $country->name();
645
-                }
646
-            }
647
-        }
648
-        if ($question instanceof EE_Question
649
-            && $registration instanceof EE_Registration) {
650
-            $answer = EEM_Answer::instance()->get_one(
651
-                array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
652
-            );
653
-        } else {
654
-            $answer = EE_Answer::new_instance();
655
-        }
656
-        $country_options = apply_filters(
657
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
658
-            $country_options,
659
-            $this,
660
-            $registration,
661
-            $question,
662
-            $answer
663
-        );
664
-        return $country_options;
665
-    }
666
-
667
-
668
-    /**
669
-     * Gets the list of states for the form input
670
-     *
671
-     * @param array|null       $states_list
672
-     * @param \EE_Question     $question
673
-     * @param \EE_Registration $registration
674
-     * @param \EE_Answer       $answer
675
-     * @return array 2d keys are state IDs, values are their names
676
-     */
677
-    public function use_cached_states_for_form_input(
678
-        $states_list,
679
-        \EE_Question $question = null,
680
-        \EE_Registration $registration = null,
681
-        \EE_Answer $answer = null
682
-    ) {
683
-        $state_options = array('' => array('' => ''));
684
-        $states        = $this->checkout->action === 'process_reg_step'
685
-            ? EEM_State::instance()->get_all_states()
686
-            : EEM_State::instance()->get_all_active_states();
687
-        if (! empty($states)) {
688
-            foreach ($states as $state) {
689
-                if ($state instanceof EE_State) {
690
-                    $state_options[$state->country()->name()][$state->ID()] = $state->name();
691
-                }
692
-            }
693
-        }
694
-        $state_options = apply_filters(
695
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
696
-            $state_options,
697
-            $this,
698
-            $registration,
699
-            $question,
700
-            $answer
701
-        );
702
-        return $state_options;
703
-    }
704
-
705
-
706
-
707
-
708
-
709
-
710
-    /********************************************************************************************************/
711
-    /****************************************  PROCESS REG STEP  ****************************************/
712
-    /********************************************************************************************************/
713
-    /**
714
-     * @return boolean
715
-     * @throws \EE_Error
716
-     */
717
-    public function process_reg_step()
718
-    {
719
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
720
-        // grab validated data from form
721
-        $valid_data = $this->checkout->current_step->valid_data();
722
-        // EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
723
-        // EEH_Debug_Tools::printr( $valid_data, '$valid_data', __FILE__, __LINE__ );
724
-        // if we don't have any $valid_data then something went TERRIBLY WRONG !!!
725
-        if (empty($valid_data)) {
726
-            EE_Error::add_error(
727
-                __('No valid question responses were received.', 'event_espresso'),
728
-                __FILE__,
729
-                __FUNCTION__,
730
-                __LINE__
731
-            );
732
-            return false;
733
-        }
734
-        if (! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg) {
735
-            EE_Error::add_error(
736
-                __('A valid transaction could not be initiated for processing your registrations.', 'event_espresso'),
737
-                __FILE__,
738
-                __FUNCTION__,
739
-                __LINE__
740
-            );
741
-            return false;
742
-        }
743
-        // get cached registrations
744
-        $registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
745
-        // verify we got the goods
746
-        if (empty($registrations)) {
747
-            EE_Error::add_error(
748
-                __('Your form data could not be applied to any valid registrations.', 'event_espresso'),
749
-                __FILE__,
750
-                __FUNCTION__,
751
-                __LINE__
752
-            );
753
-            return false;
754
-        }
755
-        // extract attendee info from form data and save to model objects
756
-        $registrations_processed = $this->_process_registrations($registrations, $valid_data);
757
-        // if first pass thru SPCO,
758
-        // then let's check processed registrations against the total number of tickets in the cart
759
-        if ($registrations_processed === false) {
760
-            // but return immediately if the previous step exited early due to errors
761
-            return false;
762
-        } else if (! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count) {
763
-            // generate a correctly translated string for all possible singular/plural combinations
764
-            if ($this->checkout->total_ticket_count === 1 && $registrations_processed !== 1) {
765
-                $error_msg = sprintf(
766
-                    __(
767
-                        'There was %1$d ticket in the Event Queue, but %2$ds registrations were processed',
768
-                        'event_espresso'
769
-                    ),
770
-                    $this->checkout->total_ticket_count,
771
-                    $registrations_processed
772
-                );
773
-            } else if ($this->checkout->total_ticket_count !== 1 && $registrations_processed === 1) {
774
-                $error_msg = sprintf(
775
-                    __(
776
-                        'There was a total of %1$d tickets in the Event Queue, but only %2$ds registration was processed',
777
-                        'event_espresso'
778
-                    ),
779
-                    $this->checkout->total_ticket_count,
780
-                    $registrations_processed
781
-                );
782
-            } else {
783
-                $error_msg = sprintf(
784
-                    __(
785
-                        'There was a total of %1$d tickets in the Event Queue, but %2$ds registrations were processed',
786
-                        'event_espresso'
787
-                    ),
788
-                    $this->checkout->total_ticket_count,
789
-                    $registrations_processed
790
-                );
791
-            }
792
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
793
-            return false;
794
-        }
795
-        // mark this reg step as completed
796
-        $this->set_completed();
797
-        $this->_set_success_message(
798
-            __('The Attendee Information Step has been successfully completed.', 'event_espresso')
799
-        );
800
-        //do action in case a plugin wants to do something with the data submitted in step 1.
801
-        //passes EE_Single_Page_Checkout, and it's posted data
802
-        do_action('AHEE__EE_Single_Page_Checkout__process_attendee_information__end', $this, $valid_data);
803
-        return true;
804
-    }
805
-
806
-
807
-    /**
808
-     *    _process_registrations
809
-     *
810
-     * @param EE_Registration[] $registrations
811
-     * @param array             $valid_data
812
-     * @return boolean | int
813
-     * @throws \EE_Error
814
-     */
815
-    private function _process_registrations($registrations = array(), $valid_data = array())
816
-    {
817
-        // load resources and set some defaults
818
-        EE_Registry::instance()->load_model('Attendee');
819
-        // holder for primary registrant attendee object
820
-        $this->checkout->primary_attendee_obj = null;
821
-        // array for tracking reg form data for the primary registrant
822
-        $primary_registrant = array(
823
-            'line_item_id' => null,
824
-        );
825
-        $copy_primary       = false;
826
-        // reg form sections that do not contain inputs
827
-        $non_input_form_sections = array(
828
-            'primary_registrant',
829
-            'additional_attendee_reg_info',
830
-            'spco_copy_attendee_chk',
831
-        );
832
-        // attendee counter
833
-        $att_nmbr = 0;
834
-        // grab the saved registrations from the transaction
835
-        foreach ($registrations as $registration) {
836
-            // verify EE_Registration object
837
-            if (! $registration instanceof EE_Registration) {
838
-                EE_Error::add_error(
839
-                    __(
840
-                        'An invalid Registration object was discovered when attempting to process your registration information.',
841
-                        'event_espresso'
842
-                    ),
843
-                    __FILE__,
844
-                    __FUNCTION__,
845
-                    __LINE__
846
-                );
847
-                return false;
848
-            }
849
-            /** @var string $reg_url_link */
850
-            $reg_url_link = $registration->reg_url_link();
851
-            // reg_url_link exists ?
852
-            if (! empty($reg_url_link)) {
853
-                // should this registration be processed during this visit ?
854
-                if ($this->checkout->visit_allows_processing_of_this_registration($registration)) {
855
-                    // if NOT revisiting, then let's save the registration now,
856
-                    // so that we have a REG_ID to use when generating other objects
857
-                    if (! $this->checkout->revisit) {
858
-                        $registration->save();
859
-                    }
860
-                    /**
861
-                     * This allows plugins to trigger a fail on processing of a
862
-                     * registration for any conditions they may have for it to pass.
863
-                     *
864
-                     * @var bool   if true is returned by the plugin then the
865
-                     *            registration processing is halted.
866
-                     */
867
-                    if (apply_filters(
868
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___process_registrations__pre_registration_process',
869
-                        false,
870
-                        $att_nmbr,
871
-                        $registration,
872
-                        $registrations,
873
-                        $valid_data,
874
-                        $this
875
-                    )) {
876
-                        return false;
877
-                    }
878
-
879
-                    // Houston, we have a registration!
880
-                    $att_nmbr++;
881
-                    $this->_attendee_data[$reg_url_link] = array();
882
-                    // grab any existing related answer objects
883
-                    $this->_registration_answers = $registration->answers();
884
-                    // unset( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] );
885
-                    if (isset($valid_data[$reg_url_link])) {
886
-                        // do we need to copy basic info from primary attendee ?
887
-                        $copy_primary = isset($valid_data[$reg_url_link]['additional_attendee_reg_info'])
888
-                                        && absint($valid_data[$reg_url_link]['additional_attendee_reg_info']) === 0
889
-                            ? true
890
-                            : false;
891
-                        // filter form input data for this registration
892
-                        $valid_data[$reg_url_link] = (array)apply_filters(
893
-                            'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
894
-                            $valid_data[$reg_url_link]
895
-                        );
896
-                        // EEH_Debug_Tools::printr( $valid_data[ $reg_url_link ], '$valid_data[ $reg_url_link ]', __FILE__, __LINE__ );
897
-                        if (isset($valid_data['primary_attendee'])) {
898
-                            $primary_registrant['line_item_id'] = ! empty($valid_data['primary_attendee'])
899
-                                ? $valid_data['primary_attendee']
900
-                                : false;
901
-                            unset($valid_data['primary_attendee']);
902
-                        }
903
-                        // now loop through our array of valid post data && process attendee reg forms
904
-                        foreach ($valid_data[$reg_url_link] as $form_section => $form_inputs) {
905
-                            if (! in_array($form_section, $non_input_form_sections)) {
906
-                                foreach ($form_inputs as $form_input => $input_value) {
907
-                                    // \EEH_Debug_Tools::printr( $input_value, $form_input, __FILE__, __LINE__ );
908
-                                    // check for critical inputs
909
-                                    if (
910
-                                    ! $this->_verify_critical_attendee_details_are_set_and_validate_email(
911
-                                        $form_input,
912
-                                        $input_value
913
-                                    )
914
-                                    ) {
915
-                                        return false;
916
-                                    }
917
-                                    // store a bit of data about the primary attendee
918
-                                    if (
919
-                                        $att_nmbr === 1
920
-                                        && ! empty($input_value)
921
-                                        && $reg_url_link === $primary_registrant['line_item_id']
922
-                                    ) {
923
-                                        $primary_registrant[$form_input] = $input_value;
924
-                                    } else if (
925
-                                        $copy_primary
926
-                                        && $input_value === null
927
-                                        && isset($primary_registrant[$form_input])
928
-                                    ) {
929
-                                        $input_value = $primary_registrant[$form_input];
930
-                                    }
931
-                                    // now attempt to save the input data
932
-                                    if (
933
-                                    ! $this->_save_registration_form_input(
934
-                                        $registration,
935
-                                        $form_input,
936
-                                        $input_value
937
-                                    )
938
-                                    ) {
939
-                                        EE_Error::add_error(
940
-                                            sprintf(
941
-                                                __(
942
-                                                    'Unable to save registration form data for the form input: "%1$s" with the submitted value: "%2$s"',
943
-                                                    'event_espresso'
944
-                                                ),
945
-                                                $form_input,
946
-                                                $input_value
947
-                                            ),
948
-                                            __FILE__,
949
-                                            __FUNCTION__,
950
-                                            __LINE__
951
-                                        );
952
-                                        return false;
953
-                                    }
954
-                                }
955
-                            }
956
-                        }  // end of foreach ( $valid_data[ $reg_url_link ] as $form_section => $form_inputs )
957
-                    }
958
-                    //EEH_Debug_Tools::printr( $this->_attendee_data, '$this->_attendee_data', __FILE__, __LINE__ );
959
-                    // this registration does not require additional attendee information ?
960
-                    if (
961
-                        $copy_primary
962
-                        && $att_nmbr > 1
963
-                        && $this->checkout->primary_attendee_obj instanceof EE_Attendee
964
-                    ) {
965
-                        // just copy the primary registrant
966
-                        $attendee = $this->checkout->primary_attendee_obj;
967
-                    } else {
968
-                        // ensure critical details are set for additional attendees
969
-                        $this->_attendee_data[$reg_url_link] = $att_nmbr > 1
970
-                            ? $this->_copy_critical_attendee_details_from_primary_registrant(
971
-                                $this->_attendee_data[$reg_url_link]
972
-                            )
973
-                            : $this->_attendee_data[$reg_url_link];
974
-                        // execute create attendee command (which may return an existing attendee)
975
-                        $attendee = EE_Registry::instance()->BUS->execute(
976
-                            new CreateAttendeeCommand(
977
-                                $this->_attendee_data[$reg_url_link],
978
-                                $registration
979
-                            )
980
-                        );
981
-                        // who's #1 ?
982
-                        if ($att_nmbr === 1) {
983
-                            $this->checkout->primary_attendee_obj = $attendee;
984
-                        }
985
-                    }
986
-                    // EEH_Debug_Tools::printr( $attendee, '$attendee', __FILE__, __LINE__ );
987
-                    // add relation to registration, set attendee ID, and cache attendee
988
-                    $this->_associate_attendee_with_registration($registration, $attendee);
989
-                    // \EEH_Debug_Tools::printr( $registration, '$registration', __FILE__, __LINE__ );
990
-                    if (! $registration->attendee() instanceof EE_Attendee) {
991
-                        EE_Error::add_error(sprintf(__('Registration %s has an invalid or missing Attendee object.',
992
-                            'event_espresso'), $reg_url_link), __FILE__, __FUNCTION__, __LINE__);
993
-                        return false;
994
-                    }
995
-                    /** @type EE_Registration_Processor $registration_processor */
996
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
997
-                    // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
998
-                    $registration_processor->toggle_incomplete_registration_status_to_default($registration, false);
999
-                    // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1000
-                    $this->checkout->transaction->toggle_failed_transaction_status();
1001
-                    // if we've gotten this far, then let's save what we have
1002
-                    $registration->save();
1003
-                    // add relation between TXN and registration
1004
-                    $this->_associate_registration_with_transaction($registration);
1005
-                } // end of if ( ! $this->checkout->revisit || $this->checkout->primary_revisit || ( $this->checkout->revisit && $this->checkout->reg_url_link == $reg_url_link )) {
1006
-
1007
-            } else {
1008
-                EE_Error::add_error(__('An invalid or missing line item ID was encountered while attempting to process the registration form.',
1009
-                    'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1010
-                // remove malformed data
1011
-                unset($valid_data[$reg_url_link]);
1012
-                return false;
1013
-            }
1014
-
1015
-        } // end of foreach ( $this->checkout->transaction->registrations()  as $registration )
1016
-        return $att_nmbr;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     *    _save_registration_form_input
1022
-     *
1023
-     * @param EE_Registration $registration
1024
-     * @param string          $form_input
1025
-     * @param string          $input_value
1026
-     * @return boolean
1027
-     * @throws \EE_Error
1028
-     */
1029
-    private function _save_registration_form_input(
1030
-        EE_Registration $registration,
1031
-        $form_input = '',
1032
-        $input_value = ''
1033
-    ) {
1034
-        // \EEH_Debug_Tools::printr( __FUNCTION__, __CLASS__, __FILE__, __LINE__, 2 );
1035
-        // \EEH_Debug_Tools::printr( $form_input, '$form_input', __FILE__, __LINE__ );
1036
-        // \EEH_Debug_Tools::printr( $input_value, '$input_value', __FILE__, __LINE__ );
1037
-        // allow for plugins to hook in and do their own processing of the form input.
1038
-        // For plugins to bypass normal processing here, they just need to return a boolean value.
1039
-        if (apply_filters(
1040
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___save_registration_form_input',
1041
-            false,
1042
-            $registration,
1043
-            $form_input,
1044
-            $input_value,
1045
-            $this
1046
-        )) {
1047
-            return true;
1048
-        }
1049
-        /*
357
+		$question_group_reg_form = new EE_Form_Section_Proper($form_args);
358
+		return apply_filters(
359
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
360
+			$question_group_reg_form,
361
+			$registration,
362
+			$question_group,
363
+			$this
364
+		);
365
+	}
366
+
367
+
368
+	/**
369
+	 * @access public
370
+	 * @param EE_Question_Group $question_group
371
+	 * @return    EE_Form_Section_HTML
372
+	 */
373
+	private function _question_group_header(EE_Question_Group $question_group)
374
+	{
375
+		$html = '';
376
+		// group_name
377
+		if ($question_group->show_group_name() && $question_group->name() !== '') {
378
+			if ($this->checkout->admin_request) {
379
+				$html .= EEH_HTML::br();
380
+				$html .= EEH_HTML::h3(
381
+					$question_group->name(),
382
+					'', 'ee-reg-form-qstn-grp-title title', 'font-size: 1.3em; padding-left:0;'
383
+				);
384
+			} else {
385
+				$html .= EEH_HTML::h4(
386
+					$question_group->name(),
387
+					'', 'ee-reg-form-qstn-grp-title section-title'
388
+				);
389
+			}
390
+		}
391
+		// group_desc
392
+		if ($question_group->show_group_desc() && $question_group->desc() !== '') {
393
+			$html .= EEH_HTML::p(
394
+				$question_group->desc(),
395
+				'',
396
+				$this->checkout->admin_request
397
+					? 'ee-reg-form-qstn-grp-desc-pg'
398
+					: 'ee-reg-form-qstn-grp-desc-pg small-text lt-grey-text'
399
+			);
400
+
401
+		}
402
+		return new EE_Form_Section_HTML($html);
403
+	}
404
+
405
+
406
+	/**
407
+	 * @access public
408
+	 * @return    EE_Form_Section_Proper
409
+	 * @throws \EE_Error
410
+	 */
411
+	private function _copy_attendee_info_form()
412
+	{
413
+		// array of params to pass to parent constructor
414
+		return new EE_Form_Section_Proper(
415
+			array(
416
+				'subsections'     => $this->_copy_attendee_info_inputs(),
417
+				'layout_strategy' => new EE_Template_Layout(
418
+					array(
419
+						'layout_template_file'     => SPCO_REG_STEPS_PATH . $this->_slug . DS . 'copy_attendee_info.template.php',
420
+						'begin_template_file'      => null,
421
+						'input_template_file'      => null,
422
+						'subsection_template_file' => null,
423
+						'end_template_file'        => null,
424
+					)
425
+				),
426
+			)
427
+		);
428
+	}
429
+
430
+
431
+	/**
432
+	 * _auto_copy_attendee_info
433
+	 *
434
+	 * @access public
435
+	 * @return EE_Form_Section_HTML
436
+	 */
437
+	private function _auto_copy_attendee_info()
438
+	{
439
+		return new EE_Form_Section_HTML(
440
+			EEH_Template::locate_template(
441
+				SPCO_REG_STEPS_PATH . $this->_slug . DS . '_auto_copy_attendee_info.template.php',
442
+				apply_filters(
443
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information__auto_copy_attendee_info__template_args',
444
+					array()
445
+				),
446
+				true,
447
+				true
448
+			)
449
+		);
450
+	}
451
+
452
+
453
+	/**
454
+	 * _copy_attendee_info_inputs
455
+	 *
456
+	 * @access public
457
+	 * @return array
458
+	 * @throws \EE_Error
459
+	 */
460
+	private function _copy_attendee_info_inputs()
461
+	{
462
+		$copy_attendee_info_inputs = array();
463
+		$prev_ticket               = null;
464
+		// grab the saved registrations from the transaction
465
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
466
+		foreach ($registrations as $registration) {
467
+			// for all  attendees other than the primary attendee
468
+			if ($registration instanceof EE_Registration && ! $registration->is_primary_registrant()) {
469
+				// if this is a new ticket OR if this is the very first additional attendee after the primary attendee
470
+				if ($registration->ticket()->ID() !== $prev_ticket) {
471
+					$item_name                                                                                         = $registration->ticket()->name();
472
+					$item_name                                                                                         .= $registration->ticket()->description() !== ''
473
+						? ' - ' . $registration->ticket()->description()
474
+						: '';
475
+					$copy_attendee_info_inputs['spco_copy_attendee_chk[ticket-' . $registration->ticket()->ID() . ']'] = new EE_Form_Section_HTML(
476
+						'<h6 class="spco-copy-attendee-event-hdr">' . $item_name . '</h6>'
477
+					);
478
+					$prev_ticket                                                                                       = $registration->ticket()->ID();
479
+				}
480
+
481
+				$copy_attendee_info_inputs['spco_copy_attendee_chk[' . $registration->ID() . ']'] = new
482
+				EE_Checkbox_Multi_Input(
483
+					array(
484
+						$registration->ID() => sprintf(
485
+							__('Attendee #%s', 'event_espresso'),
486
+							$registration->count()
487
+						),
488
+					),
489
+					array(
490
+						'html_id'                 => 'spco-copy-attendee-chk-' . $registration->reg_url_link(),
491
+						'html_class'              => 'spco-copy-attendee-chk ee-do-not-validate',
492
+						'display_html_label_text' => false,
493
+					)
494
+				);
495
+			}
496
+		}
497
+		return $copy_attendee_info_inputs;
498
+	}
499
+
500
+
501
+	/**
502
+	 * _additional_primary_registrant_inputs
503
+	 *
504
+	 * @access public
505
+	 * @param EE_Registration $registration
506
+	 * @return    EE_Form_Input_Base
507
+	 * @throws \EE_Error
508
+	 */
509
+	private function _additional_primary_registrant_inputs(EE_Registration $registration)
510
+	{
511
+		// generate hidden input
512
+		return new EE_Hidden_Input(
513
+			array(
514
+				'html_id' => 'primary_registrant',
515
+				'default' => $registration->reg_url_link(),
516
+			)
517
+		);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @access public
523
+	 * @param EE_Registration $registration
524
+	 * @param EE_Question     $question
525
+	 * @return    EE_Form_Input_Base
526
+	 * @throws \EE_Error
527
+	 */
528
+	public function reg_form_question(EE_Registration $registration, EE_Question $question)
529
+	{
530
+
531
+		// if this question was for an attendee detail, then check for that answer
532
+		$answer_value = EEM_Answer::instance()->get_attendee_property_answer_value(
533
+			$registration,
534
+			$question->system_ID()
535
+		);
536
+		$answer       = $answer_value === null
537
+			? EEM_Answer::instance()->get_one(
538
+				array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
539
+			)
540
+			: null;
541
+		// if NOT returning to edit an existing registration
542
+		// OR if this question is for an attendee property
543
+		// OR we still don't have an EE_Answer object
544
+		if ($answer_value || ! $answer instanceof EE_Answer || ! $registration->reg_url_link()) {
545
+			// create an EE_Answer object for storing everything in
546
+			$answer = EE_Answer::new_instance(array(
547
+				'QST_ID' => $question->ID(),
548
+				'REG_ID' => $registration->ID(),
549
+			));
550
+		}
551
+		// verify instance
552
+		if ($answer instanceof EE_Answer) {
553
+			if (! empty($answer_value)) {
554
+				$answer->set('ANS_value', $answer_value);
555
+			}
556
+			$answer->cache('Question', $question);
557
+			//remember system ID had a bug where sometimes it could be null
558
+			$answer_cache_id = $question->is_system_question()
559
+				? $question->system_ID() . '-' . $registration->reg_url_link()
560
+				: $question->ID() . '-' . $registration->reg_url_link();
561
+			$registration->cache('Answer', $answer, $answer_cache_id);
562
+		}
563
+		return $this->_generate_question_input($registration, $question, $answer);
564
+
565
+	}
566
+
567
+
568
+	/**
569
+	 * @param EE_Registration $registration
570
+	 * @param EE_Question     $question
571
+	 * @param                 mixed EE_Answer|NULL      $answer
572
+	 * @return EE_Form_Input_Base
573
+	 * @throws \EE_Error
574
+	 */
575
+	private function _generate_question_input(EE_Registration $registration, EE_Question $question, $answer)
576
+	{
577
+		$identifier                             = $question->is_system_question() ? $question->system_ID() : $question->ID();
578
+		$this->_required_questions[$identifier] = $question->required() ? true : false;
579
+		add_filter(
580
+			'FHEE__EE_Question__generate_form_input__country_options',
581
+			array($this, 'use_cached_countries_for_form_input'),
582
+			10,
583
+			4
584
+		);
585
+		add_filter(
586
+			'FHEE__EE_Question__generate_form_input__state_options',
587
+			array($this, 'use_cached_states_for_form_input'),
588
+			10,
589
+			4
590
+		);
591
+		$input_constructor_args                  = array(
592
+			'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
593
+			'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
594
+			'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
595
+			'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
596
+			'html_label_class' => 'ee-reg-qstn',
597
+		);
598
+		$input_constructor_args['html_label_id'] .= '-lbl';
599
+		if ($answer instanceof EE_Answer && $answer->ID()) {
600
+			$input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
601
+			$input_constructor_args['html_id']       .= '-' . $answer->ID();
602
+			$input_constructor_args['html_label_id'] .= '-' . $answer->ID();
603
+		}
604
+		$form_input = $question->generate_form_input(
605
+			$registration,
606
+			$answer,
607
+			$input_constructor_args
608
+		);
609
+		remove_filter(
610
+			'FHEE__EE_Question__generate_form_input__country_options',
611
+			array($this, 'use_cached_countries_for_form_input')
612
+		);
613
+		remove_filter(
614
+			'FHEE__EE_Question__generate_form_input__state_options',
615
+			array($this, 'use_cached_states_for_form_input')
616
+		);
617
+		return $form_input;
618
+	}
619
+
620
+
621
+	/**
622
+	 * Gets the list of countries for the form input
623
+	 *
624
+	 * @param array|null       $countries_list
625
+	 * @param \EE_Question     $question
626
+	 * @param \EE_Registration $registration
627
+	 * @param \EE_Answer       $answer
628
+	 * @return array 2d keys are country IDs, values are their names
629
+	 */
630
+	public function use_cached_countries_for_form_input(
631
+		$countries_list,
632
+		\EE_Question $question = null,
633
+		\EE_Registration $registration = null,
634
+		\EE_Answer $answer = null
635
+	) {
636
+		$country_options = array('' => '');
637
+		// get possibly cached list of countries
638
+		$countries = $this->checkout->action === 'process_reg_step'
639
+			? EEM_Country::instance()->get_all_countries()
640
+			: EEM_Country::instance()->get_all_active_countries();
641
+		if (! empty($countries)) {
642
+			foreach ($countries as $country) {
643
+				if ($country instanceof EE_Country) {
644
+					$country_options[$country->ID()] = $country->name();
645
+				}
646
+			}
647
+		}
648
+		if ($question instanceof EE_Question
649
+			&& $registration instanceof EE_Registration) {
650
+			$answer = EEM_Answer::instance()->get_one(
651
+				array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
652
+			);
653
+		} else {
654
+			$answer = EE_Answer::new_instance();
655
+		}
656
+		$country_options = apply_filters(
657
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
658
+			$country_options,
659
+			$this,
660
+			$registration,
661
+			$question,
662
+			$answer
663
+		);
664
+		return $country_options;
665
+	}
666
+
667
+
668
+	/**
669
+	 * Gets the list of states for the form input
670
+	 *
671
+	 * @param array|null       $states_list
672
+	 * @param \EE_Question     $question
673
+	 * @param \EE_Registration $registration
674
+	 * @param \EE_Answer       $answer
675
+	 * @return array 2d keys are state IDs, values are their names
676
+	 */
677
+	public function use_cached_states_for_form_input(
678
+		$states_list,
679
+		\EE_Question $question = null,
680
+		\EE_Registration $registration = null,
681
+		\EE_Answer $answer = null
682
+	) {
683
+		$state_options = array('' => array('' => ''));
684
+		$states        = $this->checkout->action === 'process_reg_step'
685
+			? EEM_State::instance()->get_all_states()
686
+			: EEM_State::instance()->get_all_active_states();
687
+		if (! empty($states)) {
688
+			foreach ($states as $state) {
689
+				if ($state instanceof EE_State) {
690
+					$state_options[$state->country()->name()][$state->ID()] = $state->name();
691
+				}
692
+			}
693
+		}
694
+		$state_options = apply_filters(
695
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
696
+			$state_options,
697
+			$this,
698
+			$registration,
699
+			$question,
700
+			$answer
701
+		);
702
+		return $state_options;
703
+	}
704
+
705
+
706
+
707
+
708
+
709
+
710
+	/********************************************************************************************************/
711
+	/****************************************  PROCESS REG STEP  ****************************************/
712
+	/********************************************************************************************************/
713
+	/**
714
+	 * @return boolean
715
+	 * @throws \EE_Error
716
+	 */
717
+	public function process_reg_step()
718
+	{
719
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
720
+		// grab validated data from form
721
+		$valid_data = $this->checkout->current_step->valid_data();
722
+		// EEH_Debug_Tools::printr( $_REQUEST, '$_REQUEST', __FILE__, __LINE__ );
723
+		// EEH_Debug_Tools::printr( $valid_data, '$valid_data', __FILE__, __LINE__ );
724
+		// if we don't have any $valid_data then something went TERRIBLY WRONG !!!
725
+		if (empty($valid_data)) {
726
+			EE_Error::add_error(
727
+				__('No valid question responses were received.', 'event_espresso'),
728
+				__FILE__,
729
+				__FUNCTION__,
730
+				__LINE__
731
+			);
732
+			return false;
733
+		}
734
+		if (! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg) {
735
+			EE_Error::add_error(
736
+				__('A valid transaction could not be initiated for processing your registrations.', 'event_espresso'),
737
+				__FILE__,
738
+				__FUNCTION__,
739
+				__LINE__
740
+			);
741
+			return false;
742
+		}
743
+		// get cached registrations
744
+		$registrations = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
745
+		// verify we got the goods
746
+		if (empty($registrations)) {
747
+			EE_Error::add_error(
748
+				__('Your form data could not be applied to any valid registrations.', 'event_espresso'),
749
+				__FILE__,
750
+				__FUNCTION__,
751
+				__LINE__
752
+			);
753
+			return false;
754
+		}
755
+		// extract attendee info from form data and save to model objects
756
+		$registrations_processed = $this->_process_registrations($registrations, $valid_data);
757
+		// if first pass thru SPCO,
758
+		// then let's check processed registrations against the total number of tickets in the cart
759
+		if ($registrations_processed === false) {
760
+			// but return immediately if the previous step exited early due to errors
761
+			return false;
762
+		} else if (! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count) {
763
+			// generate a correctly translated string for all possible singular/plural combinations
764
+			if ($this->checkout->total_ticket_count === 1 && $registrations_processed !== 1) {
765
+				$error_msg = sprintf(
766
+					__(
767
+						'There was %1$d ticket in the Event Queue, but %2$ds registrations were processed',
768
+						'event_espresso'
769
+					),
770
+					$this->checkout->total_ticket_count,
771
+					$registrations_processed
772
+				);
773
+			} else if ($this->checkout->total_ticket_count !== 1 && $registrations_processed === 1) {
774
+				$error_msg = sprintf(
775
+					__(
776
+						'There was a total of %1$d tickets in the Event Queue, but only %2$ds registration was processed',
777
+						'event_espresso'
778
+					),
779
+					$this->checkout->total_ticket_count,
780
+					$registrations_processed
781
+				);
782
+			} else {
783
+				$error_msg = sprintf(
784
+					__(
785
+						'There was a total of %1$d tickets in the Event Queue, but %2$ds registrations were processed',
786
+						'event_espresso'
787
+					),
788
+					$this->checkout->total_ticket_count,
789
+					$registrations_processed
790
+				);
791
+			}
792
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
793
+			return false;
794
+		}
795
+		// mark this reg step as completed
796
+		$this->set_completed();
797
+		$this->_set_success_message(
798
+			__('The Attendee Information Step has been successfully completed.', 'event_espresso')
799
+		);
800
+		//do action in case a plugin wants to do something with the data submitted in step 1.
801
+		//passes EE_Single_Page_Checkout, and it's posted data
802
+		do_action('AHEE__EE_Single_Page_Checkout__process_attendee_information__end', $this, $valid_data);
803
+		return true;
804
+	}
805
+
806
+
807
+	/**
808
+	 *    _process_registrations
809
+	 *
810
+	 * @param EE_Registration[] $registrations
811
+	 * @param array             $valid_data
812
+	 * @return boolean | int
813
+	 * @throws \EE_Error
814
+	 */
815
+	private function _process_registrations($registrations = array(), $valid_data = array())
816
+	{
817
+		// load resources and set some defaults
818
+		EE_Registry::instance()->load_model('Attendee');
819
+		// holder for primary registrant attendee object
820
+		$this->checkout->primary_attendee_obj = null;
821
+		// array for tracking reg form data for the primary registrant
822
+		$primary_registrant = array(
823
+			'line_item_id' => null,
824
+		);
825
+		$copy_primary       = false;
826
+		// reg form sections that do not contain inputs
827
+		$non_input_form_sections = array(
828
+			'primary_registrant',
829
+			'additional_attendee_reg_info',
830
+			'spco_copy_attendee_chk',
831
+		);
832
+		// attendee counter
833
+		$att_nmbr = 0;
834
+		// grab the saved registrations from the transaction
835
+		foreach ($registrations as $registration) {
836
+			// verify EE_Registration object
837
+			if (! $registration instanceof EE_Registration) {
838
+				EE_Error::add_error(
839
+					__(
840
+						'An invalid Registration object was discovered when attempting to process your registration information.',
841
+						'event_espresso'
842
+					),
843
+					__FILE__,
844
+					__FUNCTION__,
845
+					__LINE__
846
+				);
847
+				return false;
848
+			}
849
+			/** @var string $reg_url_link */
850
+			$reg_url_link = $registration->reg_url_link();
851
+			// reg_url_link exists ?
852
+			if (! empty($reg_url_link)) {
853
+				// should this registration be processed during this visit ?
854
+				if ($this->checkout->visit_allows_processing_of_this_registration($registration)) {
855
+					// if NOT revisiting, then let's save the registration now,
856
+					// so that we have a REG_ID to use when generating other objects
857
+					if (! $this->checkout->revisit) {
858
+						$registration->save();
859
+					}
860
+					/**
861
+					 * This allows plugins to trigger a fail on processing of a
862
+					 * registration for any conditions they may have for it to pass.
863
+					 *
864
+					 * @var bool   if true is returned by the plugin then the
865
+					 *            registration processing is halted.
866
+					 */
867
+					if (apply_filters(
868
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___process_registrations__pre_registration_process',
869
+						false,
870
+						$att_nmbr,
871
+						$registration,
872
+						$registrations,
873
+						$valid_data,
874
+						$this
875
+					)) {
876
+						return false;
877
+					}
878
+
879
+					// Houston, we have a registration!
880
+					$att_nmbr++;
881
+					$this->_attendee_data[$reg_url_link] = array();
882
+					// grab any existing related answer objects
883
+					$this->_registration_answers = $registration->answers();
884
+					// unset( $valid_data[ $reg_url_link ]['additional_attendee_reg_info'] );
885
+					if (isset($valid_data[$reg_url_link])) {
886
+						// do we need to copy basic info from primary attendee ?
887
+						$copy_primary = isset($valid_data[$reg_url_link]['additional_attendee_reg_info'])
888
+										&& absint($valid_data[$reg_url_link]['additional_attendee_reg_info']) === 0
889
+							? true
890
+							: false;
891
+						// filter form input data for this registration
892
+						$valid_data[$reg_url_link] = (array)apply_filters(
893
+							'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
894
+							$valid_data[$reg_url_link]
895
+						);
896
+						// EEH_Debug_Tools::printr( $valid_data[ $reg_url_link ], '$valid_data[ $reg_url_link ]', __FILE__, __LINE__ );
897
+						if (isset($valid_data['primary_attendee'])) {
898
+							$primary_registrant['line_item_id'] = ! empty($valid_data['primary_attendee'])
899
+								? $valid_data['primary_attendee']
900
+								: false;
901
+							unset($valid_data['primary_attendee']);
902
+						}
903
+						// now loop through our array of valid post data && process attendee reg forms
904
+						foreach ($valid_data[$reg_url_link] as $form_section => $form_inputs) {
905
+							if (! in_array($form_section, $non_input_form_sections)) {
906
+								foreach ($form_inputs as $form_input => $input_value) {
907
+									// \EEH_Debug_Tools::printr( $input_value, $form_input, __FILE__, __LINE__ );
908
+									// check for critical inputs
909
+									if (
910
+									! $this->_verify_critical_attendee_details_are_set_and_validate_email(
911
+										$form_input,
912
+										$input_value
913
+									)
914
+									) {
915
+										return false;
916
+									}
917
+									// store a bit of data about the primary attendee
918
+									if (
919
+										$att_nmbr === 1
920
+										&& ! empty($input_value)
921
+										&& $reg_url_link === $primary_registrant['line_item_id']
922
+									) {
923
+										$primary_registrant[$form_input] = $input_value;
924
+									} else if (
925
+										$copy_primary
926
+										&& $input_value === null
927
+										&& isset($primary_registrant[$form_input])
928
+									) {
929
+										$input_value = $primary_registrant[$form_input];
930
+									}
931
+									// now attempt to save the input data
932
+									if (
933
+									! $this->_save_registration_form_input(
934
+										$registration,
935
+										$form_input,
936
+										$input_value
937
+									)
938
+									) {
939
+										EE_Error::add_error(
940
+											sprintf(
941
+												__(
942
+													'Unable to save registration form data for the form input: "%1$s" with the submitted value: "%2$s"',
943
+													'event_espresso'
944
+												),
945
+												$form_input,
946
+												$input_value
947
+											),
948
+											__FILE__,
949
+											__FUNCTION__,
950
+											__LINE__
951
+										);
952
+										return false;
953
+									}
954
+								}
955
+							}
956
+						}  // end of foreach ( $valid_data[ $reg_url_link ] as $form_section => $form_inputs )
957
+					}
958
+					//EEH_Debug_Tools::printr( $this->_attendee_data, '$this->_attendee_data', __FILE__, __LINE__ );
959
+					// this registration does not require additional attendee information ?
960
+					if (
961
+						$copy_primary
962
+						&& $att_nmbr > 1
963
+						&& $this->checkout->primary_attendee_obj instanceof EE_Attendee
964
+					) {
965
+						// just copy the primary registrant
966
+						$attendee = $this->checkout->primary_attendee_obj;
967
+					} else {
968
+						// ensure critical details are set for additional attendees
969
+						$this->_attendee_data[$reg_url_link] = $att_nmbr > 1
970
+							? $this->_copy_critical_attendee_details_from_primary_registrant(
971
+								$this->_attendee_data[$reg_url_link]
972
+							)
973
+							: $this->_attendee_data[$reg_url_link];
974
+						// execute create attendee command (which may return an existing attendee)
975
+						$attendee = EE_Registry::instance()->BUS->execute(
976
+							new CreateAttendeeCommand(
977
+								$this->_attendee_data[$reg_url_link],
978
+								$registration
979
+							)
980
+						);
981
+						// who's #1 ?
982
+						if ($att_nmbr === 1) {
983
+							$this->checkout->primary_attendee_obj = $attendee;
984
+						}
985
+					}
986
+					// EEH_Debug_Tools::printr( $attendee, '$attendee', __FILE__, __LINE__ );
987
+					// add relation to registration, set attendee ID, and cache attendee
988
+					$this->_associate_attendee_with_registration($registration, $attendee);
989
+					// \EEH_Debug_Tools::printr( $registration, '$registration', __FILE__, __LINE__ );
990
+					if (! $registration->attendee() instanceof EE_Attendee) {
991
+						EE_Error::add_error(sprintf(__('Registration %s has an invalid or missing Attendee object.',
992
+							'event_espresso'), $reg_url_link), __FILE__, __FUNCTION__, __LINE__);
993
+						return false;
994
+					}
995
+					/** @type EE_Registration_Processor $registration_processor */
996
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
997
+					// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
998
+					$registration_processor->toggle_incomplete_registration_status_to_default($registration, false);
999
+					// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1000
+					$this->checkout->transaction->toggle_failed_transaction_status();
1001
+					// if we've gotten this far, then let's save what we have
1002
+					$registration->save();
1003
+					// add relation between TXN and registration
1004
+					$this->_associate_registration_with_transaction($registration);
1005
+				} // end of if ( ! $this->checkout->revisit || $this->checkout->primary_revisit || ( $this->checkout->revisit && $this->checkout->reg_url_link == $reg_url_link )) {
1006
+
1007
+			} else {
1008
+				EE_Error::add_error(__('An invalid or missing line item ID was encountered while attempting to process the registration form.',
1009
+					'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1010
+				// remove malformed data
1011
+				unset($valid_data[$reg_url_link]);
1012
+				return false;
1013
+			}
1014
+
1015
+		} // end of foreach ( $this->checkout->transaction->registrations()  as $registration )
1016
+		return $att_nmbr;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 *    _save_registration_form_input
1022
+	 *
1023
+	 * @param EE_Registration $registration
1024
+	 * @param string          $form_input
1025
+	 * @param string          $input_value
1026
+	 * @return boolean
1027
+	 * @throws \EE_Error
1028
+	 */
1029
+	private function _save_registration_form_input(
1030
+		EE_Registration $registration,
1031
+		$form_input = '',
1032
+		$input_value = ''
1033
+	) {
1034
+		// \EEH_Debug_Tools::printr( __FUNCTION__, __CLASS__, __FILE__, __LINE__, 2 );
1035
+		// \EEH_Debug_Tools::printr( $form_input, '$form_input', __FILE__, __LINE__ );
1036
+		// \EEH_Debug_Tools::printr( $input_value, '$input_value', __FILE__, __LINE__ );
1037
+		// allow for plugins to hook in and do their own processing of the form input.
1038
+		// For plugins to bypass normal processing here, they just need to return a boolean value.
1039
+		if (apply_filters(
1040
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___save_registration_form_input',
1041
+			false,
1042
+			$registration,
1043
+			$form_input,
1044
+			$input_value,
1045
+			$this
1046
+		)) {
1047
+			return true;
1048
+		}
1049
+		/*
1050 1050
          * $answer_cache_id is the key used to find the EE_Answer we want
1051 1051
          * @see https://events.codebasehq.com/projects/event-espresso/tickets/10477
1052 1052
          */
1053
-        $answer_cache_id = $this->checkout->reg_url_link
1054
-            ? $form_input . '-' . $registration->reg_url_link()
1055
-            : $form_input;
1056
-        $answer_is_obj   = isset($this->_registration_answers[$answer_cache_id])
1057
-                           && $this->_registration_answers[$answer_cache_id] instanceof EE_Answer
1058
-            ? true
1059
-            : false;
1060
-        //rename form_inputs if they are EE_Attendee properties
1061
-        switch ((string)$form_input) {
1062
-
1063
-            case 'state' :
1064
-            case 'STA_ID' :
1065
-                $attendee_property = true;
1066
-                $form_input        = 'STA_ID';
1067
-                break;
1068
-
1069
-            case 'country' :
1070
-            case 'CNT_ISO' :
1071
-                $attendee_property = true;
1072
-                $form_input        = 'CNT_ISO';
1073
-                break;
1074
-
1075
-            default :
1076
-                $ATT_input = 'ATT_' . $form_input;
1077
-                //EEH_Debug_Tools::printr( $ATT_input, '$ATT_input', __FILE__, __LINE__ );
1078
-                $attendee_property = EEM_Attendee::instance()->has_field($ATT_input) ? true : false;
1079
-                $form_input        = $attendee_property ? 'ATT_' . $form_input : $form_input;
1080
-        }
1081
-        // EEH_Debug_Tools::printr( $answer_cache_id, '$answer_cache_id', __FILE__, __LINE__ );
1082
-        // EEH_Debug_Tools::printr( $attendee_property, '$attendee_property', __FILE__, __LINE__ );
1083
-        // EEH_Debug_Tools::printr( $answer_is_obj, '$answer_is_obj', __FILE__, __LINE__ );
1084
-        // if this form input has a corresponding attendee property
1085
-        if ($attendee_property) {
1086
-            $this->_attendee_data[$registration->reg_url_link()][$form_input] = $input_value;
1087
-            if ($answer_is_obj) {
1088
-                // and delete the corresponding answer since we won't be storing this data in that object
1089
-                $registration->_remove_relation_to($this->_registration_answers[$answer_cache_id], 'Answer');
1090
-                $this->_registration_answers[$answer_cache_id]->delete_permanently();
1091
-            }
1092
-            return true;
1093
-        } elseif ($answer_is_obj) {
1094
-            // save this data to the answer object
1095
-            $this->_registration_answers[$answer_cache_id]->set_value($input_value);
1096
-            $result = $this->_registration_answers[$answer_cache_id]->save();
1097
-            return $result !== false ? true : false;
1098
-        } else {
1099
-            foreach ($this->_registration_answers as $answer) {
1100
-                if ($answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id) {
1101
-                    $answer->set_value($input_value);
1102
-                    $result = $answer->save();
1103
-                    return $result !== false ? true : false;
1104
-                }
1105
-            }
1106
-        }
1107
-        return false;
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     *    _verify_critical_attendee_details_are_set
1113
-     *
1114
-     * @param string $form_input
1115
-     * @param string $input_value
1116
-     * @return boolean
1117
-     */
1118
-    private function _verify_critical_attendee_details_are_set_and_validate_email(
1119
-        $form_input = '',
1120
-        $input_value = ''
1121
-    ) {
1122
-        if (empty($input_value)) {
1123
-            // if the form input isn't marked as being required, then just return
1124
-            if (! isset($this->_required_questions[$form_input]) || ! $this->_required_questions[$form_input]) {
1125
-                return true;
1126
-            }
1127
-            switch ($form_input) {
1128
-                case 'fname' :
1129
-                    EE_Error::add_error(
1130
-                        __('First Name is a required value.', 'event_espresso'),
1131
-                        __FILE__,
1132
-                        __FUNCTION__,
1133
-                        __LINE__
1134
-                    );
1135
-                    return false;
1136
-                    break;
1137
-                case 'lname' :
1138
-                    EE_Error::add_error(
1139
-                        __('Last Name is a required value.', 'event_espresso'),
1140
-                        __FILE__,
1141
-                        __FUNCTION__,
1142
-                        __LINE__
1143
-                    );
1144
-                    return false;
1145
-                    break;
1146
-                case 'email' :
1147
-                    EE_Error::add_error(
1148
-                        __('Please enter a valid email address.', 'event_espresso'),
1149
-                        __FILE__,
1150
-                        __FUNCTION__,
1151
-                        __LINE__
1152
-                    );
1153
-                    return false;
1154
-                    break;
1155
-            }
1156
-        }
1157
-        return true;
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     *    _associate_attendee_with_registration
1163
-     *
1164
-     * @param EE_Registration $registration
1165
-     * @param EE_Attendee     $attendee
1166
-     * @return void
1167
-     * @throws \EE_Error
1168
-     */
1169
-    private function _associate_attendee_with_registration(EE_Registration $registration, EE_Attendee $attendee)
1170
-    {
1171
-        // add relation to attendee
1172
-        $registration->_add_relation_to($attendee, 'Attendee');
1173
-        $registration->set_attendee_id($attendee->ID());
1174
-        $registration->update_cache_after_object_save('Attendee', $attendee);
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     *    _associate_registration_with_transaction
1180
-     *
1181
-     * @param EE_Registration $registration
1182
-     * @return void
1183
-     * @throws \EE_Error
1184
-     */
1185
-    private function _associate_registration_with_transaction(EE_Registration $registration)
1186
-    {
1187
-        // add relation to registration
1188
-        $this->checkout->transaction->_add_relation_to($registration, 'Registration');
1189
-        $this->checkout->transaction->update_cache_after_object_save('Registration', $registration);
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     *    _copy_critical_attendee_details_from_primary_registrant
1195
-     *    ensures that all attendees at least have data for first name, last name, and email address
1196
-     *
1197
-     * @param array $attendee_data
1198
-     * @return array
1199
-     * @throws \EE_Error
1200
-     */
1201
-    private function _copy_critical_attendee_details_from_primary_registrant($attendee_data = array())
1202
-    {
1203
-        // bare minimum critical details include first name, last name, email address
1204
-        $critical_attendee_details = array('ATT_fname', 'ATT_lname', 'ATT_email');
1205
-        // add address info to critical details?
1206
-        if (apply_filters(
1207
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information__merge_address_details_with_critical_attendee_details',
1208
-            false
1209
-        )) {
1210
-            $address_details           = array(
1211
-                'ATT_address',
1212
-                'ATT_address2',
1213
-                'ATT_city',
1214
-                'STA_ID',
1215
-                'CNT_ISO',
1216
-                'ATT_zip',
1217
-                'ATT_phone',
1218
-            );
1219
-            $critical_attendee_details = array_merge($critical_attendee_details, $address_details);
1220
-        }
1221
-        foreach ($critical_attendee_details as $critical_attendee_detail) {
1222
-            if (! isset($attendee_data[$critical_attendee_detail])
1223
-                || empty($attendee_data[$critical_attendee_detail])
1224
-            ) {
1225
-                $attendee_data[$critical_attendee_detail] = $this->checkout->primary_attendee_obj->get(
1226
-                    $critical_attendee_detail
1227
-                );
1228
-            }
1229
-        }
1230
-        return $attendee_data;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     *    update_reg_step
1236
-     *    this is the final step after a user  revisits the site to edit their attendee information
1237
-     *    this gets called AFTER the process_reg_step() method above
1238
-     *
1239
-     * @return boolean
1240
-     * @throws \EE_Error
1241
-     */
1242
-    public function update_reg_step()
1243
-    {
1244
-        // save everything
1245
-        if ($this->process_reg_step()) {
1246
-            $this->checkout->redirect     = true;
1247
-            $this->checkout->redirect_url = add_query_arg(
1248
-                array(
1249
-                    'e_reg_url_link' => $this->checkout->reg_url_link,
1250
-                    'revisit'        => true,
1251
-                ),
1252
-                $this->checkout->thank_you_page_url
1253
-            );
1254
-            $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1255
-            return true;
1256
-        }
1257
-        return false;
1258
-    }
1053
+		$answer_cache_id = $this->checkout->reg_url_link
1054
+			? $form_input . '-' . $registration->reg_url_link()
1055
+			: $form_input;
1056
+		$answer_is_obj   = isset($this->_registration_answers[$answer_cache_id])
1057
+						   && $this->_registration_answers[$answer_cache_id] instanceof EE_Answer
1058
+			? true
1059
+			: false;
1060
+		//rename form_inputs if they are EE_Attendee properties
1061
+		switch ((string)$form_input) {
1062
+
1063
+			case 'state' :
1064
+			case 'STA_ID' :
1065
+				$attendee_property = true;
1066
+				$form_input        = 'STA_ID';
1067
+				break;
1068
+
1069
+			case 'country' :
1070
+			case 'CNT_ISO' :
1071
+				$attendee_property = true;
1072
+				$form_input        = 'CNT_ISO';
1073
+				break;
1074
+
1075
+			default :
1076
+				$ATT_input = 'ATT_' . $form_input;
1077
+				//EEH_Debug_Tools::printr( $ATT_input, '$ATT_input', __FILE__, __LINE__ );
1078
+				$attendee_property = EEM_Attendee::instance()->has_field($ATT_input) ? true : false;
1079
+				$form_input        = $attendee_property ? 'ATT_' . $form_input : $form_input;
1080
+		}
1081
+		// EEH_Debug_Tools::printr( $answer_cache_id, '$answer_cache_id', __FILE__, __LINE__ );
1082
+		// EEH_Debug_Tools::printr( $attendee_property, '$attendee_property', __FILE__, __LINE__ );
1083
+		// EEH_Debug_Tools::printr( $answer_is_obj, '$answer_is_obj', __FILE__, __LINE__ );
1084
+		// if this form input has a corresponding attendee property
1085
+		if ($attendee_property) {
1086
+			$this->_attendee_data[$registration->reg_url_link()][$form_input] = $input_value;
1087
+			if ($answer_is_obj) {
1088
+				// and delete the corresponding answer since we won't be storing this data in that object
1089
+				$registration->_remove_relation_to($this->_registration_answers[$answer_cache_id], 'Answer');
1090
+				$this->_registration_answers[$answer_cache_id]->delete_permanently();
1091
+			}
1092
+			return true;
1093
+		} elseif ($answer_is_obj) {
1094
+			// save this data to the answer object
1095
+			$this->_registration_answers[$answer_cache_id]->set_value($input_value);
1096
+			$result = $this->_registration_answers[$answer_cache_id]->save();
1097
+			return $result !== false ? true : false;
1098
+		} else {
1099
+			foreach ($this->_registration_answers as $answer) {
1100
+				if ($answer instanceof EE_Answer && $answer->question_ID() === $answer_cache_id) {
1101
+					$answer->set_value($input_value);
1102
+					$result = $answer->save();
1103
+					return $result !== false ? true : false;
1104
+				}
1105
+			}
1106
+		}
1107
+		return false;
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 *    _verify_critical_attendee_details_are_set
1113
+	 *
1114
+	 * @param string $form_input
1115
+	 * @param string $input_value
1116
+	 * @return boolean
1117
+	 */
1118
+	private function _verify_critical_attendee_details_are_set_and_validate_email(
1119
+		$form_input = '',
1120
+		$input_value = ''
1121
+	) {
1122
+		if (empty($input_value)) {
1123
+			// if the form input isn't marked as being required, then just return
1124
+			if (! isset($this->_required_questions[$form_input]) || ! $this->_required_questions[$form_input]) {
1125
+				return true;
1126
+			}
1127
+			switch ($form_input) {
1128
+				case 'fname' :
1129
+					EE_Error::add_error(
1130
+						__('First Name is a required value.', 'event_espresso'),
1131
+						__FILE__,
1132
+						__FUNCTION__,
1133
+						__LINE__
1134
+					);
1135
+					return false;
1136
+					break;
1137
+				case 'lname' :
1138
+					EE_Error::add_error(
1139
+						__('Last Name is a required value.', 'event_espresso'),
1140
+						__FILE__,
1141
+						__FUNCTION__,
1142
+						__LINE__
1143
+					);
1144
+					return false;
1145
+					break;
1146
+				case 'email' :
1147
+					EE_Error::add_error(
1148
+						__('Please enter a valid email address.', 'event_espresso'),
1149
+						__FILE__,
1150
+						__FUNCTION__,
1151
+						__LINE__
1152
+					);
1153
+					return false;
1154
+					break;
1155
+			}
1156
+		}
1157
+		return true;
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 *    _associate_attendee_with_registration
1163
+	 *
1164
+	 * @param EE_Registration $registration
1165
+	 * @param EE_Attendee     $attendee
1166
+	 * @return void
1167
+	 * @throws \EE_Error
1168
+	 */
1169
+	private function _associate_attendee_with_registration(EE_Registration $registration, EE_Attendee $attendee)
1170
+	{
1171
+		// add relation to attendee
1172
+		$registration->_add_relation_to($attendee, 'Attendee');
1173
+		$registration->set_attendee_id($attendee->ID());
1174
+		$registration->update_cache_after_object_save('Attendee', $attendee);
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 *    _associate_registration_with_transaction
1180
+	 *
1181
+	 * @param EE_Registration $registration
1182
+	 * @return void
1183
+	 * @throws \EE_Error
1184
+	 */
1185
+	private function _associate_registration_with_transaction(EE_Registration $registration)
1186
+	{
1187
+		// add relation to registration
1188
+		$this->checkout->transaction->_add_relation_to($registration, 'Registration');
1189
+		$this->checkout->transaction->update_cache_after_object_save('Registration', $registration);
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 *    _copy_critical_attendee_details_from_primary_registrant
1195
+	 *    ensures that all attendees at least have data for first name, last name, and email address
1196
+	 *
1197
+	 * @param array $attendee_data
1198
+	 * @return array
1199
+	 * @throws \EE_Error
1200
+	 */
1201
+	private function _copy_critical_attendee_details_from_primary_registrant($attendee_data = array())
1202
+	{
1203
+		// bare minimum critical details include first name, last name, email address
1204
+		$critical_attendee_details = array('ATT_fname', 'ATT_lname', 'ATT_email');
1205
+		// add address info to critical details?
1206
+		if (apply_filters(
1207
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information__merge_address_details_with_critical_attendee_details',
1208
+			false
1209
+		)) {
1210
+			$address_details           = array(
1211
+				'ATT_address',
1212
+				'ATT_address2',
1213
+				'ATT_city',
1214
+				'STA_ID',
1215
+				'CNT_ISO',
1216
+				'ATT_zip',
1217
+				'ATT_phone',
1218
+			);
1219
+			$critical_attendee_details = array_merge($critical_attendee_details, $address_details);
1220
+		}
1221
+		foreach ($critical_attendee_details as $critical_attendee_detail) {
1222
+			if (! isset($attendee_data[$critical_attendee_detail])
1223
+				|| empty($attendee_data[$critical_attendee_detail])
1224
+			) {
1225
+				$attendee_data[$critical_attendee_detail] = $this->checkout->primary_attendee_obj->get(
1226
+					$critical_attendee_detail
1227
+				);
1228
+			}
1229
+		}
1230
+		return $attendee_data;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 *    update_reg_step
1236
+	 *    this is the final step after a user  revisits the site to edit their attendee information
1237
+	 *    this gets called AFTER the process_reg_step() method above
1238
+	 *
1239
+	 * @return boolean
1240
+	 * @throws \EE_Error
1241
+	 */
1242
+	public function update_reg_step()
1243
+	{
1244
+		// save everything
1245
+		if ($this->process_reg_step()) {
1246
+			$this->checkout->redirect     = true;
1247
+			$this->checkout->redirect_url = add_query_arg(
1248
+				array(
1249
+					'e_reg_url_link' => $this->checkout->reg_url_link,
1250
+					'revisit'        => true,
1251
+				),
1252
+				$this->checkout->thank_you_page_url
1253
+			);
1254
+			$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1255
+			return true;
1256
+		}
1257
+		return false;
1258
+	}
1259 1259
 
1260 1260
 
1261 1261
 }
Please login to merge, or discard this patch.
Spacing   +51 added lines, -52 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\commands\attendee\CreateAttendeeCommand;
2 2
 
3
-if (! defined('EVENT_ESPRESSO_VERSION')) {
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
5 5
 }
6 6
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
     {
48 48
         $this->_slug     = 'attendee_information';
49 49
         $this->_name     = __('Attendee Information', 'event_espresso');
50
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'attendee_info_main.template.php';
50
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'attendee_info_main.template.php';
51 51
         $this->checkout  = $checkout;
52 52
         $this->_reset_success_message();
53 53
         $this->set_instructions(
@@ -67,18 +67,18 @@  discard block
 block discarded – undo
67 67
             'Please answer all required questions correctly before proceeding.',
68 68
             'event_espresso'
69 69
         );
70
-        EE_Registry::$i18n_js_strings['attendee_info_copied']      = sprintf(
70
+        EE_Registry::$i18n_js_strings['attendee_info_copied'] = sprintf(
71 71
             __(
72 72
                 'The attendee information was successfully copied.%sPlease ensure the rest of the registration form is completed before proceeding.',
73 73
                 'event_espresso'
74 74
             ),
75 75
             '<br/>'
76 76
         );
77
-        EE_Registry::$i18n_js_strings['attendee_info_copy_error']  = __(
77
+        EE_Registry::$i18n_js_strings['attendee_info_copy_error'] = __(
78 78
             'An unknown error occurred on the server while attempting to copy the attendee information. Please refresh the page and try again.',
79 79
             'event_espresso'
80 80
         );
81
-        EE_Registry::$i18n_js_strings['enter_valid_email']         = __(
81
+        EE_Registry::$i18n_js_strings['enter_valid_email'] = __(
82 82
             'You must enter a valid email address.',
83 83
             'event_espresso'
84 84
         );
@@ -139,14 +139,14 @@  discard block
 block discarded – undo
139 139
                     && $this->checkout->visit_allows_processing_of_this_registration($registration)
140 140
                 ) {
141 141
                     $subsections[$registration->reg_url_link()] = $this->_registrations_reg_form($registration);
142
-                    if (! $this->checkout->admin_request) {
142
+                    if ( ! $this->checkout->admin_request) {
143 143
                         $template_args['registrations'][$registration->reg_url_link()]    = $registration;
144 144
                         $template_args['ticket_count'][$registration->ticket()->ID()]     = isset(
145 145
                             $template_args['ticket_count'][$registration->ticket()->ID()]
146 146
                         )
147 147
                             ? $template_args['ticket_count'][$registration->ticket()->ID()] + 1
148 148
                             : 1;
149
-                        $ticket_line_item                                                 = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
149
+                        $ticket_line_item = EEH_Line_Item::get_line_items_by_object_type_and_IDs(
150 150
                             $this->checkout->cart->get_grand_total(),
151 151
                             'Ticket',
152 152
                             array($registration->ticket()->ID())
@@ -185,8 +185,7 @@  discard block
 block discarded – undo
185 185
                 'html_id'         => $this->reg_form_name(),
186 186
                 'subsections'     => $subsections,
187 187
                 'layout_strategy' => $this->checkout->admin_request ?
188
-                    new EE_Div_Per_Section_Layout() :
189
-                    new EE_Template_Layout(
188
+                    new EE_Div_Per_Section_Layout() : new EE_Template_Layout(
190 189
                         array(
191 190
                             'layout_template_file' => $this->_template, // layout_template
192 191
                             'template_args'        => $template_args,
@@ -221,7 +220,7 @@  discard block
 block discarded – undo
221 220
             if ($question_groups) {
222 221
                 // array of params to pass to parent constructor
223 222
                 $form_args = array(
224
-                    'html_id'         => 'ee-registration-' . $registration->reg_url_link(),
223
+                    'html_id'         => 'ee-registration-'.$registration->reg_url_link(),
225 224
                     'html_class'      => 'ee-reg-form-attendee-dv',
226 225
                     'html_style'      => $this->checkout->admin_request
227 226
                         ? 'padding:0em 2em 1em; margin:3em 0 0; border:1px solid #ddd;'
@@ -275,7 +274,7 @@  discard block
 block discarded – undo
275 274
         // generate hidden input
276 275
         return new EE_Hidden_Input(
277 276
             array(
278
-                'html_id' => 'additional-attendee-reg-info-' . $registration->reg_url_link(),
277
+                'html_id' => 'additional-attendee-reg-info-'.$registration->reg_url_link(),
279 278
                 'default' => $additional_attendee_reg_info,
280 279
             )
281 280
         );
@@ -292,11 +291,11 @@  discard block
 block discarded – undo
292 291
     {
293 292
         // array of params to pass to parent constructor
294 293
         $form_args = array(
295
-            'html_id'         => 'ee-reg-form-qstn-grp-' . $question_group->identifier(),
294
+            'html_id'         => 'ee-reg-form-qstn-grp-'.$question_group->identifier(),
296 295
             'html_class'      => $this->checkout->admin_request
297 296
                 ? 'form-table ee-reg-form-qstn-grp-dv'
298 297
                 : 'ee-reg-form-qstn-grp-dv',
299
-            'html_label_id'   => 'ee-reg-form-qstn-grp-' . $question_group->identifier() . '-lbl',
298
+            'html_label_id'   => 'ee-reg-form-qstn-grp-'.$question_group->identifier().'-lbl',
300 299
             'subsections'     => array(
301 300
                 'reg_form_qstn_grp_hdr' => $this->_question_group_header($question_group),
302 301
             ),
@@ -307,7 +306,7 @@  discard block
 block discarded – undo
307 306
         // where params
308 307
         $query_params = array('QST_deleted' => 0);
309 308
         // don't load admin only questions on the frontend
310
-        if (! $this->checkout->admin_request) {
309
+        if ( ! $this->checkout->admin_request) {
311 310
             $query_params['QST_admin_only'] = array('!=', true);
312 311
         }
313 312
         $questions = $question_group->get_many_related(
@@ -416,7 +415,7 @@  discard block
 block discarded – undo
416 415
                 'subsections'     => $this->_copy_attendee_info_inputs(),
417 416
                 'layout_strategy' => new EE_Template_Layout(
418 417
                     array(
419
-                        'layout_template_file'     => SPCO_REG_STEPS_PATH . $this->_slug . DS . 'copy_attendee_info.template.php',
418
+                        'layout_template_file'     => SPCO_REG_STEPS_PATH.$this->_slug.DS.'copy_attendee_info.template.php',
420 419
                         'begin_template_file'      => null,
421 420
                         'input_template_file'      => null,
422 421
                         'subsection_template_file' => null,
@@ -438,7 +437,7 @@  discard block
 block discarded – undo
438 437
     {
439 438
         return new EE_Form_Section_HTML(
440 439
             EEH_Template::locate_template(
441
-                SPCO_REG_STEPS_PATH . $this->_slug . DS . '_auto_copy_attendee_info.template.php',
440
+                SPCO_REG_STEPS_PATH.$this->_slug.DS.'_auto_copy_attendee_info.template.php',
442 441
                 apply_filters(
443 442
                     'FHEE__EE_SPCO_Reg_Step_Attendee_Information__auto_copy_attendee_info__template_args',
444 443
                     array()
@@ -468,17 +467,17 @@  discard block
 block discarded – undo
468 467
             if ($registration instanceof EE_Registration && ! $registration->is_primary_registrant()) {
469 468
                 // if this is a new ticket OR if this is the very first additional attendee after the primary attendee
470 469
                 if ($registration->ticket()->ID() !== $prev_ticket) {
471
-                    $item_name                                                                                         = $registration->ticket()->name();
472
-                    $item_name                                                                                         .= $registration->ticket()->description() !== ''
473
-                        ? ' - ' . $registration->ticket()->description()
470
+                    $item_name = $registration->ticket()->name();
471
+                    $item_name .= $registration->ticket()->description() !== ''
472
+                        ? ' - '.$registration->ticket()->description()
474 473
                         : '';
475
-                    $copy_attendee_info_inputs['spco_copy_attendee_chk[ticket-' . $registration->ticket()->ID() . ']'] = new EE_Form_Section_HTML(
476
-                        '<h6 class="spco-copy-attendee-event-hdr">' . $item_name . '</h6>'
474
+                    $copy_attendee_info_inputs['spco_copy_attendee_chk[ticket-'.$registration->ticket()->ID().']'] = new EE_Form_Section_HTML(
475
+                        '<h6 class="spco-copy-attendee-event-hdr">'.$item_name.'</h6>'
477 476
                     );
478 477
                     $prev_ticket                                                                                       = $registration->ticket()->ID();
479 478
                 }
480 479
 
481
-                $copy_attendee_info_inputs['spco_copy_attendee_chk[' . $registration->ID() . ']'] = new
480
+                $copy_attendee_info_inputs['spco_copy_attendee_chk['.$registration->ID().']'] = new
482 481
                 EE_Checkbox_Multi_Input(
483 482
                     array(
484 483
                         $registration->ID() => sprintf(
@@ -487,7 +486,7 @@  discard block
 block discarded – undo
487 486
                         ),
488 487
                     ),
489 488
                     array(
490
-                        'html_id'                 => 'spco-copy-attendee-chk-' . $registration->reg_url_link(),
489
+                        'html_id'                 => 'spco-copy-attendee-chk-'.$registration->reg_url_link(),
491 490
                         'html_class'              => 'spco-copy-attendee-chk ee-do-not-validate',
492 491
                         'display_html_label_text' => false,
493 492
                     )
@@ -533,7 +532,7 @@  discard block
 block discarded – undo
533 532
             $registration,
534 533
             $question->system_ID()
535 534
         );
536
-        $answer       = $answer_value === null
535
+        $answer = $answer_value === null
537 536
             ? EEM_Answer::instance()->get_one(
538 537
                 array(array('QST_ID' => $question->ID(), 'REG_ID' => $registration->ID()))
539 538
             )
@@ -550,14 +549,14 @@  discard block
 block discarded – undo
550 549
         }
551 550
         // verify instance
552 551
         if ($answer instanceof EE_Answer) {
553
-            if (! empty($answer_value)) {
552
+            if ( ! empty($answer_value)) {
554 553
                 $answer->set('ANS_value', $answer_value);
555 554
             }
556 555
             $answer->cache('Question', $question);
557 556
             //remember system ID had a bug where sometimes it could be null
558 557
             $answer_cache_id = $question->is_system_question()
559
-                ? $question->system_ID() . '-' . $registration->reg_url_link()
560
-                : $question->ID() . '-' . $registration->reg_url_link();
558
+                ? $question->system_ID().'-'.$registration->reg_url_link()
559
+                : $question->ID().'-'.$registration->reg_url_link();
561 560
             $registration->cache('Answer', $answer, $answer_cache_id);
562 561
         }
563 562
         return $this->_generate_question_input($registration, $question, $answer);
@@ -588,18 +587,18 @@  discard block
 block discarded – undo
588 587
             10,
589 588
             4
590 589
         );
591
-        $input_constructor_args                  = array(
592
-            'html_name'        => 'ee_reg_qstn[' . $registration->ID() . '][' . $identifier . ']',
593
-            'html_id'          => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
594
-            'html_class'       => 'ee-reg-qstn ee-reg-qstn-' . $identifier,
595
-            'html_label_id'    => 'ee_reg_qstn-' . $registration->ID() . '-' . $identifier,
590
+        $input_constructor_args = array(
591
+            'html_name'        => 'ee_reg_qstn['.$registration->ID().']['.$identifier.']',
592
+            'html_id'          => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
593
+            'html_class'       => 'ee-reg-qstn ee-reg-qstn-'.$identifier,
594
+            'html_label_id'    => 'ee_reg_qstn-'.$registration->ID().'-'.$identifier,
596 595
             'html_label_class' => 'ee-reg-qstn',
597 596
         );
598 597
         $input_constructor_args['html_label_id'] .= '-lbl';
599 598
         if ($answer instanceof EE_Answer && $answer->ID()) {
600
-            $input_constructor_args['html_name']     .= '[' . $answer->ID() . ']';
601
-            $input_constructor_args['html_id']       .= '-' . $answer->ID();
602
-            $input_constructor_args['html_label_id'] .= '-' . $answer->ID();
599
+            $input_constructor_args['html_name']     .= '['.$answer->ID().']';
600
+            $input_constructor_args['html_id']       .= '-'.$answer->ID();
601
+            $input_constructor_args['html_label_id'] .= '-'.$answer->ID();
603 602
         }
604 603
         $form_input = $question->generate_form_input(
605 604
             $registration,
@@ -638,7 +637,7 @@  discard block
 block discarded – undo
638 637
         $countries = $this->checkout->action === 'process_reg_step'
639 638
             ? EEM_Country::instance()->get_all_countries()
640 639
             : EEM_Country::instance()->get_all_active_countries();
641
-        if (! empty($countries)) {
640
+        if ( ! empty($countries)) {
642 641
             foreach ($countries as $country) {
643 642
                 if ($country instanceof EE_Country) {
644 643
                     $country_options[$country->ID()] = $country->name();
@@ -684,7 +683,7 @@  discard block
 block discarded – undo
684 683
         $states        = $this->checkout->action === 'process_reg_step'
685 684
             ? EEM_State::instance()->get_all_states()
686 685
             : EEM_State::instance()->get_all_active_states();
687
-        if (! empty($states)) {
686
+        if ( ! empty($states)) {
688 687
             foreach ($states as $state) {
689 688
                 if ($state instanceof EE_State) {
690 689
                     $state_options[$state->country()->name()][$state->ID()] = $state->name();
@@ -731,7 +730,7 @@  discard block
 block discarded – undo
731 730
             );
732 731
             return false;
733 732
         }
734
-        if (! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg) {
733
+        if ( ! $this->checkout->transaction instanceof EE_Transaction || ! $this->checkout->continue_reg) {
735 734
             EE_Error::add_error(
736 735
                 __('A valid transaction could not be initiated for processing your registrations.', 'event_espresso'),
737 736
                 __FILE__,
@@ -759,7 +758,7 @@  discard block
 block discarded – undo
759 758
         if ($registrations_processed === false) {
760 759
             // but return immediately if the previous step exited early due to errors
761 760
             return false;
762
-        } else if (! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count) {
761
+        } else if ( ! $this->checkout->revisit && $registrations_processed !== $this->checkout->total_ticket_count) {
763 762
             // generate a correctly translated string for all possible singular/plural combinations
764 763
             if ($this->checkout->total_ticket_count === 1 && $registrations_processed !== 1) {
765 764
                 $error_msg = sprintf(
@@ -834,7 +833,7 @@  discard block
 block discarded – undo
834 833
         // grab the saved registrations from the transaction
835 834
         foreach ($registrations as $registration) {
836 835
             // verify EE_Registration object
837
-            if (! $registration instanceof EE_Registration) {
836
+            if ( ! $registration instanceof EE_Registration) {
838 837
                 EE_Error::add_error(
839 838
                     __(
840 839
                         'An invalid Registration object was discovered when attempting to process your registration information.',
@@ -849,12 +848,12 @@  discard block
 block discarded – undo
849 848
             /** @var string $reg_url_link */
850 849
             $reg_url_link = $registration->reg_url_link();
851 850
             // reg_url_link exists ?
852
-            if (! empty($reg_url_link)) {
851
+            if ( ! empty($reg_url_link)) {
853 852
                 // should this registration be processed during this visit ?
854 853
                 if ($this->checkout->visit_allows_processing_of_this_registration($registration)) {
855 854
                     // if NOT revisiting, then let's save the registration now,
856 855
                     // so that we have a REG_ID to use when generating other objects
857
-                    if (! $this->checkout->revisit) {
856
+                    if ( ! $this->checkout->revisit) {
858 857
                         $registration->save();
859 858
                     }
860 859
                     /**
@@ -889,7 +888,7 @@  discard block
 block discarded – undo
889 888
                             ? true
890 889
                             : false;
891 890
                         // filter form input data for this registration
892
-                        $valid_data[$reg_url_link] = (array)apply_filters(
891
+                        $valid_data[$reg_url_link] = (array) apply_filters(
893 892
                             'FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
894 893
                             $valid_data[$reg_url_link]
895 894
                         );
@@ -902,7 +901,7 @@  discard block
 block discarded – undo
902 901
                         }
903 902
                         // now loop through our array of valid post data && process attendee reg forms
904 903
                         foreach ($valid_data[$reg_url_link] as $form_section => $form_inputs) {
905
-                            if (! in_array($form_section, $non_input_form_sections)) {
904
+                            if ( ! in_array($form_section, $non_input_form_sections)) {
906 905
                                 foreach ($form_inputs as $form_input => $input_value) {
907 906
                                     // \EEH_Debug_Tools::printr( $input_value, $form_input, __FILE__, __LINE__ );
908 907
                                     // check for critical inputs
@@ -987,7 +986,7 @@  discard block
 block discarded – undo
987 986
                     // add relation to registration, set attendee ID, and cache attendee
988 987
                     $this->_associate_attendee_with_registration($registration, $attendee);
989 988
                     // \EEH_Debug_Tools::printr( $registration, '$registration', __FILE__, __LINE__ );
990
-                    if (! $registration->attendee() instanceof EE_Attendee) {
989
+                    if ( ! $registration->attendee() instanceof EE_Attendee) {
991 990
                         EE_Error::add_error(sprintf(__('Registration %s has an invalid or missing Attendee object.',
992 991
                             'event_espresso'), $reg_url_link), __FILE__, __FUNCTION__, __LINE__);
993 992
                         return false;
@@ -1051,14 +1050,14 @@  discard block
 block discarded – undo
1051 1050
          * @see https://events.codebasehq.com/projects/event-espresso/tickets/10477
1052 1051
          */
1053 1052
         $answer_cache_id = $this->checkout->reg_url_link
1054
-            ? $form_input . '-' . $registration->reg_url_link()
1053
+            ? $form_input.'-'.$registration->reg_url_link()
1055 1054
             : $form_input;
1056 1055
         $answer_is_obj   = isset($this->_registration_answers[$answer_cache_id])
1057 1056
                            && $this->_registration_answers[$answer_cache_id] instanceof EE_Answer
1058 1057
             ? true
1059 1058
             : false;
1060 1059
         //rename form_inputs if they are EE_Attendee properties
1061
-        switch ((string)$form_input) {
1060
+        switch ((string) $form_input) {
1062 1061
 
1063 1062
             case 'state' :
1064 1063
             case 'STA_ID' :
@@ -1073,10 +1072,10 @@  discard block
 block discarded – undo
1073 1072
                 break;
1074 1073
 
1075 1074
             default :
1076
-                $ATT_input = 'ATT_' . $form_input;
1075
+                $ATT_input = 'ATT_'.$form_input;
1077 1076
                 //EEH_Debug_Tools::printr( $ATT_input, '$ATT_input', __FILE__, __LINE__ );
1078 1077
                 $attendee_property = EEM_Attendee::instance()->has_field($ATT_input) ? true : false;
1079
-                $form_input        = $attendee_property ? 'ATT_' . $form_input : $form_input;
1078
+                $form_input        = $attendee_property ? 'ATT_'.$form_input : $form_input;
1080 1079
         }
1081 1080
         // EEH_Debug_Tools::printr( $answer_cache_id, '$answer_cache_id', __FILE__, __LINE__ );
1082 1081
         // EEH_Debug_Tools::printr( $attendee_property, '$attendee_property', __FILE__, __LINE__ );
@@ -1121,7 +1120,7 @@  discard block
 block discarded – undo
1121 1120
     ) {
1122 1121
         if (empty($input_value)) {
1123 1122
             // if the form input isn't marked as being required, then just return
1124
-            if (! isset($this->_required_questions[$form_input]) || ! $this->_required_questions[$form_input]) {
1123
+            if ( ! isset($this->_required_questions[$form_input]) || ! $this->_required_questions[$form_input]) {
1125 1124
                 return true;
1126 1125
             }
1127 1126
             switch ($form_input) {
@@ -1207,7 +1206,7 @@  discard block
 block discarded – undo
1207 1206
             'FHEE__EE_SPCO_Reg_Step_Attendee_Information__merge_address_details_with_critical_attendee_details',
1208 1207
             false
1209 1208
         )) {
1210
-            $address_details           = array(
1209
+            $address_details = array(
1211 1210
                 'ATT_address',
1212 1211
                 'ATT_address2',
1213 1212
                 'ATT_city',
@@ -1219,7 +1218,7 @@  discard block
 block discarded – undo
1219 1218
             $critical_attendee_details = array_merge($critical_attendee_details, $address_details);
1220 1219
         }
1221 1220
         foreach ($critical_attendee_details as $critical_attendee_detail) {
1222
-            if (! isset($attendee_data[$critical_attendee_detail])
1221
+            if ( ! isset($attendee_data[$critical_attendee_detail])
1223 1222
                 || empty($attendee_data[$critical_attendee_detail])
1224 1223
             ) {
1225 1224
                 $attendee_data[$critical_attendee_detail] = $this->checkout->primary_attendee_obj->get(
Please login to merge, or discard this patch.
reg_steps/payment_options/EE_SPCO_Reg_Step_Payment_Options.class.php 3 patches
Doc Comments   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 
143 143
 
144 144
     /**
145
-     * @return null
145
+     * @return EE_Line_Item_Display
146 146
      */
147 147
     public function line_item_display()
148 148
     {
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
 
152 152
 
153 153
     /**
154
-     * @param null $line_item_display
154
+     * @param EE_Line_Item_Display $line_item_display
155 155
      */
156 156
     public function set_line_item_display($line_item_display)
157 157
     {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
      *    _apply_registration_payments_to_amount_owing
850 850
      *
851 851
      * @access protected
852
-     * @param array $registrations
852
+     * @param EE_Base_Class[] $registrations
853 853
      */
854 854
     protected function _apply_registration_payments_to_amount_owing(array $registrations)
855 855
     {
@@ -1122,7 +1122,7 @@  discard block
 block discarded – undo
1122 1122
      * get_billing_form_html_for_payment_method
1123 1123
      *
1124 1124
      * @access public
1125
-     * @return string
1125
+     * @return boolean
1126 1126
      * @throws \EE_Error
1127 1127
      */
1128 1128
     public function get_billing_form_html_for_payment_method()
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
      *
1187 1187
      * @access private
1188 1188
      * @param EE_Payment_Method $payment_method
1189
-     * @return \EE_Billing_Info_Form|\EE_Form_Section_HTML
1189
+     * @return EE_Billing_Info_Form
1190 1190
      * @throws \EE_Error
1191 1191
      */
1192 1192
     private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
@@ -1290,7 +1290,7 @@  discard block
 block discarded – undo
1290 1290
      * switch_payment_method
1291 1291
      *
1292 1292
      * @access public
1293
-     * @return string
1293
+     * @return boolean
1294 1294
      * @throws \EE_Error
1295 1295
      */
1296 1296
     public function switch_payment_method()
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
     /**
1546 1546
      * process_reg_step
1547 1547
      *
1548
-     * @return boolean
1548
+     * @return null|boolean
1549 1549
      * @throws \EE_Error
1550 1550
      */
1551 1551
     public function process_reg_step()
@@ -1671,7 +1671,7 @@  discard block
 block discarded – undo
1671 1671
      *    update_reg_step
1672 1672
      *    this is the final step after a user  revisits the site to retry a payment
1673 1673
      *
1674
-     * @return boolean
1674
+     * @return null|boolean
1675 1675
      * @throws \EE_Error
1676 1676
      */
1677 1677
     public function update_reg_step()
@@ -2084,7 +2084,7 @@  discard block
 block discarded – undo
2084 2084
      *
2085 2085
      * @access    private
2086 2086
      * @type    EE_Payment_Method $payment_method
2087
-     * @return    mixed    EE_Payment | boolean
2087
+     * @return    EE_Payment|null    EE_Payment | boolean
2088 2088
      * @throws \EE_Error
2089 2089
      */
2090 2090
     private function _attempt_payment(EE_Payment_Method $payment_method)
@@ -2215,7 +2215,7 @@  discard block
 block discarded – undo
2215 2215
      * _post_payment_processing
2216 2216
      *
2217 2217
      * @access private
2218
-     * @param EE_Payment|bool $payment
2218
+     * @param EE_Payment $payment
2219 2219
      * @return bool
2220 2220
      * @throws \EE_Error
2221 2221
      */
@@ -2406,7 +2406,7 @@  discard block
 block discarded – undo
2406 2406
      *        or present the payment options again
2407 2407
      *
2408 2408
      * @access private
2409
-     * @return EE_Payment | FALSE
2409
+     * @return boolean | FALSE
2410 2410
      * @throws \EE_Error
2411 2411
      */
2412 2412
     public function process_gateway_response()
@@ -2538,8 +2538,8 @@  discard block
 block discarded – undo
2538 2538
      * _redirect_wayward_request
2539 2539
      *
2540 2540
      * @access private
2541
-     * @param \EE_Registration|null $primary_registrant
2542
-     * @return bool
2541
+     * @param EE_Registration $primary_registrant
2542
+     * @return false|null
2543 2543
      * @throws \EE_Error
2544 2544
      */
2545 2545
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
Please login to merge, or discard this patch.
Indentation   +2711 added lines, -2711 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -15,2716 +15,2716 @@  discard block
 block discarded – undo
15 15
 class EE_SPCO_Reg_Step_Payment_Options extends EE_SPCO_Reg_Step
16 16
 {
17 17
 
18
-    /**
19
-     * @access protected
20
-     * @var EE_Line_Item_Display $Line_Item_Display
21
-     */
22
-    protected $line_item_display;
23
-
24
-    /**
25
-     * @access protected
26
-     * @var boolean $handle_IPN_in_this_request
27
-     */
28
-    protected $handle_IPN_in_this_request = false;
29
-
30
-
31
-    /**
32
-     *    set_hooks - for hooking into EE Core, other modules, etc
33
-     *
34
-     * @access    public
35
-     * @return    void
36
-     */
37
-    public static function set_hooks()
38
-    {
39
-        add_filter(
40
-            'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
-            array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
-        );
43
-        add_action(
44
-            'wp_ajax_switch_spco_billing_form',
45
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
-        );
47
-        add_action(
48
-            'wp_ajax_nopriv_switch_spco_billing_form',
49
-            array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
-        );
51
-        add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
-        add_action(
53
-            'wp_ajax_nopriv_save_payer_details',
54
-            array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
-        );
56
-        add_action(
57
-            'wp_ajax_get_transaction_details_for_gateways',
58
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
-        );
60
-        add_action(
61
-            'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
-            array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
-        );
64
-        add_filter(
65
-            'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
-            array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
-            10,
68
-            1
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     *    ajax switch_spco_billing_form
75
-     *
76
-     * @throws \EE_Error
77
-     */
78
-    public static function switch_spco_billing_form()
79
-    {
80
-        EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
-    }
82
-
83
-
84
-    /**
85
-     *    ajax save_payer_details
86
-     *
87
-     * @throws \EE_Error
88
-     */
89
-    public static function save_payer_details()
90
-    {
91
-        EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
-    }
93
-
94
-
95
-    /**
96
-     *    ajax get_transaction_details
97
-     *
98
-     * @throws \EE_Error
99
-     */
100
-    public static function get_transaction_details()
101
-    {
102
-        EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
-    }
104
-
105
-
106
-    /**
107
-     * bypass_recaptcha_for_load_payment_method
108
-     *
109
-     * @access public
110
-     * @return array
111
-     */
112
-    public static function bypass_recaptcha_for_load_payment_method()
113
-    {
114
-        return array(
115
-            'EESID'  => EE_Registry::instance()->SSN->id(),
116
-            'step'   => 'payment_options',
117
-            'action' => 'spco_billing_form',
118
-        );
119
-    }
120
-
121
-
122
-    /**
123
-     *    class constructor
124
-     *
125
-     * @access    public
126
-     * @param    EE_Checkout $checkout
127
-     */
128
-    public function __construct(EE_Checkout $checkout)
129
-    {
130
-        $this->_slug     = 'payment_options';
131
-        $this->_name     = __('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
-        $this->checkout  = $checkout;
134
-        $this->_reset_success_message();
135
-        $this->set_instructions(
136
-            __(
137
-                'Please select a method of payment and provide any necessary billing information before proceeding.',
138
-                'event_espresso'
139
-            )
140
-        );
141
-    }
142
-
143
-
144
-    /**
145
-     * @return null
146
-     */
147
-    public function line_item_display()
148
-    {
149
-        return $this->line_item_display;
150
-    }
151
-
152
-
153
-    /**
154
-     * @param null $line_item_display
155
-     */
156
-    public function set_line_item_display($line_item_display)
157
-    {
158
-        $this->line_item_display = $line_item_display;
159
-    }
160
-
161
-
162
-    /**
163
-     * @return boolean
164
-     */
165
-    public function handle_IPN_in_this_request()
166
-    {
167
-        return $this->handle_IPN_in_this_request;
168
-    }
169
-
170
-
171
-    /**
172
-     * @param boolean $handle_IPN_in_this_request
173
-     */
174
-    public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
-    {
176
-        $this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
-    }
178
-
179
-
180
-    /**
181
-     * translate_js_strings
182
-     *
183
-     * @return void
184
-     */
185
-    public function translate_js_strings()
186
-    {
187
-        EE_Registry::$i18n_js_strings['no_payment_method']      = __(
188
-            'Please select a method of payment in order to continue.',
189
-            'event_espresso'
190
-        );
191
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = __(
192
-            'A valid method of payment could not be determined. Please refresh the page and try again.',
193
-            'event_espresso'
194
-        );
195
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = __(
196
-            'Forwarding to Secure Payment Provider.',
197
-            'event_espresso'
198
-        );
199
-    }
200
-
201
-
202
-    /**
203
-     * enqueue_styles_and_scripts
204
-     *
205
-     * @return void
206
-     */
207
-    public function enqueue_styles_and_scripts()
208
-    {
209
-        $transaction = $this->checkout->transaction;
210
-        //if the transaction isn't set or nothing is owed on it, don't enqueue any JS
211
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
212
-            return;
213
-        }
214
-        foreach (
215
-            EEM_Payment_Method::instance()->get_all_for_transaction($transaction,
216
-                EEM_Payment_Method::scope_cart) as $payment_method
217
-        ) {
218
-            $type_obj = $payment_method->type_obj();
219
-            if ($type_obj instanceof EE_PMT_Base) {
220
-                $billing_form = $type_obj->generate_new_billing_form($transaction);
221
-                if ($billing_form instanceof EE_Form_Section_Proper) {
222
-                    $billing_form->enqueue_js();
223
-                }
224
-            }
225
-        }
226
-    }
227
-
228
-
229
-    /**
230
-     * initialize_reg_step
231
-     *
232
-     * @return boolean
233
-     * @throws \EE_Error
234
-     */
235
-    public function initialize_reg_step()
236
-    {
237
-        // TODO: if /when we implement donations, then this will need overriding
238
-        if (
239
-            // don't need payment options for:
240
-            // 	registrations made via the admin
241
-            // 	completed transactions
242
-            // 	overpaid transactions
243
-            // 	$ 0.00 transactions (no payment required)
244
-            ! $this->checkout->payment_required()
245
-            // but do NOT remove if current action being called belongs to this reg step
246
-            && ! is_callable(array($this, $this->checkout->action))
247
-            && ! $this->completed()
248
-        ) {
249
-            // and if so, then we no longer need the Payment Options step
250
-            if ($this->is_current_step()) {
251
-                $this->checkout->generate_reg_form = false;
252
-            }
253
-            $this->checkout->remove_reg_step($this->_slug);
254
-            // DEBUG LOG
255
-            //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
256
-            return false;
257
-        }
258
-        // load EEM_Payment_Method
259
-        EE_Registry::instance()->load_model('Payment_Method');
260
-        // get all active payment methods
261
-        $this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
262
-            $this->checkout->transaction,
263
-            EEM_Payment_Method::scope_cart
264
-        );
265
-        return true;
266
-    }
267
-
268
-
269
-    /**
270
-     * @return \EE_Form_Section_Proper
271
-     * @throws \EE_Error
272
-     */
273
-    public function generate_reg_form()
274
-    {
275
-        // reset in case someone changes their mind
276
-        $this->_reset_selected_method_of_payment();
277
-        // set some defaults
278
-        $this->checkout->selected_method_of_payment = 'payments_closed';
279
-        $registrations_requiring_payment            = array();
280
-        $registrations_for_free_events              = array();
281
-        $registrations_requiring_pre_approval       = array();
282
-        $sold_out_events                            = array();
283
-        $insufficient_spaces_available              = array();
284
-        $no_payment_required                        = true;
285
-        // loop thru registrations to gather info
286
-        $registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
287
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
288
-            $registrations,
289
-            $this->checkout->revisit
290
-        );
291
-        foreach ($registrations as $REG_ID => $registration) {
292
-            /** @var $registration EE_Registration */
293
-            // has this registration lost it's space ?
294
-            if (isset($ejected_registrations[$REG_ID])) {
295
-                $insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
296
-                continue;
297
-            }
298
-            // event requires admin approval
299
-            if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
300
-                // add event to list of events with pre-approval reg status
301
-                $registrations_requiring_pre_approval[$REG_ID] = $registration;
302
-                do_action(
303
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
304
-                    $registration->event(),
305
-                    $this
306
-                );
307
-                continue;
308
-            }
309
-            if (
310
-                // returning registrant
311
-                $this->checkout->revisit
312
-                // anything other than Approved
313
-                && $registration->status_ID() !== EEM_Registration::status_id_approved
314
-                && (
315
-                    $registration->event()->is_sold_out()
316
-                    || $registration->event()->is_sold_out(true)
317
-                )
318
-            ) {
319
-                // add event to list of events that are sold out
320
-                $sold_out_events[$registration->event()->ID()] = $registration->event();
321
-                do_action(
322
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
323
-                    $registration->event(),
324
-                    $this
325
-                );
326
-                continue;
327
-            }
328
-            // are they allowed to pay now and is there monies owing?
329
-            if ($registration->owes_monies_and_can_pay()) {
330
-                $registrations_requiring_payment[$REG_ID] = $registration;
331
-                do_action(
332
-                    'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
333
-                    $registration->event(),
334
-                    $this
335
-                );
336
-            } else if (
337
-                ! $this->checkout->revisit
338
-                && $registration->status_ID() !== EEM_Registration::status_id_not_approved
339
-                && $registration->ticket()->is_free()
340
-            ) {
341
-                $registrations_for_free_events[$registration->event()->ID()] = $registration;
342
-            }
343
-        }
344
-        $subsections = array();
345
-        // now decide which template to load
346
-        if (! empty($sold_out_events)) {
347
-            $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
348
-        }
349
-        if (! empty($insufficient_spaces_available)) {
350
-            $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
351
-                $insufficient_spaces_available
352
-            );
353
-        }
354
-        if (! empty($registrations_requiring_pre_approval)) {
355
-            $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
356
-                $registrations_requiring_pre_approval
357
-            );
358
-        }
359
-        if (! empty($registrations_for_free_events)) {
360
-            $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
361
-        }
362
-        if (! empty($registrations_requiring_payment)) {
363
-            if ($this->checkout->amount_owing > 0) {
364
-                // autoload Line_Item_Display classes
365
-                EEH_Autoloader::register_line_item_filter_autoloaders();
366
-                $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
367
-                    apply_filters(
368
-                        'FHEE__SPCO__EE_Line_Item_Filter_Collection',
369
-                        new EE_Line_Item_Filter_Collection()
370
-                    ),
371
-                    $this->checkout->cart->get_grand_total()
372
-                );
373
-                /** @var EE_Line_Item $filtered_line_item_tree */
374
-                $filtered_line_item_tree = $line_item_filter_processor->process();
375
-                EEH_Autoloader::register_line_item_display_autoloaders();
376
-                $this->set_line_item_display(new EE_Line_Item_Display('spco'));
377
-                $subsections['payment_options'] = $this->_display_payment_options(
378
-                    $this->line_item_display->display_line_item(
379
-                        $filtered_line_item_tree,
380
-                        array('registrations' => $registrations)
381
-                    )
382
-                );
383
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
384
-                $this->_apply_registration_payments_to_amount_owing($registrations);
385
-            }
386
-            $no_payment_required = false;
387
-        } else {
388
-            $this->_hide_reg_step_submit_button_if_revisit();
389
-        }
390
-        $this->_save_selected_method_of_payment();
391
-
392
-        $subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
393
-        $subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
394
-
395
-        return new EE_Form_Section_Proper(
396
-            array(
397
-                'name'            => $this->reg_form_name(),
398
-                'html_id'         => $this->reg_form_name(),
399
-                'subsections'     => $subsections,
400
-                'layout_strategy' => new EE_No_Layout(),
401
-            )
402
-        );
403
-    }
404
-
405
-
406
-    /**
407
-     * add line item filters required for this reg step
408
-     * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
409
-     *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
410
-     *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
411
-     *        payment options reg step, can apply these filters via the following: apply_filters(
412
-     *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
413
-     *        filter collection by passing that instead of instantiating a new collection
414
-     *
415
-     * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
416
-     * @return \EE_Line_Item_Filter_Collection
417
-     * @throws \EE_Error
418
-     */
419
-    public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
420
-    {
421
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
422
-            return $line_item_filter_collection;
423
-        }
424
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
425
-            return $line_item_filter_collection;
426
-        }
427
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
428
-            return $line_item_filter_collection;
429
-        }
430
-        $line_item_filter_collection->add(
431
-            new EE_Billable_Line_Item_Filter(
432
-                EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
433
-                    EE_Registry::instance()->SSN->checkout()->transaction->registrations(
434
-                        EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
435
-                    )
436
-                )
437
-            )
438
-        );
439
-        $line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
440
-        return $line_item_filter_collection;
441
-    }
442
-
443
-
444
-    /**
445
-     * remove_ejected_registrations
446
-     * if a registrant has lost their potential space at an event due to lack of payment,
447
-     * then this method removes them from the list of registrations being paid for during this request
448
-     *
449
-     * @param \EE_Registration[] $registrations
450
-     * @return \EE_Registration[]
451
-     * @throws \EE_Error
452
-     */
453
-    public static function remove_ejected_registrations(array $registrations)
454
-    {
455
-        $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
456
-            $registrations,
457
-            EE_Registry::instance()->SSN->checkout()->revisit
458
-        );
459
-        foreach ($registrations as $REG_ID => $registration) {
460
-            // has this registration lost it's space ?
461
-            if (isset($ejected_registrations[$REG_ID])) {
462
-                unset($registrations[$REG_ID]);
463
-                continue;
464
-            }
465
-        }
466
-        return $registrations;
467
-    }
468
-
469
-
470
-    /**
471
-     * find_registrations_that_lost_their_space
472
-     * If a registrant chooses an offline payment method like Invoice,
473
-     * then no space is reserved for them at the event until they fully pay fo that site
474
-     * (unless the event's default reg status is set to APPROVED)
475
-     * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
476
-     * then this method will determine which registrations have lost the ability to complete the reg process.
477
-     *
478
-     * @param \EE_Registration[] $registrations
479
-     * @param bool               $revisit
480
-     * @return array
481
-     * @throws \EE_Error
482
-     */
483
-    public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
484
-    {
485
-        // registrations per event
486
-        $event_reg_count = array();
487
-        // spaces left per event
488
-        $event_spaces_remaining = array();
489
-        // tickets left sorted by ID
490
-        $tickets_remaining = array();
491
-        // registrations that have lost their space
492
-        $ejected_registrations = array();
493
-        foreach ($registrations as $REG_ID => $registration) {
494
-            if (
495
-                $registration->status_ID() === EEM_Registration::status_id_approved
496
-                || apply_filters(
497
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
498
-                    false,
499
-                    $registration,
500
-                    $revisit
501
-                )
502
-            ) {
503
-                continue;
504
-            }
505
-            $EVT_ID = $registration->event_ID();
506
-            $ticket = $registration->ticket();
507
-            if (! isset($tickets_remaining[$ticket->ID()])) {
508
-                $tickets_remaining[$ticket->ID()] = $ticket->remaining();
509
-            }
510
-            if ($tickets_remaining[$ticket->ID()] > 0) {
511
-                if (! isset($event_reg_count[$EVT_ID])) {
512
-                    $event_reg_count[$EVT_ID] = 0;
513
-                }
514
-                $event_reg_count[$EVT_ID]++;
515
-                if (! isset($event_spaces_remaining[$EVT_ID])) {
516
-                    $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
517
-                }
518
-            }
519
-            if (
520
-                $revisit
521
-                && (
522
-                    $tickets_remaining[$ticket->ID()] === 0
523
-                    || $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
524
-                )
525
-            ) {
526
-                $ejected_registrations[$REG_ID] = $registration->event();
527
-                if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
528
-                    /** @type EE_Registration_Processor $registration_processor */
529
-                    $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
530
-                    // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
531
-                    $registration_processor->manually_update_registration_status(
532
-                        $registration,
533
-                        EEM_Registration::status_id_wait_list
534
-                    );
535
-                }
536
-
537
-            }
538
-        }
539
-        return $ejected_registrations;
540
-    }
541
-
542
-
543
-    /**
544
-     * _hide_reg_step_submit_button
545
-     * removes the html for the reg step submit button
546
-     * by replacing it with an empty string via filter callback
547
-     *
548
-     * @return void
549
-     */
550
-    protected function _adjust_registration_status_if_event_old_sold()
551
-    {
552
-    }
553
-
554
-
555
-    /**
556
-     * _hide_reg_step_submit_button
557
-     * removes the html for the reg step submit button
558
-     * by replacing it with an empty string via filter callback
559
-     *
560
-     * @return void
561
-     */
562
-    protected function _hide_reg_step_submit_button_if_revisit()
563
-    {
564
-        if ($this->checkout->revisit) {
565
-            add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
566
-        }
567
-    }
568
-
569
-
570
-    /**
571
-     * sold_out_events
572
-     * displays notices regarding events that have sold out since hte registrant first signed up
573
-     *
574
-     * @param \EE_Event[] $sold_out_events_array
575
-     * @return \EE_Form_Section_Proper
576
-     * @throws \EE_Error
577
-     */
578
-    private function _sold_out_events($sold_out_events_array = array())
579
-    {
580
-        // set some defaults
581
-        $this->checkout->selected_method_of_payment = 'events_sold_out';
582
-        $sold_out_events                            = '';
583
-        foreach ($sold_out_events_array as $sold_out_event) {
584
-            $sold_out_events .= EEH_HTML::li(
585
-                EEH_HTML::span('  ' . $sold_out_event->name(), '',
586
-                    'dashicons dashicons-marker ee-icon-size-16 pink-text')
587
-            );
588
-        }
589
-        return new EE_Form_Section_Proper(
590
-            array(
591
-                'layout_strategy' => new EE_Template_Layout(
592
-                    array(
593
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
594
-                                                  . $this->_slug
595
-                                                  . DS
596
-                                                  . 'sold_out_events.template.php',
597
-                        'template_args'        => apply_filters(
598
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
599
-                            array(
600
-                                'sold_out_events'     => $sold_out_events,
601
-                                'sold_out_events_msg' => apply_filters(
602
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
603
-                                    sprintf(
604
-                                        __('It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
605
-                                            'event_espresso'),
606
-                                        '<strong>',
607
-                                        '</strong>',
608
-                                        '<br />'
609
-                                    )
610
-                                ),
611
-                            )
612
-                        ),
613
-                    )
614
-                ),
615
-            )
616
-        );
617
-    }
618
-
619
-
620
-    /**
621
-     * _insufficient_spaces_available
622
-     * displays notices regarding events that do not have enough remaining spaces
623
-     * to satisfy the current number of registrations looking to pay
624
-     *
625
-     * @param \EE_Event[] $insufficient_spaces_events_array
626
-     * @return \EE_Form_Section_Proper
627
-     * @throws \EE_Error
628
-     */
629
-    private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
630
-    {
631
-        // set some defaults
632
-        $this->checkout->selected_method_of_payment = 'invoice';
633
-        $insufficient_space_events                  = '';
634
-        foreach ($insufficient_spaces_events_array as $event) {
635
-            if ($event instanceof EE_Event) {
636
-                $insufficient_space_events .= EEH_HTML::li(
637
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
638
-                );
639
-            }
640
-        }
641
-        return new EE_Form_Section_Proper(
642
-            array(
643
-                'subsections'     => array(
644
-                    'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
645
-                    'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
646
-                ),
647
-                'layout_strategy' => new EE_Template_Layout(
648
-                    array(
649
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
650
-                                                  . $this->_slug
651
-                                                  . DS
652
-                                                  . 'sold_out_events.template.php',
653
-                        'template_args'        => apply_filters(
654
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
655
-                            array(
656
-                                'sold_out_events'     => $insufficient_space_events,
657
-                                'sold_out_events_msg' => apply_filters(
658
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
659
-                                    __(
660
-                                        'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
661
-                                        'event_espresso'
662
-                                    )
663
-                                ),
664
-                            )
665
-                        ),
666
-                    )
667
-                ),
668
-            )
669
-        );
670
-    }
671
-
672
-
673
-    /**
674
-     * registrations_requiring_pre_approval
675
-     *
676
-     * @param array $registrations_requiring_pre_approval
677
-     * @return \EE_Form_Section_Proper
678
-     * @throws \EE_Error
679
-     */
680
-    private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
681
-    {
682
-        $events_requiring_pre_approval = '';
683
-        foreach ($registrations_requiring_pre_approval as $registration) {
684
-            if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
685
-                $events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
686
-                    EEH_HTML::span(
687
-                        '',
688
-                        '',
689
-                        'dashicons dashicons-marker ee-icon-size-16 orange-text'
690
-                    )
691
-                    . EEH_HTML::span($registration->event()->name(), '', 'orange-text')
692
-                );
693
-            }
694
-        }
695
-        return new EE_Form_Section_Proper(
696
-            array(
697
-                'layout_strategy' => new EE_Template_Layout(
698
-                    array(
699
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
700
-                                                  . $this->_slug
701
-                                                  . DS
702
-                                                  . 'events_requiring_pre_approval.template.php', // layout_template
703
-                        'template_args'        => apply_filters(
704
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
705
-                            array(
706
-                                'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
707
-                                'events_requiring_pre_approval_msg' => apply_filters(
708
-                                    'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
709
-                                    __(
710
-                                        'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
711
-                                        'event_espresso'
712
-                                    )
713
-                                ),
714
-                            )
715
-                        ),
716
-                    )
717
-                ),
718
-            )
719
-        );
720
-    }
721
-
722
-
723
-    /**
724
-     * _no_payment_required
725
-     *
726
-     * @param \EE_Event[] $registrations_for_free_events
727
-     * @return \EE_Form_Section_Proper
728
-     * @throws \EE_Error
729
-     */
730
-    private function _no_payment_required($registrations_for_free_events = array())
731
-    {
732
-        // set some defaults
733
-        $this->checkout->selected_method_of_payment = 'no_payment_required';
734
-        // generate no_payment_required form
735
-        return new EE_Form_Section_Proper(
736
-            array(
737
-                'layout_strategy' => new EE_Template_Layout(
738
-                    array(
739
-                        'layout_template_file' => SPCO_REG_STEPS_PATH
740
-                                                  . $this->_slug
741
-                                                  . DS
742
-                                                  . 'no_payment_required.template.php', // layout_template
743
-                        'template_args'        => apply_filters(
744
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
745
-                            array(
746
-                                'revisit'                       => $this->checkout->revisit,
747
-                                'registrations'                 => array(),
748
-                                'ticket_count'                  => array(),
749
-                                'registrations_for_free_events' => $registrations_for_free_events,
750
-                                'no_payment_required_msg'       => EEH_HTML::p(
751
-                                    __('This is a free event, so no billing will occur.', 'event_espresso')
752
-                                ),
753
-                            )
754
-                        ),
755
-                    )
756
-                ),
757
-            )
758
-        );
759
-    }
760
-
761
-
762
-    /**
763
-     * _display_payment_options
764
-     *
765
-     * @param string $transaction_details
766
-     * @return \EE_Form_Section_Proper
767
-     * @throws \EE_Error
768
-     */
769
-    private function _display_payment_options($transaction_details = '')
770
-    {
771
-        // has method_of_payment been set by no-js user?
772
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
773
-        // build payment options form
774
-        return apply_filters(
775
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
776
-            new EE_Form_Section_Proper(
777
-                array(
778
-                    'subsections'     => array(
779
-                        'before_payment_options' => apply_filters(
780
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
781
-                            new EE_Form_Section_Proper(
782
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
783
-                            )
784
-                        ),
785
-                        'payment_options'        => $this->_setup_payment_options(),
786
-                        'after_payment_options'  => apply_filters(
787
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
788
-                            new EE_Form_Section_Proper(
789
-                                array('layout_strategy' => new EE_Div_Per_Section_Layout())
790
-                            )
791
-                        ),
792
-                    ),
793
-                    'layout_strategy' => new EE_Template_Layout(
794
-                        array(
795
-                            'layout_template_file' => $this->_template,
796
-                            'template_args'        => apply_filters(
797
-                                'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
798
-                                array(
799
-                                    'reg_count'                 => $this->line_item_display->total_items(),
800
-                                    'transaction_details'       => $transaction_details,
801
-                                    'available_payment_methods' => array(),
802
-                                )
803
-                            ),
804
-                        )
805
-                    ),
806
-                )
807
-            )
808
-        );
809
-    }
810
-
811
-
812
-    /**
813
-     * _extra_hidden_inputs
814
-     *
815
-     * @param bool $no_payment_required
816
-     * @return \EE_Form_Section_Proper
817
-     * @throws \EE_Error
818
-     */
819
-    private function _extra_hidden_inputs($no_payment_required = true)
820
-    {
821
-        return new EE_Form_Section_Proper(
822
-            array(
823
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
824
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
825
-                'subsections'     => array(
826
-                    'spco_no_payment_required' => new EE_Hidden_Input(
827
-                        array(
828
-                            'normalization_strategy' => new EE_Boolean_Normalization(),
829
-                            'html_name'              => 'spco_no_payment_required',
830
-                            'html_id'                => 'spco-no-payment-required-payment_options',
831
-                            'default'                => $no_payment_required,
832
-                        )
833
-                    ),
834
-                    'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
835
-                        array(
836
-                            'normalization_strategy' => new EE_Int_Normalization(),
837
-                            'html_name'              => 'spco_transaction_id',
838
-                            'html_id'                => 'spco-transaction-id',
839
-                            'default'                => $this->checkout->transaction->ID(),
840
-                        )
841
-                    ),
842
-                ),
843
-            )
844
-        );
845
-    }
846
-
847
-
848
-    /**
849
-     *    _apply_registration_payments_to_amount_owing
850
-     *
851
-     * @access protected
852
-     * @param array $registrations
853
-     */
854
-    protected function _apply_registration_payments_to_amount_owing(array $registrations)
855
-    {
856
-        $payments = array();
857
-        foreach ($registrations as $registration) {
858
-            if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
859
-                $payments += $registration->registration_payments();
860
-            }
861
-        }
862
-        if (! empty($payments)) {
863
-            foreach ($payments as $payment) {
864
-                if ($payment instanceof EE_Registration_Payment) {
865
-                    $this->checkout->amount_owing -= $payment->amount();
866
-                }
867
-            }
868
-        }
869
-    }
870
-
871
-
872
-    /**
873
-     *    _reset_selected_method_of_payment
874
-     *
875
-     * @access    private
876
-     * @param    bool $force_reset
877
-     * @return    void
878
-     */
879
-    private function _reset_selected_method_of_payment($force_reset = false)
880
-    {
881
-        $reset_payment_method = $force_reset
882
-            ? true
883
-            : sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
884
-        if ($reset_payment_method) {
885
-            $this->checkout->selected_method_of_payment = null;
886
-            $this->checkout->payment_method             = null;
887
-            $this->checkout->billing_form               = null;
888
-            $this->_save_selected_method_of_payment();
889
-        }
890
-    }
891
-
892
-
893
-    /**
894
-     * _save_selected_method_of_payment
895
-     * stores the selected_method_of_payment in the session
896
-     * so that it's available for all subsequent requests including AJAX
897
-     *
898
-     * @access        private
899
-     * @param string $selected_method_of_payment
900
-     * @return  void
901
-     */
902
-    private function _save_selected_method_of_payment($selected_method_of_payment = '')
903
-    {
904
-        $selected_method_of_payment = ! empty($selected_method_of_payment)
905
-            ? $selected_method_of_payment
906
-            : $this->checkout->selected_method_of_payment;
907
-        EE_Registry::instance()->SSN->set_session_data(
908
-            array('selected_method_of_payment' => $selected_method_of_payment)
909
-        );
910
-    }
911
-
912
-
913
-    /**
914
-     * _setup_payment_options
915
-     *
916
-     * @return \EE_Form_Section_Proper
917
-     * @throws \EE_Error
918
-     */
919
-    public function _setup_payment_options()
920
-    {
921
-        // load payment method classes
922
-        $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
923
-        // switch up header depending on number of available payment methods
924
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
925
-            ? apply_filters(
926
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
927
-                __('Please Select Your Method of Payment', 'event_espresso')
928
-            )
929
-            : apply_filters(
930
-                'FHEE__registration_page_payment_options__method_of_payment_hdr',
931
-                __('Method of Payment', 'event_espresso')
932
-            );
933
-        $available_payment_methods = array(
934
-            // display the "Payment Method" header
935
-            'payment_method_header' => new EE_Form_Section_HTML(
936
-                EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
937
-            ),
938
-        );
939
-        // the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
940
-        $available_payment_method_options = array();
941
-        $default_payment_method_option    = array();
942
-        // additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
943
-        $payment_methods_billing_info = array(
944
-            new EE_Form_Section_HTML(
945
-                EEH_HTML::div('<br />', '', '', 'clear:both;')
946
-            ),
947
-        );
948
-        // loop through payment methods
949
-        foreach ($this->checkout->available_payment_methods as $payment_method) {
950
-            if ($payment_method instanceof EE_Payment_Method) {
951
-                $payment_method_button = EEH_HTML::img(
952
-                    $payment_method->button_url(),
953
-                    $payment_method->name(),
954
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
955
-                    'spco-payment-method-btn-img'
956
-                );
957
-                // check if any payment methods are set as default
958
-                // if payment method is already selected OR nothing is selected and this payment method should be open_by_default
959
-                if (
960
-                    ($this->checkout->selected_method_of_payment === $payment_method->slug())
961
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
962
-                ) {
963
-                    $this->checkout->selected_method_of_payment = $payment_method->slug();
964
-                    $this->_save_selected_method_of_payment();
965
-                    $default_payment_method_option[$payment_method->slug()] = $payment_method_button;
966
-                } else {
967
-                    $available_payment_method_options[$payment_method->slug()] = $payment_method_button;
968
-                }
969
-                $payment_methods_billing_info[$payment_method->slug()
970
-                                              . '-info'] = $this->_payment_method_billing_info(
971
-                    $payment_method
972
-                );
973
-            }
974
-        }
975
-        // prepend available_payment_method_options with default_payment_method_option so that it appears first in list of PMs
976
-        $available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
977
-        // now generate the actual form  inputs
978
-        $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
979
-            $available_payment_method_options
980
-        );
981
-        $available_payment_methods                              += $payment_methods_billing_info;
982
-        // build the available payment methods form
983
-        return new EE_Form_Section_Proper(
984
-            array(
985
-                'html_id'         => 'spco-available-methods-of-payment-dv',
986
-                'subsections'     => $available_payment_methods,
987
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
988
-            )
989
-        );
990
-    }
991
-
992
-
993
-    /**
994
-     * _get_available_payment_methods
995
-     *
996
-     * @return EE_Payment_Method[]
997
-     */
998
-    protected function _get_available_payment_methods()
999
-    {
1000
-        if (! empty($this->checkout->available_payment_methods)) {
1001
-            return $this->checkout->available_payment_methods;
1002
-        }
1003
-        $available_payment_methods = array();
1004
-        // load EEM_Payment_Method
1005
-        EE_Registry::instance()->load_model('Payment_Method');
1006
-        /** @type EEM_Payment_Method $EEM_Payment_Method */
1007
-        $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1008
-        // get all active payment methods
1009
-        $payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1010
-            $this->checkout->transaction,
1011
-            EEM_Payment_Method::scope_cart
1012
-        );
1013
-        foreach ($payment_methods as $payment_method) {
1014
-            if ($payment_method instanceof EE_Payment_Method) {
1015
-                $available_payment_methods[$payment_method->slug()] = $payment_method;
1016
-            }
1017
-        }
1018
-        return $available_payment_methods;
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     *    _available_payment_method_inputs
1024
-     *
1025
-     * @access    private
1026
-     * @param    array $available_payment_method_options
1027
-     * @return    \EE_Form_Section_Proper
1028
-     */
1029
-    private function _available_payment_method_inputs($available_payment_method_options = array())
1030
-    {
1031
-        // generate inputs
1032
-        return new EE_Form_Section_Proper(
1033
-            array(
1034
-                'html_id'         => 'ee-available-payment-method-inputs',
1035
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1036
-                'subsections'     => array(
1037
-                    '' => new EE_Radio_Button_Input (
1038
-                        $available_payment_method_options,
1039
-                        array(
1040
-                            'html_name'          => 'selected_method_of_payment',
1041
-                            'html_class'         => 'spco-payment-method',
1042
-                            'default'            => $this->checkout->selected_method_of_payment,
1043
-                            'label_size'         => 11,
1044
-                            'enforce_label_size' => true,
1045
-                        )
1046
-                    ),
1047
-                ),
1048
-            )
1049
-        );
1050
-    }
1051
-
1052
-
1053
-    /**
1054
-     *    _payment_method_billing_info
1055
-     *
1056
-     * @access    private
1057
-     * @param    EE_Payment_Method $payment_method
1058
-     * @return    \EE_Form_Section_Proper
1059
-     * @throws \EE_Error
1060
-     */
1061
-    private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1062
-    {
1063
-        $currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1064
-            ? true
1065
-            : false;
1066
-        // generate the billing form for payment method
1067
-        $billing_form                 = $currently_selected
1068
-            ? $this->_get_billing_form_for_payment_method($payment_method)
1069
-            : new EE_Form_Section_HTML();
1070
-        $this->checkout->billing_form = $currently_selected
1071
-            ? $billing_form
1072
-            : $this->checkout->billing_form;
1073
-        // it's all in the details
1074
-        $info_html = EEH_HTML::h3(
1075
-            __('Important information regarding your payment', 'event_espresso'),
1076
-            '',
1077
-            'spco-payment-method-hdr'
1078
-        );
1079
-        // add some info regarding the step, either from what's saved in the admin,
1080
-        // or a default string depending on whether the PM has a billing form or not
1081
-        if ($payment_method->description()) {
1082
-            $payment_method_info = $payment_method->description();
1083
-        } elseif ($billing_form instanceof EE_Billing_Info_Form) {
1084
-            $payment_method_info = sprintf(
1085
-                __(
1086
-                    'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1087
-                    'event_espresso'
1088
-                ),
1089
-                $this->submit_button_text()
1090
-            );
1091
-        } else {
1092
-            $payment_method_info = sprintf(
1093
-                __('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1094
-                $this->submit_button_text()
1095
-            );
1096
-        }
1097
-        $info_html .= EEH_HTML::p(
1098
-            apply_filters(
1099
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1100
-                $payment_method_info
1101
-            ),
1102
-            '',
1103
-            'spco-payment-method-desc ee-attention'
1104
-        );
1105
-        return new EE_Form_Section_Proper(
1106
-            array(
1107
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1108
-                'html_class'      => 'spco-payment-method-info-dv',
1109
-                // only display the selected or default PM
1110
-                'html_style'      => $currently_selected ? '' : 'display:none;',
1111
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1112
-                'subsections'     => array(
1113
-                    'info'         => new EE_Form_Section_HTML($info_html),
1114
-                    'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1115
-                ),
1116
-            )
1117
-        );
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * get_billing_form_html_for_payment_method
1123
-     *
1124
-     * @access public
1125
-     * @return string
1126
-     * @throws \EE_Error
1127
-     */
1128
-    public function get_billing_form_html_for_payment_method()
1129
-    {
1130
-        // how have they chosen to pay?
1131
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1132
-        $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1133
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1134
-            return false;
1135
-        }
1136
-        if (apply_filters(
1137
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1138
-            false
1139
-        )) {
1140
-            EE_Error::add_success(
1141
-                apply_filters(
1142
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1143
-                    sprintf(
1144
-                        __(
1145
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1146
-                            'event_espresso'
1147
-                        ),
1148
-                        $this->checkout->payment_method->name()
1149
-                    )
1150
-                )
1151
-            );
1152
-        }
1153
-        // now generate billing form for selected method of payment
1154
-        $payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1155
-        // fill form with attendee info if applicable
1156
-        if (
1157
-            $payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1158
-            && $this->checkout->transaction_has_primary_registrant()
1159
-        ) {
1160
-            $payment_method_billing_form->populate_from_attendee(
1161
-                $this->checkout->transaction->primary_registration()->attendee()
1162
-            );
1163
-        }
1164
-        // and debug content
1165
-        if (
1166
-            $payment_method_billing_form instanceof EE_Billing_Info_Form
1167
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1168
-        ) {
1169
-            $payment_method_billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1170
-                $payment_method_billing_form
1171
-            );
1172
-        }
1173
-        $billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1174
-            ? $payment_method_billing_form->get_html()
1175
-            : '';
1176
-        $this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1177
-        // localize validation rules for main form
1178
-        $this->checkout->current_step->reg_form->localize_validation_rules();
1179
-        $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1180
-        return true;
1181
-    }
1182
-
1183
-
1184
-    /**
1185
-     * _get_billing_form_for_payment_method
1186
-     *
1187
-     * @access private
1188
-     * @param EE_Payment_Method $payment_method
1189
-     * @return \EE_Billing_Info_Form|\EE_Form_Section_HTML
1190
-     * @throws \EE_Error
1191
-     */
1192
-    private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1193
-    {
1194
-        $billing_form = $payment_method->type_obj()->billing_form(
1195
-            $this->checkout->transaction,
1196
-            array('amount_owing' => $this->checkout->amount_owing)
1197
-        );
1198
-        if ($billing_form instanceof EE_Billing_Info_Form) {
1199
-            if (
1200
-                apply_filters(
1201
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1202
-                    false
1203
-                )
1204
-                && EE_Registry::instance()->REQ->is_set('payment_method')
1205
-            ) {
1206
-                EE_Error::add_success(
1207
-                    apply_filters(
1208
-                        'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1209
-                        sprintf(
1210
-                            __(
1211
-                                'You have selected "%s" as your method of payment. Please note the important payment information below.',
1212
-                                'event_espresso'
1213
-                            ),
1214
-                            $payment_method->name()
1215
-                        )
1216
-                    )
1217
-                );
1218
-            }
1219
-            return apply_filters(
1220
-                'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1221
-                $billing_form,
1222
-                $payment_method
1223
-            );
1224
-        }
1225
-        // no actual billing form, so return empty HTML form section
1226
-        return new EE_Form_Section_HTML();
1227
-    }
1228
-
1229
-
1230
-    /**
1231
-     * _get_selected_method_of_payment
1232
-     *
1233
-     * @access private
1234
-     * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1235
-     *                          is not found in the incoming request
1236
-     * @param string  $request_param
1237
-     * @return NULL|string
1238
-     * @throws \EE_Error
1239
-     */
1240
-    private function _get_selected_method_of_payment(
1241
-        $required = false,
1242
-        $request_param = 'selected_method_of_payment'
1243
-    ) {
1244
-        // is selected_method_of_payment set in the request ?
1245
-        $selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1246
-        if ($selected_method_of_payment) {
1247
-            // sanitize it
1248
-            $selected_method_of_payment = is_array($selected_method_of_payment)
1249
-                ? array_shift($selected_method_of_payment)
1250
-                : $selected_method_of_payment;
1251
-            $selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1252
-            // store it in the session so that it's available for all subsequent requests including AJAX
1253
-            $this->_save_selected_method_of_payment($selected_method_of_payment);
1254
-        } else {
1255
-            // or is is set in the session ?
1256
-            $selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1257
-                'selected_method_of_payment'
1258
-            );
1259
-        }
1260
-        // do ya really really gotta have it?
1261
-        if (empty($selected_method_of_payment) && $required) {
1262
-            EE_Error::add_error(
1263
-                sprintf(
1264
-                    __(
1265
-                        'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1266
-                        'event_espresso'
1267
-                    ),
1268
-                    '<br/>',
1269
-                    '<br/>',
1270
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1271
-                ),
1272
-                __FILE__,
1273
-                __FUNCTION__,
1274
-                __LINE__
1275
-            );
1276
-            return null;
1277
-        }
1278
-        return $selected_method_of_payment;
1279
-    }
1280
-
1281
-
1282
-
1283
-
1284
-
1285
-
1286
-    /********************************************************************************************************/
1287
-    /***********************************  SWITCH PAYMENT METHOD  ************************************/
1288
-    /********************************************************************************************************/
1289
-    /**
1290
-     * switch_payment_method
1291
-     *
1292
-     * @access public
1293
-     * @return string
1294
-     * @throws \EE_Error
1295
-     */
1296
-    public function switch_payment_method()
1297
-    {
1298
-        if (! $this->_verify_payment_method_is_set()) {
1299
-            return false;
1300
-        }
1301
-        if (apply_filters(
1302
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1303
-            false
1304
-        )) {
1305
-            EE_Error::add_success(
1306
-                apply_filters(
1307
-                    'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1308
-                    sprintf(
1309
-                        __(
1310
-                            'You have selected "%s" as your method of payment. Please note the important payment information below.',
1311
-                            'event_espresso'
1312
-                        ),
1313
-                        $this->checkout->payment_method->name()
1314
-                    )
1315
-                )
1316
-            );
1317
-        }
1318
-        // generate billing form for selected method of payment if it hasn't been done already
1319
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1320
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1321
-                $this->checkout->payment_method
1322
-            );
1323
-        }
1324
-        // fill form with attendee info if applicable
1325
-        if (
1326
-        apply_filters(
1327
-            'FHEE__populate_billing_form_fields_from_attendee',
1328
-            (
1329
-                $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1330
-                && $this->checkout->transaction_has_primary_registrant()
1331
-            ),
1332
-            $this->checkout->billing_form,
1333
-            $this->checkout->transaction
1334
-        )
1335
-        ) {
1336
-            $this->checkout->billing_form->populate_from_attendee(
1337
-                $this->checkout->transaction->primary_registration()->attendee()
1338
-            );
1339
-        }
1340
-        // and debug content
1341
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1342
-            && $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1343
-        ) {
1344
-            $this->checkout->billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1345
-                $this->checkout->billing_form
1346
-            );
1347
-        }
1348
-        // get html and validation rules for form
1349
-        if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1350
-            $this->checkout->json_response->set_return_data(
1351
-                array('payment_method_info' => $this->checkout->billing_form->get_html())
1352
-            );
1353
-            // localize validation rules for main form
1354
-            $this->checkout->billing_form->localize_validation_rules(true);
1355
-            $this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1356
-        } else {
1357
-            $this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1358
-        }
1359
-        //prevents advancement to next step
1360
-        $this->checkout->continue_reg = false;
1361
-        return true;
1362
-    }
1363
-
1364
-
1365
-    /**
1366
-     * _verify_payment_method_is_set
1367
-     *
1368
-     * @return boolean
1369
-     * @throws \EE_Error
1370
-     */
1371
-    protected function _verify_payment_method_is_set()
1372
-    {
1373
-        // generate billing form for selected method of payment if it hasn't been done already
1374
-        if (empty($this->checkout->selected_method_of_payment)) {
1375
-            // how have they chosen to pay?
1376
-            $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1377
-        } else {
1378
-            // choose your own adventure based on method_of_payment
1379
-            switch ($this->checkout->selected_method_of_payment) {
1380
-                case 'events_sold_out' :
1381
-                    EE_Error::add_attention(
1382
-                        apply_filters(
1383
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1384
-                            __('It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1385
-                                'event_espresso')
1386
-                        ),
1387
-                        __FILE__, __FUNCTION__, __LINE__
1388
-                    );
1389
-                    return false;
1390
-                    break;
1391
-                case 'payments_closed' :
1392
-                    EE_Error::add_attention(
1393
-                        apply_filters(
1394
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1395
-                            __('It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1396
-                                'event_espresso')
1397
-                        ),
1398
-                        __FILE__, __FUNCTION__, __LINE__
1399
-                    );
1400
-                    return false;
1401
-                    break;
1402
-                case 'no_payment_required' :
1403
-                    EE_Error::add_attention(
1404
-                        apply_filters(
1405
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1406
-                            __('It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1407
-                                'event_espresso')
1408
-                        ),
1409
-                        __FILE__, __FUNCTION__, __LINE__
1410
-                    );
1411
-                    return false;
1412
-                    break;
1413
-                default:
1414
-            }
1415
-        }
1416
-        // verify payment method
1417
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1418
-            // get payment method for selected method of payment
1419
-            $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1420
-        }
1421
-        return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1422
-    }
1423
-
1424
-
1425
-
1426
-    /********************************************************************************************************/
1427
-    /***************************************  SAVE PAYER DETAILS  ****************************************/
1428
-    /********************************************************************************************************/
1429
-    /**
1430
-     * save_payer_details_via_ajax
1431
-     *
1432
-     * @return void
1433
-     * @throws \EE_Error
1434
-     */
1435
-    public function save_payer_details_via_ajax()
1436
-    {
1437
-        if (! $this->_verify_payment_method_is_set()) {
1438
-            return;
1439
-        }
1440
-        // generate billing form for selected method of payment if it hasn't been done already
1441
-        if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1442
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1443
-                $this->checkout->payment_method
1444
-            );
1445
-        }
1446
-        // generate primary attendee from payer info if applicable
1447
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1448
-            $attendee = $this->_create_attendee_from_request_data();
1449
-            if ($attendee instanceof EE_Attendee) {
1450
-                foreach ($this->checkout->transaction->registrations() as $registration) {
1451
-                    if ($registration->is_primary_registrant()) {
1452
-                        $this->checkout->primary_attendee_obj = $attendee;
1453
-                        $registration->_add_relation_to($attendee, 'Attendee');
1454
-                        $registration->set_attendee_id($attendee->ID());
1455
-                        $registration->update_cache_after_object_save('Attendee', $attendee);
1456
-                    }
1457
-                }
1458
-            }
1459
-        }
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * create_attendee_from_request_data
1465
-     * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1466
-     *
1467
-     * @return \EE_Attendee
1468
-     * @throws \EE_Error
1469
-     */
1470
-    protected function _create_attendee_from_request_data()
1471
-    {
1472
-        // get State ID
1473
-        $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1474
-        if (! empty($STA_ID)) {
1475
-            // can we get state object from name ?
1476
-            EE_Registry::instance()->load_model('State');
1477
-            $state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1478
-            $STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1479
-        }
1480
-        // get Country ISO
1481
-        $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1482
-        if (! empty($CNT_ISO)) {
1483
-            // can we get country object from name ?
1484
-            EE_Registry::instance()->load_model('Country');
1485
-            $country = EEM_Country::instance()->get_col(
1486
-                array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1487
-                'CNT_ISO'
1488
-            );
1489
-            $CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1490
-        }
1491
-        // grab attendee data
1492
-        $attendee_data = array(
1493
-            'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1494
-            'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1495
-            'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1496
-            'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1497
-            'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1498
-            'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1499
-            'STA_ID'       => $STA_ID,
1500
-            'CNT_ISO'      => $CNT_ISO,
1501
-            'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1502
-            'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1503
-        );
1504
-        // validate the email address since it is the most important piece of info
1505
-        if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1506
-            EE_Error::add_error(
1507
-                __('An invalid email address was submitted.', 'event_espresso'),
1508
-                __FILE__,
1509
-                __FUNCTION__,
1510
-                __LINE__
1511
-            );
1512
-        }
1513
-        // does this attendee already exist in the db ? we're searching using a combination of first name, last name, AND email address
1514
-        if (! empty($attendee_data['ATT_fname'])
1515
-            && ! empty($attendee_data['ATT_lname'])
1516
-            && ! empty($attendee_data['ATT_email'])
1517
-        ) {
1518
-            $existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1519
-                array(
1520
-                    'ATT_fname' => $attendee_data['ATT_fname'],
1521
-                    'ATT_lname' => $attendee_data['ATT_lname'],
1522
-                    'ATT_email' => $attendee_data['ATT_email'],
1523
-                )
1524
-            );
1525
-            if ($existing_attendee instanceof EE_Attendee) {
1526
-                return $existing_attendee;
1527
-            }
1528
-        }
1529
-        // no existing attendee? kk let's create a new one
1530
-        // kinda lame, but we need a first and last name to create an attendee, so use the email address if those don't exist
1531
-        $attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1532
-            ? $attendee_data['ATT_fname']
1533
-            : $attendee_data['ATT_email'];
1534
-        $attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1535
-            ? $attendee_data['ATT_lname']
1536
-            : $attendee_data['ATT_email'];
1537
-        return EE_Attendee::new_instance($attendee_data);
1538
-    }
1539
-
1540
-
1541
-
1542
-    /********************************************************************************************************/
1543
-    /****************************************  PROCESS REG STEP  *****************************************/
1544
-    /********************************************************************************************************/
1545
-    /**
1546
-     * process_reg_step
1547
-     *
1548
-     * @return boolean
1549
-     * @throws \EE_Error
1550
-     */
1551
-    public function process_reg_step()
1552
-    {
1553
-        // how have they chosen to pay?
1554
-        $this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1555
-            ? 'no_payment_required'
1556
-            : $this->_get_selected_method_of_payment(true);
1557
-        // choose your own adventure based on method_of_payment
1558
-        switch ($this->checkout->selected_method_of_payment) {
1559
-
1560
-            case 'events_sold_out' :
1561
-                $this->checkout->redirect     = true;
1562
-                $this->checkout->redirect_url = $this->checkout->cancel_page_url;
1563
-                $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1564
-                // mark this reg step as completed
1565
-                $this->set_completed();
1566
-                return false;
1567
-                break;
1568
-
1569
-            case 'payments_closed' :
1570
-                if (apply_filters(
1571
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1572
-                    false
1573
-                )) {
1574
-                    EE_Error::add_success(
1575
-                        __('no payment required at this time.', 'event_espresso'),
1576
-                        __FILE__,
1577
-                        __FUNCTION__,
1578
-                        __LINE__
1579
-                    );
1580
-                }
1581
-                // mark this reg step as completed
1582
-                $this->set_completed();
1583
-                return true;
1584
-                break;
1585
-
1586
-            case 'no_payment_required' :
1587
-                if (apply_filters(
1588
-                    'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1589
-                    false
1590
-                )) {
1591
-                    EE_Error::add_success(
1592
-                        __('no payment required.', 'event_espresso'),
1593
-                        __FILE__,
1594
-                        __FUNCTION__,
1595
-                        __LINE__
1596
-                    );
1597
-                }
1598
-                // mark this reg step as completed
1599
-                $this->set_completed();
1600
-                return true;
1601
-                break;
1602
-
1603
-            default:
1604
-                $registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1605
-                    EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1606
-                );
1607
-                $ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1608
-                    $registrations,
1609
-                    EE_Registry::instance()->SSN->checkout()->revisit
1610
-                );
1611
-                // calculate difference between the two arrays
1612
-                $registrations = array_diff($registrations, $ejected_registrations);
1613
-                if (empty($registrations)) {
1614
-                    $this->_redirect_because_event_sold_out();
1615
-                    return false;
1616
-                }
1617
-                $payment_successful = $this->_process_payment();
1618
-                if ($payment_successful) {
1619
-                    $this->checkout->continue_reg = true;
1620
-                    $this->_maybe_set_completed($this->checkout->payment_method);
1621
-                } else {
1622
-                    $this->checkout->continue_reg = false;
1623
-                }
1624
-                return $payment_successful;
1625
-
1626
-        }
1627
-    }
1628
-
1629
-
1630
-    /**
1631
-     * _redirect_because_event_sold_out
1632
-     *
1633
-     * @access protected
1634
-     * @return void
1635
-     */
1636
-    protected function _redirect_because_event_sold_out()
1637
-    {
1638
-        $this->checkout->continue_reg = false;
1639
-        // set redirect URL
1640
-        $this->checkout->redirect_url = add_query_arg(
1641
-            array('e_reg_url_link' => $this->checkout->reg_url_link),
1642
-            $this->checkout->current_step->reg_step_url()
1643
-        );
1644
-        $this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1645
-    }
1646
-
1647
-
1648
-    /**
1649
-     * _maybe_set_completed
1650
-     *
1651
-     * @access protected
1652
-     * @param \EE_Payment_Method $payment_method
1653
-     * @return void
1654
-     * @throws \EE_Error
1655
-     */
1656
-    protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1657
-    {
1658
-        switch ($payment_method->type_obj()->payment_occurs()) {
1659
-            case EE_PMT_Base::offsite :
1660
-                break;
1661
-            case EE_PMT_Base::onsite :
1662
-            case EE_PMT_Base::offline :
1663
-                // mark this reg step as completed
1664
-                $this->set_completed();
1665
-                break;
1666
-        }
1667
-    }
1668
-
1669
-
1670
-    /**
1671
-     *    update_reg_step
1672
-     *    this is the final step after a user  revisits the site to retry a payment
1673
-     *
1674
-     * @return boolean
1675
-     * @throws \EE_Error
1676
-     */
1677
-    public function update_reg_step()
1678
-    {
1679
-        $success = true;
1680
-        // if payment required
1681
-        if ($this->checkout->transaction->total() > 0) {
1682
-            do_action(
1683
-                'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1684
-                $this->checkout->transaction
1685
-            );
1686
-            // attempt payment via payment method
1687
-            $success = $this->process_reg_step();
1688
-        }
1689
-        if ($success && ! $this->checkout->redirect) {
1690
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1691
-                $this->checkout->transaction->ID()
1692
-            );
1693
-            // set return URL
1694
-            $this->checkout->redirect_url = add_query_arg(
1695
-                array('e_reg_url_link' => $this->checkout->reg_url_link),
1696
-                $this->checkout->thank_you_page_url
1697
-            );
1698
-        }
1699
-        return $success;
1700
-    }
1701
-
1702
-
1703
-    /**
1704
-     *    _process_payment
1705
-     *
1706
-     * @access private
1707
-     * @return    bool
1708
-     * @throws \EE_Error
1709
-     */
1710
-    private function _process_payment()
1711
-    {
1712
-        // basically confirm that the event hasn't sold out since they hit the page
1713
-        if (! $this->_last_second_ticket_verifications()) {
1714
-            return false;
1715
-        }
1716
-        // ya gotta make a choice man
1717
-        if (empty($this->checkout->selected_method_of_payment)) {
1718
-            $this->checkout->json_response->set_plz_select_method_of_payment(
1719
-                __('Please select a method of payment before proceeding.', 'event_espresso')
1720
-            );
1721
-            return false;
1722
-        }
1723
-        // get EE_Payment_Method object
1724
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1725
-            return false;
1726
-        }
1727
-        // setup billing form
1728
-        if ($this->checkout->payment_method->is_on_site()) {
1729
-            $this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1730
-                $this->checkout->payment_method
1731
-            );
1732
-            // bad billing form ?
1733
-            if (! $this->_billing_form_is_valid()) {
1734
-                return false;
1735
-            }
1736
-        }
1737
-        // ensure primary registrant has been fully processed
1738
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1739
-            return false;
1740
-        }
1741
-        // if session is close to expiring (under 10 minutes by default)
1742
-        if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1743
-            // add some time to session expiration so that payment can be completed
1744
-            EE_Registry::instance()->SSN->extend_expiration();
1745
-        }
1746
-        /** @type EE_Transaction_Processor $transaction_processor */
1747
-        //$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1748
-        // in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations for events with a default reg status of Approved
1749
-        //$transaction_processor->toggle_registration_statuses_for_default_approved_events( $this->checkout->transaction, $this->checkout->reg_cache_where_params );
1750
-        // attempt payment
1751
-        $payment = $this->_attempt_payment($this->checkout->payment_method);
1752
-        // process results
1753
-        $payment = $this->_validate_payment($payment);
1754
-        $payment = $this->_post_payment_processing($payment);
1755
-        // verify payment
1756
-        if ($payment instanceof EE_Payment) {
1757
-            // store that for later
1758
-            $this->checkout->payment = $payment;
1759
-            // we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1760
-            $this->checkout->transaction->toggle_failed_transaction_status();
1761
-            $payment_status = $payment->status();
1762
-            if (
1763
-                $payment_status === EEM_Payment::status_id_approved
1764
-                || $payment_status === EEM_Payment::status_id_pending
1765
-            ) {
1766
-                return true;
1767
-            } else {
1768
-                return false;
1769
-            }
1770
-        } else if ($payment === true) {
1771
-            // please note that offline payment methods will NOT make a payment,
1772
-            // but instead just mark themselves as the PMD_ID on the transaction, and return true
1773
-            $this->checkout->payment = $payment;
1774
-            return true;
1775
-        }
1776
-        // where's my money?
1777
-        return false;
1778
-    }
1779
-
1780
-
1781
-    /**
1782
-     * _last_second_ticket_verifications
1783
-     *
1784
-     * @access public
1785
-     * @return bool
1786
-     */
1787
-    protected function _last_second_ticket_verifications()
1788
-    {
1789
-        // don't bother re-validating if not a return visit
1790
-        if (! $this->checkout->revisit) {
1791
-            return true;
1792
-        }
1793
-        $registrations = $this->checkout->transaction->registrations();
1794
-        if (empty($registrations)) {
1795
-            return false;
1796
-        }
1797
-        foreach ($registrations as $registration) {
1798
-            if ($registration instanceof EE_Registration) {
1799
-                $event = $registration->event_obj();
1800
-                if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1801
-                    EE_Error::add_error(
1802
-                        apply_filters(
1803
-                            'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1804
-                            sprintf(
1805
-                                __('It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1806
-                                    'event_espresso'),
1807
-                                $event->name()
1808
-                            )
1809
-                        ),
1810
-                        __FILE__,
1811
-                        __FUNCTION__,
1812
-                        __LINE__
1813
-                    );
1814
-                    return false;
1815
-                }
1816
-            }
1817
-        }
1818
-        return true;
1819
-    }
1820
-
1821
-
1822
-    /**
1823
-     * redirect_form
1824
-     *
1825
-     * @access public
1826
-     * @return bool
1827
-     * @throws \EE_Error
1828
-     */
1829
-    public function redirect_form()
1830
-    {
1831
-        $payment_method_billing_info = $this->_payment_method_billing_info(
1832
-            $this->_get_payment_method_for_selected_method_of_payment()
1833
-        );
1834
-        $html                        = $payment_method_billing_info->get_html();
1835
-        $html                        .= $this->checkout->redirect_form;
1836
-        EE_Registry::instance()->REQ->add_output($html);
1837
-        return true;
1838
-    }
1839
-
1840
-
1841
-    /**
1842
-     * _billing_form_is_valid
1843
-     *
1844
-     * @access private
1845
-     * @return bool
1846
-     * @throws \EE_Error
1847
-     */
1848
-    private function _billing_form_is_valid()
1849
-    {
1850
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1851
-            return true;
1852
-        }
1853
-        if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1854
-            if ($this->checkout->billing_form->was_submitted()) {
1855
-                $this->checkout->billing_form->receive_form_submission();
1856
-                if ($this->checkout->billing_form->is_valid()) {
1857
-                    return true;
1858
-                }
1859
-                $validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1860
-                $error_strings     = array();
1861
-                foreach ($validation_errors as $validation_error) {
1862
-                    if ($validation_error instanceof EE_Validation_Error) {
1863
-                        $form_section = $validation_error->get_form_section();
1864
-                        if ($form_section instanceof EE_Form_Input_Base) {
1865
-                            $label = $form_section->html_label_text();
1866
-                        } elseif ($form_section instanceof EE_Form_Section_Base) {
1867
-                            $label = $form_section->name();
1868
-                        } else {
1869
-                            $label = __('Validation Error', 'event_espresso');
1870
-                        }
1871
-                        $error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
1872
-                    }
1873
-                }
1874
-                EE_Error::add_error(
1875
-                    sprintf(
1876
-                        __(
1877
-                            'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
1878
-                            'event_espresso'
1879
-                        ),
1880
-                        '<br/>',
1881
-                        implode('<br/>', $error_strings)
1882
-                    ),
1883
-                    __FILE__,
1884
-                    __FUNCTION__,
1885
-                    __LINE__
1886
-                );
1887
-            } else {
1888
-                EE_Error::add_error(
1889
-                    __(
1890
-                        'The billing form was not submitted or something prevented it\'s submission.',
1891
-                        'event_espresso'
1892
-                    ),
1893
-                    __FILE__,
1894
-                    __FUNCTION__,
1895
-                    __LINE__
1896
-                );
1897
-            }
1898
-        } else {
1899
-            EE_Error::add_error(
1900
-                __('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
1901
-                __FILE__,
1902
-                __FUNCTION__,
1903
-                __LINE__
1904
-            );
1905
-        }
1906
-        return false;
1907
-    }
1908
-
1909
-
1910
-    /**
1911
-     * _setup_primary_registrant_prior_to_payment
1912
-     * ensures that the primary registrant has a valid attendee object created with the critical details populated
1913
-     * (first & last name & email) and that both the transaction object and primary registration object have been saved
1914
-     * plz note that any other registrations will NOT be saved at this point (because they may not have any details
1915
-     * yet)
1916
-     *
1917
-     * @access private
1918
-     * @return bool
1919
-     * @throws \EE_Error
1920
-     */
1921
-    private function _setup_primary_registrant_prior_to_payment()
1922
-    {
1923
-        // check if transaction has a primary registrant and that it has a related Attendee object
1924
-        // if not, then we need to at least gather some primary registrant data before attempting payment
1925
-        if (
1926
-            $this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1927
-            && ! $this->checkout->transaction_has_primary_registrant()
1928
-            && ! $this->_capture_primary_registration_data_from_billing_form()
1929
-        ) {
1930
-            return false;
1931
-        }
1932
-        // because saving an object clears it's cache, we need to do the chevy shuffle
1933
-        // grab the primary_registration object
1934
-        $primary_registration = $this->checkout->transaction->primary_registration();
1935
-        // at this point we'll consider a TXN to not have been failed
1936
-        $this->checkout->transaction->toggle_failed_transaction_status();
1937
-        // save the TXN ( which clears cached copy of primary_registration)
1938
-        $this->checkout->transaction->save();
1939
-        // grab TXN ID and save it to the primary_registration
1940
-        $primary_registration->set_transaction_id($this->checkout->transaction->ID());
1941
-        // save what we have so far
1942
-        $primary_registration->save();
1943
-        return true;
1944
-    }
1945
-
1946
-
1947
-    /**
1948
-     * _capture_primary_registration_data_from_billing_form
1949
-     *
1950
-     * @access private
1951
-     * @return bool
1952
-     * @throws \EE_Error
1953
-     */
1954
-    private function _capture_primary_registration_data_from_billing_form()
1955
-    {
1956
-        // convert billing form data into an attendee
1957
-        $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
1958
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
1959
-            EE_Error::add_error(
1960
-                sprintf(
1961
-                    __(
1962
-                        'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
1963
-                        'event_espresso'
1964
-                    ),
1965
-                    '<br/>',
1966
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1967
-                ),
1968
-                __FILE__,
1969
-                __FUNCTION__,
1970
-                __LINE__
1971
-            );
1972
-            return false;
1973
-        }
1974
-        $primary_registration = $this->checkout->transaction->primary_registration();
1975
-        if (! $primary_registration instanceof EE_Registration) {
1976
-            EE_Error::add_error(
1977
-                sprintf(
1978
-                    __(
1979
-                        'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
1980
-                        'event_espresso'
1981
-                    ),
1982
-                    '<br/>',
1983
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
1984
-                ),
1985
-                __FILE__,
1986
-                __FUNCTION__,
1987
-                __LINE__
1988
-            );
1989
-            return false;
1990
-        }
1991
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
1992
-              instanceof
1993
-              EE_Attendee
1994
-        ) {
1995
-            EE_Error::add_error(
1996
-                sprintf(
1997
-                    __(
1998
-                        'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
1999
-                        'event_espresso'
2000
-                    ),
2001
-                    '<br/>',
2002
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2003
-                ),
2004
-                __FILE__,
2005
-                __FUNCTION__,
2006
-                __LINE__
2007
-            );
2008
-            return false;
2009
-        }
2010
-        /** @type EE_Registration_Processor $registration_processor */
2011
-        $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2012
-        // at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2013
-        $registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2014
-        return true;
2015
-    }
2016
-
2017
-
2018
-    /**
2019
-     * _get_payment_method_for_selected_method_of_payment
2020
-     * retrieves a valid payment method
2021
-     *
2022
-     * @access public
2023
-     * @return \EE_Payment_Method
2024
-     * @throws \EE_Error
2025
-     */
2026
-    private function _get_payment_method_for_selected_method_of_payment()
2027
-    {
2028
-        if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2029
-            $this->_redirect_because_event_sold_out();
2030
-            return null;
2031
-        }
2032
-        // get EE_Payment_Method object
2033
-        if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2034
-            $payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2035
-        } else {
2036
-            // load EEM_Payment_Method
2037
-            EE_Registry::instance()->load_model('Payment_Method');
2038
-            /** @type EEM_Payment_Method $EEM_Payment_Method */
2039
-            $EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2040
-            $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2041
-        }
2042
-        // verify $payment_method
2043
-        if (! $payment_method instanceof EE_Payment_Method) {
2044
-            // not a payment
2045
-            EE_Error::add_error(
2046
-                sprintf(
2047
-                    __(
2048
-                        'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2049
-                        'event_espresso'
2050
-                    ),
2051
-                    '<br/>',
2052
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2053
-                ),
2054
-                __FILE__,
2055
-                __FUNCTION__,
2056
-                __LINE__
2057
-            );
2058
-            return null;
2059
-        }
2060
-        // and verify it has a valid Payment_Method Type object
2061
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2062
-            // not a payment
2063
-            EE_Error::add_error(
2064
-                sprintf(
2065
-                    __(
2066
-                        'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2067
-                        'event_espresso'
2068
-                    ),
2069
-                    '<br/>',
2070
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2071
-                ),
2072
-                __FILE__,
2073
-                __FUNCTION__,
2074
-                __LINE__
2075
-            );
2076
-            return null;
2077
-        }
2078
-        return $payment_method;
2079
-    }
2080
-
2081
-
2082
-    /**
2083
-     *    _attempt_payment
2084
-     *
2085
-     * @access    private
2086
-     * @type    EE_Payment_Method $payment_method
2087
-     * @return    mixed    EE_Payment | boolean
2088
-     * @throws \EE_Error
2089
-     */
2090
-    private function _attempt_payment(EE_Payment_Method $payment_method)
2091
-    {
2092
-        $payment = null;
2093
-        $this->checkout->transaction->save();
2094
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2095
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2096
-            return false;
2097
-        }
2098
-        try {
2099
-            $payment_processor->set_revisit($this->checkout->revisit);
2100
-            // generate payment object
2101
-            $payment = $payment_processor->process_payment(
2102
-                $payment_method,
2103
-                $this->checkout->transaction,
2104
-                $this->checkout->amount_owing,
2105
-                $this->checkout->billing_form,
2106
-                $this->_get_return_url($payment_method),
2107
-                'CART',
2108
-                $this->checkout->admin_request,
2109
-                true,
2110
-                $this->reg_step_url()
2111
-            );
2112
-        } catch (Exception $e) {
2113
-            $this->_handle_payment_processor_exception($e);
2114
-        }
2115
-        return $payment;
2116
-    }
2117
-
2118
-
2119
-    /**
2120
-     * _handle_payment_processor_exception
2121
-     *
2122
-     * @access protected
2123
-     * @param \Exception $e
2124
-     * @return void
2125
-     * @throws \EE_Error
2126
-     */
2127
-    protected function _handle_payment_processor_exception(Exception $e)
2128
-    {
2129
-        EE_Error::add_error(
2130
-            sprintf(
2131
-                __(
2132
-                    'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2133
-                    'event_espresso'
2134
-                ),
2135
-                '<br/>',
2136
-                EE_Registry::instance()->CFG->organization->get_pretty('email'),
2137
-                $e->getMessage(),
2138
-                $e->getFile(),
2139
-                $e->getLine()
2140
-            ),
2141
-            __FILE__,
2142
-            __FUNCTION__,
2143
-            __LINE__
2144
-        );
2145
-    }
2146
-
2147
-
2148
-    /**
2149
-     * _get_return_url
2150
-     *
2151
-     * @access protected
2152
-     * @param \EE_Payment_Method $payment_method
2153
-     * @return string
2154
-     * @throws \EE_Error
2155
-     */
2156
-    protected function _get_return_url(EE_Payment_Method $payment_method)
2157
-    {
2158
-        $return_url = '';
2159
-        switch ($payment_method->type_obj()->payment_occurs()) {
2160
-            case EE_PMT_Base::offsite :
2161
-                $return_url = add_query_arg(
2162
-                    array(
2163
-                        'action'                     => 'process_gateway_response',
2164
-                        'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2165
-                        'spco_txn'                   => $this->checkout->transaction->ID(),
2166
-                    ),
2167
-                    $this->reg_step_url()
2168
-                );
2169
-                break;
2170
-            case EE_PMT_Base::onsite :
2171
-            case EE_PMT_Base::offline :
2172
-                $return_url = $this->checkout->next_step->reg_step_url();
2173
-                break;
2174
-        }
2175
-        return $return_url;
2176
-    }
2177
-
2178
-
2179
-    /**
2180
-     * _validate_payment
2181
-     *
2182
-     * @access private
2183
-     * @param EE_Payment $payment
2184
-     * @return EE_Payment | FALSE
2185
-     * @throws \EE_Error
2186
-     */
2187
-    private function _validate_payment($payment = null)
2188
-    {
2189
-        if ($this->checkout->payment_method->is_off_line()) {
2190
-            return true;
2191
-        }
2192
-        // verify payment object
2193
-        if (! $payment instanceof EE_Payment) {
2194
-            // not a payment
2195
-            EE_Error::add_error(
2196
-                sprintf(
2197
-                    __(
2198
-                        'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2199
-                        'event_espresso'
2200
-                    ),
2201
-                    '<br/>',
2202
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2203
-                ),
2204
-                __FILE__,
2205
-                __FUNCTION__,
2206
-                __LINE__
2207
-            );
2208
-            return false;
2209
-        }
2210
-        return $payment;
2211
-    }
2212
-
2213
-
2214
-    /**
2215
-     * _post_payment_processing
2216
-     *
2217
-     * @access private
2218
-     * @param EE_Payment|bool $payment
2219
-     * @return bool
2220
-     * @throws \EE_Error
2221
-     */
2222
-    private function _post_payment_processing($payment = null)
2223
-    {
2224
-        // Off-Line payment?
2225
-        if ($payment === true) {
2226
-            //$this->_setup_redirect_for_next_step();
2227
-            return true;
2228
-            // On-Site payment?
2229
-        } else if ($this->checkout->payment_method->is_on_site()) {
2230
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2231
-                //$this->_setup_redirect_for_next_step();
2232
-                $this->checkout->continue_reg = false;
2233
-            }
2234
-            // Off-Site payment?
2235
-        } else if ($this->checkout->payment_method->is_off_site()) {
2236
-            // if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2237
-            if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2238
-                do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2239
-                $this->checkout->redirect      = true;
2240
-                $this->checkout->redirect_form = $payment->redirect_form();
2241
-                $this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2242
-                // set JSON response
2243
-                $this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2244
-                // set cron job for finalizing the TXN
2245
-                // in case the user does not return from the off-site gateway
2246
-                EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
2247
-                    EE_Registry::instance()->SSN->expiration() + 1,
2248
-                    $this->checkout->transaction->ID()
2249
-                );
2250
-                // and lastly, let's bump the payment status to pending
2251
-                $payment->set_status(EEM_Payment::status_id_pending);
2252
-                $payment->save();
2253
-            } else {
2254
-                // not a payment
2255
-                $this->checkout->continue_reg = false;
2256
-                EE_Error::add_error(
2257
-                    sprintf(
2258
-                        __(
2259
-                            'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2260
-                            'event_espresso'
2261
-                        ),
2262
-                        '<br/>',
2263
-                        EE_Registry::instance()->CFG->organization->get_pretty('email')
2264
-                    ),
2265
-                    __FILE__,
2266
-                    __FUNCTION__,
2267
-                    __LINE__
2268
-                );
2269
-            }
2270
-        } else {
2271
-            // ummm ya... not Off-Line, not On-Site, not off-Site ????
2272
-            $this->checkout->continue_reg = false;
2273
-            return false;
2274
-        }
2275
-        return $payment;
2276
-    }
2277
-
2278
-
2279
-
2280
-    /**
2281
-     *    _setup_redirect_for_next_step
2282
-     *
2283
-     * @access private
2284
-     * @return    void
2285
-     */
2286
-    //private function _setup_redirect_for_next_step() {
2287
-    //$this->checkout->redirect = TRUE;
2288
-    //$this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
2289
-    // set JSON response
2290
-    //$this->checkout->json_response->set_redirect_url( $this->checkout->redirect_url );
2291
-    //}
2292
-    /**
2293
-     *    _process_payment_status
2294
-     *
2295
-     * @access private
2296
-     * @type    EE_Payment $payment
2297
-     * @param string       $payment_occurs
2298
-     * @return bool
2299
-     * @throws \EE_Error
2300
-     */
2301
-    private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2302
-    {
2303
-        // off-line payment? carry on
2304
-        if ($payment_occurs === EE_PMT_Base::offline) {
2305
-            return true;
2306
-        }
2307
-        // verify payment validity
2308
-        if ($payment instanceof EE_Payment) {
2309
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2310
-            $msg = $payment->gateway_response();
2311
-            // check results
2312
-            switch ($payment->status()) {
2313
-                // good payment
2314
-                case EEM_Payment::status_id_approved :
2315
-                    EE_Error::add_success(
2316
-                        __('Your payment was processed successfully.', 'event_espresso'),
2317
-                        __FILE__,
2318
-                        __FUNCTION__,
2319
-                        __LINE__
2320
-                    );
2321
-                    return true;
2322
-                    break;
2323
-                // slow payment
2324
-                case EEM_Payment::status_id_pending :
2325
-                    if (empty($msg)) {
2326
-                        $msg = __(
2327
-                            'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2328
-                            'event_espresso'
2329
-                        );
2330
-                    }
2331
-                    EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2332
-                    return true;
2333
-                    break;
2334
-                // don't wanna payment
2335
-                case EEM_Payment::status_id_cancelled :
2336
-                    if (empty($msg)) {
2337
-                        $msg = _n(
2338
-                            'Payment cancelled. Please try again.',
2339
-                            'Payment cancelled. Please try again or select another method of payment.',
2340
-                            count($this->checkout->available_payment_methods),
2341
-                            'event_espresso'
2342
-                        );
2343
-                    }
2344
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2345
-                    return false;
2346
-                    break;
2347
-                // not enough payment
2348
-                case EEM_Payment::status_id_declined :
2349
-                    if (empty($msg)) {
2350
-                        $msg = _n(
2351
-                            'We\'re sorry but your payment was declined. Please try again.',
2352
-                            'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2353
-                            count($this->checkout->available_payment_methods),
2354
-                            'event_espresso'
2355
-                        );
2356
-                    }
2357
-                    EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2358
-                    return false;
2359
-                    break;
2360
-                // bad payment
2361
-                case EEM_Payment::status_id_failed :
2362
-                    if (! empty($msg)) {
2363
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2364
-                        return false;
2365
-                    }
2366
-                    // default to error below
2367
-                    break;
2368
-            }
2369
-        }
2370
-        // off-site payment gateway responses are too unreliable, so let's just assume that
2371
-        // the payment processing is just running slower than the registrant's request
2372
-        if ($payment_occurs === EE_PMT_Base::offsite) {
2373
-            return true;
2374
-        }
2375
-        EE_Error::add_error(
2376
-            sprintf(
2377
-                __(
2378
-                    'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2379
-                    'event_espresso'
2380
-                ),
2381
-                '<br/>',
2382
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
2383
-            ),
2384
-            __FILE__,
2385
-            __FUNCTION__,
2386
-            __LINE__
2387
-        );
2388
-        return false;
2389
-    }
2390
-
2391
-
2392
-
2393
-
2394
-
2395
-
2396
-    /********************************************************************************************************/
2397
-    /**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2398
-    /********************************************************************************************************/
2399
-    /**
2400
-     * process_gateway_response
2401
-     * this is the return point for Off-Site Payment Methods
2402
-     * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2403
-     * otherwise, it will load up the last payment made for the TXN.
2404
-     * If the payment retrieved looks good, it will then either:
2405
-     *    complete the current step and allow advancement to the next reg step
2406
-     *        or present the payment options again
2407
-     *
2408
-     * @access private
2409
-     * @return EE_Payment | FALSE
2410
-     * @throws \EE_Error
2411
-     */
2412
-    public function process_gateway_response()
2413
-    {
2414
-        $payment = null;
2415
-        // how have they chosen to pay?
2416
-        $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2417
-        // get EE_Payment_Method object
2418
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2419
-            $this->checkout->continue_reg = false;
2420
-            return false;
2421
-        }
2422
-        if (! $this->checkout->payment_method->is_off_site()) {
2423
-            return false;
2424
-        }
2425
-        $this->_validate_offsite_return();
2426
-        // DEBUG LOG
2427
-        //$this->checkout->log(
2428
-        //	__CLASS__, __FUNCTION__, __LINE__,
2429
-        //	array(
2430
-        //		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2431
-        //		'payment_method' => $this->checkout->payment_method,
2432
-        //	),
2433
-        //	true
2434
-        //);
2435
-        // verify TXN
2436
-        if ($this->checkout->transaction instanceof EE_Transaction) {
2437
-            $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2438
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2439
-                $this->checkout->continue_reg = false;
2440
-                return false;
2441
-            }
2442
-            $payment = $this->_process_off_site_payment($gateway);
2443
-            $payment = $this->_process_cancelled_payments($payment);
2444
-            $payment = $this->_validate_payment($payment);
2445
-            // if payment was not declined by the payment gateway or cancelled by the registrant
2446
-            if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2447
-                //$this->_setup_redirect_for_next_step();
2448
-                // store that for later
2449
-                $this->checkout->payment = $payment;
2450
-                // mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2451
-                // because we will complete this step during the IPN processing then
2452
-                if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2453
-                    $this->set_completed();
2454
-                }
2455
-                return true;
2456
-            }
2457
-        }
2458
-        // DEBUG LOG
2459
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2460
-        //	array( 'payment' => $payment )
2461
-        //);
2462
-        $this->checkout->continue_reg = false;
2463
-        return false;
2464
-    }
2465
-
2466
-
2467
-    /**
2468
-     * _validate_return
2469
-     *
2470
-     * @access private
2471
-     * @return void
2472
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2473
-     * @throws \EE_Error
2474
-     */
2475
-    private function _validate_offsite_return()
2476
-    {
2477
-        $TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2478
-        if ($TXN_ID !== $this->checkout->transaction->ID()) {
2479
-            // Houston... we might have a problem
2480
-            $invalid_TXN = false;
2481
-            // first gather some info
2482
-            $valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2483
-            $primary_registrant = $valid_TXN instanceof EE_Transaction
2484
-                ? $valid_TXN->primary_registration()
2485
-                : null;
2486
-            // let's start by retrieving the cart for this TXN
2487
-            $cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2488
-            if ($cart instanceof EE_Cart) {
2489
-                // verify that the current cart has tickets
2490
-                $tickets = $cart->get_tickets();
2491
-                if (empty($tickets)) {
2492
-                    $invalid_TXN = true;
2493
-                }
2494
-            } else {
2495
-                $invalid_TXN = true;
2496
-            }
2497
-            $valid_TXN_SID = $primary_registrant instanceof EE_Registration
2498
-                ? $primary_registrant->session_ID()
2499
-                : null;
2500
-            // validate current Session ID and compare against valid TXN session ID
2501
-            if (
2502
-                $invalid_TXN // if this is already true, then skip other checks
2503
-                || EE_Session::instance()->id() === null
2504
-                || (
2505
-                    // WARNING !!!
2506
-                    // this could be PayPal sending back duplicate requests (ya they do that)
2507
-                    // or it **could** mean someone is simply registering AGAIN after having just done so
2508
-                    // so now we need to determine if this current TXN looks valid or not
2509
-                    // and whether this reg step has even been started ?
2510
-                    EE_Session::instance()->id() === $valid_TXN_SID
2511
-                    // really? you're half way through this reg step, but you never started it ?
2512
-                    && $this->checkout->transaction->reg_step_completed($this->slug()) === false
2513
-                )
2514
-            ) {
2515
-                $invalid_TXN = true;
2516
-            }
2517
-            if ($invalid_TXN) {
2518
-                // is the valid TXN completed ?
2519
-                if ($valid_TXN instanceof EE_Transaction) {
2520
-                    // has this step even been started ?
2521
-                    $reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2522
-                    if ($reg_step_completed !== false && $reg_step_completed !== true) {
2523
-                        // so it **looks** like this is a double request from PayPal
2524
-                        // so let's try to pick up where we left off
2525
-                        $this->checkout->transaction = $valid_TXN;
2526
-                        $this->checkout->refresh_all_entities(true);
2527
-                        return;
2528
-                    }
2529
-                }
2530
-                // you appear to be lost?
2531
-                $this->_redirect_wayward_request($primary_registrant);
2532
-            }
2533
-        }
2534
-    }
2535
-
2536
-
2537
-    /**
2538
-     * _redirect_wayward_request
2539
-     *
2540
-     * @access private
2541
-     * @param \EE_Registration|null $primary_registrant
2542
-     * @return bool
2543
-     * @throws \EE_Error
2544
-     */
2545
-    private function _redirect_wayward_request(EE_Registration $primary_registrant)
2546
-    {
2547
-        if (! $primary_registrant instanceof EE_Registration) {
2548
-            // try redirecting based on the current TXN
2549
-            $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2550
-                ? $this->checkout->transaction->primary_registration()
2551
-                : null;
2552
-        }
2553
-        if (! $primary_registrant instanceof EE_Registration) {
2554
-            EE_Error::add_error(
2555
-                sprintf(
2556
-                    __(
2557
-                        'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2558
-                        'event_espresso'
2559
-                    ),
2560
-                    '<br/>',
2561
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
2562
-                ),
2563
-                __FILE__,
2564
-                __FUNCTION__,
2565
-                __LINE__
2566
-            );
2567
-            return false;
2568
-        }
2569
-        // make sure transaction is not locked
2570
-        $this->checkout->transaction->unlock();
2571
-        wp_safe_redirect(
2572
-            add_query_arg(
2573
-                array(
2574
-                    'e_reg_url_link' => $primary_registrant->reg_url_link(),
2575
-                ),
2576
-                $this->checkout->thank_you_page_url
2577
-            )
2578
-        );
2579
-        exit();
2580
-    }
2581
-
2582
-
2583
-    /**
2584
-     * _process_off_site_payment
2585
-     *
2586
-     * @access private
2587
-     * @param \EE_Offsite_Gateway $gateway
2588
-     * @return \EE_Payment
2589
-     * @throws \EE_Error
2590
-     */
2591
-    private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2592
-    {
2593
-        try {
2594
-            $request_data = \EE_Registry::instance()->REQ->params();
2595
-            // if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2596
-            $this->set_handle_IPN_in_this_request(
2597
-                $gateway->handle_IPN_in_this_request($request_data, false)
2598
-            );
2599
-            if ($this->handle_IPN_in_this_request()) {
2600
-                // get payment details and process results
2601
-                /** @type EE_Payment_Processor $payment_processor */
2602
-                $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2603
-                $payment           = $payment_processor->process_ipn(
2604
-                    $request_data,
2605
-                    $this->checkout->transaction,
2606
-                    $this->checkout->payment_method,
2607
-                    true,
2608
-                    false
2609
-                );
2610
-                //$payment_source = 'process_ipn';
2611
-            } else {
2612
-                $payment = $this->checkout->transaction->last_payment();
2613
-                //$payment_source = 'last_payment';
2614
-            }
2615
-        } catch (Exception $e) {
2616
-            // let's just eat the exception and try to move on using any previously set payment info
2617
-            $payment = $this->checkout->transaction->last_payment();
2618
-            //$payment_source = 'last_payment after Exception';
2619
-            // but if we STILL don't have a payment object
2620
-            if (! $payment instanceof EE_Payment) {
2621
-                // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2622
-                $this->_handle_payment_processor_exception($e);
2623
-            }
2624
-        }
2625
-        // DEBUG LOG
2626
-        //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2627
-        //	array(
2628
-        //		'process_ipn_payment' => $payment,
2629
-        //		'payment_source'      => $payment_source,
2630
-        //	)
2631
-        //);
2632
-        return $payment;
2633
-    }
2634
-
2635
-
2636
-    /**
2637
-     * _process_cancelled_payments
2638
-     * just makes sure that the payment status gets updated correctly
2639
-     * so tha tan error isn't generated during payment validation
2640
-     *
2641
-     * @access private
2642
-     * @param EE_Payment $payment
2643
-     * @return EE_Payment | FALSE
2644
-     * @throws \EE_Error
2645
-     */
2646
-    private function _process_cancelled_payments($payment = null)
2647
-    {
2648
-        if (
2649
-            $payment instanceof EE_Payment
2650
-            && isset($_REQUEST['ee_cancel_payment'])
2651
-            && $payment->status() === EEM_Payment::status_id_failed
2652
-        ) {
2653
-            $payment->set_status(EEM_Payment::status_id_cancelled);
2654
-        }
2655
-        return $payment;
2656
-    }
2657
-
2658
-
2659
-    /**
2660
-     *    get_transaction_details_for_gateways
2661
-     *
2662
-     * @access    public
2663
-     * @return    int
2664
-     * @throws \EE_Error
2665
-     */
2666
-    public function get_transaction_details_for_gateways()
2667
-    {
2668
-        $txn_details = array();
2669
-        // ya gotta make a choice man
2670
-        if (empty($this->checkout->selected_method_of_payment)) {
2671
-            $txn_details = array(
2672
-                'error' => __('Please select a method of payment before proceeding.', 'event_espresso'),
2673
-            );
2674
-        }
2675
-        // get EE_Payment_Method object
2676
-        if (
2677
-            empty($txn_details)
2678
-            &&
2679
-            ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2680
-        ) {
2681
-            $txn_details = array(
2682
-                'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2683
-                'error'                      => __(
2684
-                    'A valid Payment Method could not be determined.',
2685
-                    'event_espresso'
2686
-                ),
2687
-            );
2688
-        }
2689
-        if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2690
-            $return_url  = $this->_get_return_url($this->checkout->payment_method);
2691
-            $txn_details = array(
2692
-                'TXN_ID'         => $this->checkout->transaction->ID(),
2693
-                'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2694
-                'TXN_total'      => $this->checkout->transaction->total(),
2695
-                'TXN_paid'       => $this->checkout->transaction->paid(),
2696
-                'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2697
-                'STS_ID'         => $this->checkout->transaction->status_ID(),
2698
-                'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2699
-                'payment_amount' => $this->checkout->amount_owing,
2700
-                'return_url'     => $return_url,
2701
-                'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2702
-                'notify_url'     => EE_Config::instance()->core->txn_page_url(
2703
-                    array(
2704
-                        'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2705
-                        'ee_payment_method' => $this->checkout->payment_method->slug(),
2706
-                    )
2707
-                ),
2708
-            );
2709
-        }
2710
-        echo wp_json_encode($txn_details);
2711
-        exit();
2712
-    }
2713
-
2714
-
2715
-    /**
2716
-     *    __sleep
2717
-     * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2718
-     * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2719
-     * reg form, because if needed, it will be regenerated anyways
2720
-     *
2721
-     * @return array
2722
-     */
2723
-    public function __sleep()
2724
-    {
2725
-        // remove the reg form and the checkout
2726
-        return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2727
-    }
18
+	/**
19
+	 * @access protected
20
+	 * @var EE_Line_Item_Display $Line_Item_Display
21
+	 */
22
+	protected $line_item_display;
23
+
24
+	/**
25
+	 * @access protected
26
+	 * @var boolean $handle_IPN_in_this_request
27
+	 */
28
+	protected $handle_IPN_in_this_request = false;
29
+
30
+
31
+	/**
32
+	 *    set_hooks - for hooking into EE Core, other modules, etc
33
+	 *
34
+	 * @access    public
35
+	 * @return    void
36
+	 */
37
+	public static function set_hooks()
38
+	{
39
+		add_filter(
40
+			'FHEE__SPCO__EE_Line_Item_Filter_Collection',
41
+			array('EE_SPCO_Reg_Step_Payment_Options', 'add_spco_line_item_filters')
42
+		);
43
+		add_action(
44
+			'wp_ajax_switch_spco_billing_form',
45
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
46
+		);
47
+		add_action(
48
+			'wp_ajax_nopriv_switch_spco_billing_form',
49
+			array('EE_SPCO_Reg_Step_Payment_Options', 'switch_spco_billing_form')
50
+		);
51
+		add_action('wp_ajax_save_payer_details', array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details'));
52
+		add_action(
53
+			'wp_ajax_nopriv_save_payer_details',
54
+			array('EE_SPCO_Reg_Step_Payment_Options', 'save_payer_details')
55
+		);
56
+		add_action(
57
+			'wp_ajax_get_transaction_details_for_gateways',
58
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
59
+		);
60
+		add_action(
61
+			'wp_ajax_nopriv_get_transaction_details_for_gateways',
62
+			array('EE_SPCO_Reg_Step_Payment_Options', 'get_transaction_details')
63
+		);
64
+		add_filter(
65
+			'FHEE__EED_Recaptcha___bypass_recaptcha__bypass_request_params_array',
66
+			array('EE_SPCO_Reg_Step_Payment_Options', 'bypass_recaptcha_for_load_payment_method'),
67
+			10,
68
+			1
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 *    ajax switch_spco_billing_form
75
+	 *
76
+	 * @throws \EE_Error
77
+	 */
78
+	public static function switch_spco_billing_form()
79
+	{
80
+		EED_Single_Page_Checkout::process_ajax_request('switch_payment_method');
81
+	}
82
+
83
+
84
+	/**
85
+	 *    ajax save_payer_details
86
+	 *
87
+	 * @throws \EE_Error
88
+	 */
89
+	public static function save_payer_details()
90
+	{
91
+		EED_Single_Page_Checkout::process_ajax_request('save_payer_details_via_ajax');
92
+	}
93
+
94
+
95
+	/**
96
+	 *    ajax get_transaction_details
97
+	 *
98
+	 * @throws \EE_Error
99
+	 */
100
+	public static function get_transaction_details()
101
+	{
102
+		EED_Single_Page_Checkout::process_ajax_request('get_transaction_details_for_gateways');
103
+	}
104
+
105
+
106
+	/**
107
+	 * bypass_recaptcha_for_load_payment_method
108
+	 *
109
+	 * @access public
110
+	 * @return array
111
+	 */
112
+	public static function bypass_recaptcha_for_load_payment_method()
113
+	{
114
+		return array(
115
+			'EESID'  => EE_Registry::instance()->SSN->id(),
116
+			'step'   => 'payment_options',
117
+			'action' => 'spco_billing_form',
118
+		);
119
+	}
120
+
121
+
122
+	/**
123
+	 *    class constructor
124
+	 *
125
+	 * @access    public
126
+	 * @param    EE_Checkout $checkout
127
+	 */
128
+	public function __construct(EE_Checkout $checkout)
129
+	{
130
+		$this->_slug     = 'payment_options';
131
+		$this->_name     = __('Payment Options', 'event_espresso');
132
+		$this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
133
+		$this->checkout  = $checkout;
134
+		$this->_reset_success_message();
135
+		$this->set_instructions(
136
+			__(
137
+				'Please select a method of payment and provide any necessary billing information before proceeding.',
138
+				'event_espresso'
139
+			)
140
+		);
141
+	}
142
+
143
+
144
+	/**
145
+	 * @return null
146
+	 */
147
+	public function line_item_display()
148
+	{
149
+		return $this->line_item_display;
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param null $line_item_display
155
+	 */
156
+	public function set_line_item_display($line_item_display)
157
+	{
158
+		$this->line_item_display = $line_item_display;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @return boolean
164
+	 */
165
+	public function handle_IPN_in_this_request()
166
+	{
167
+		return $this->handle_IPN_in_this_request;
168
+	}
169
+
170
+
171
+	/**
172
+	 * @param boolean $handle_IPN_in_this_request
173
+	 */
174
+	public function set_handle_IPN_in_this_request($handle_IPN_in_this_request)
175
+	{
176
+		$this->handle_IPN_in_this_request = filter_var($handle_IPN_in_this_request, FILTER_VALIDATE_BOOLEAN);
177
+	}
178
+
179
+
180
+	/**
181
+	 * translate_js_strings
182
+	 *
183
+	 * @return void
184
+	 */
185
+	public function translate_js_strings()
186
+	{
187
+		EE_Registry::$i18n_js_strings['no_payment_method']      = __(
188
+			'Please select a method of payment in order to continue.',
189
+			'event_espresso'
190
+		);
191
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = __(
192
+			'A valid method of payment could not be determined. Please refresh the page and try again.',
193
+			'event_espresso'
194
+		);
195
+		EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = __(
196
+			'Forwarding to Secure Payment Provider.',
197
+			'event_espresso'
198
+		);
199
+	}
200
+
201
+
202
+	/**
203
+	 * enqueue_styles_and_scripts
204
+	 *
205
+	 * @return void
206
+	 */
207
+	public function enqueue_styles_and_scripts()
208
+	{
209
+		$transaction = $this->checkout->transaction;
210
+		//if the transaction isn't set or nothing is owed on it, don't enqueue any JS
211
+		if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
212
+			return;
213
+		}
214
+		foreach (
215
+			EEM_Payment_Method::instance()->get_all_for_transaction($transaction,
216
+				EEM_Payment_Method::scope_cart) as $payment_method
217
+		) {
218
+			$type_obj = $payment_method->type_obj();
219
+			if ($type_obj instanceof EE_PMT_Base) {
220
+				$billing_form = $type_obj->generate_new_billing_form($transaction);
221
+				if ($billing_form instanceof EE_Form_Section_Proper) {
222
+					$billing_form->enqueue_js();
223
+				}
224
+			}
225
+		}
226
+	}
227
+
228
+
229
+	/**
230
+	 * initialize_reg_step
231
+	 *
232
+	 * @return boolean
233
+	 * @throws \EE_Error
234
+	 */
235
+	public function initialize_reg_step()
236
+	{
237
+		// TODO: if /when we implement donations, then this will need overriding
238
+		if (
239
+			// don't need payment options for:
240
+			// 	registrations made via the admin
241
+			// 	completed transactions
242
+			// 	overpaid transactions
243
+			// 	$ 0.00 transactions (no payment required)
244
+			! $this->checkout->payment_required()
245
+			// but do NOT remove if current action being called belongs to this reg step
246
+			&& ! is_callable(array($this, $this->checkout->action))
247
+			&& ! $this->completed()
248
+		) {
249
+			// and if so, then we no longer need the Payment Options step
250
+			if ($this->is_current_step()) {
251
+				$this->checkout->generate_reg_form = false;
252
+			}
253
+			$this->checkout->remove_reg_step($this->_slug);
254
+			// DEBUG LOG
255
+			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
256
+			return false;
257
+		}
258
+		// load EEM_Payment_Method
259
+		EE_Registry::instance()->load_model('Payment_Method');
260
+		// get all active payment methods
261
+		$this->checkout->available_payment_methods = EEM_Payment_Method::instance()->get_all_for_transaction(
262
+			$this->checkout->transaction,
263
+			EEM_Payment_Method::scope_cart
264
+		);
265
+		return true;
266
+	}
267
+
268
+
269
+	/**
270
+	 * @return \EE_Form_Section_Proper
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function generate_reg_form()
274
+	{
275
+		// reset in case someone changes their mind
276
+		$this->_reset_selected_method_of_payment();
277
+		// set some defaults
278
+		$this->checkout->selected_method_of_payment = 'payments_closed';
279
+		$registrations_requiring_payment            = array();
280
+		$registrations_for_free_events              = array();
281
+		$registrations_requiring_pre_approval       = array();
282
+		$sold_out_events                            = array();
283
+		$insufficient_spaces_available              = array();
284
+		$no_payment_required                        = true;
285
+		// loop thru registrations to gather info
286
+		$registrations         = $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params);
287
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
288
+			$registrations,
289
+			$this->checkout->revisit
290
+		);
291
+		foreach ($registrations as $REG_ID => $registration) {
292
+			/** @var $registration EE_Registration */
293
+			// has this registration lost it's space ?
294
+			if (isset($ejected_registrations[$REG_ID])) {
295
+				$insufficient_spaces_available[$registration->event()->ID()] = $registration->event();
296
+				continue;
297
+			}
298
+			// event requires admin approval
299
+			if ($registration->status_ID() === EEM_Registration::status_id_not_approved) {
300
+				// add event to list of events with pre-approval reg status
301
+				$registrations_requiring_pre_approval[$REG_ID] = $registration;
302
+				do_action(
303
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_pre_approval',
304
+					$registration->event(),
305
+					$this
306
+				);
307
+				continue;
308
+			}
309
+			if (
310
+				// returning registrant
311
+				$this->checkout->revisit
312
+				// anything other than Approved
313
+				&& $registration->status_ID() !== EEM_Registration::status_id_approved
314
+				&& (
315
+					$registration->event()->is_sold_out()
316
+					|| $registration->event()->is_sold_out(true)
317
+				)
318
+			) {
319
+				// add event to list of events that are sold out
320
+				$sold_out_events[$registration->event()->ID()] = $registration->event();
321
+				do_action(
322
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__sold_out_event',
323
+					$registration->event(),
324
+					$this
325
+				);
326
+				continue;
327
+			}
328
+			// are they allowed to pay now and is there monies owing?
329
+			if ($registration->owes_monies_and_can_pay()) {
330
+				$registrations_requiring_payment[$REG_ID] = $registration;
331
+				do_action(
332
+					'AHEE__EE_SPCO_Reg_Step_Payment_Options__generate_reg_form__event_requires_payment',
333
+					$registration->event(),
334
+					$this
335
+				);
336
+			} else if (
337
+				! $this->checkout->revisit
338
+				&& $registration->status_ID() !== EEM_Registration::status_id_not_approved
339
+				&& $registration->ticket()->is_free()
340
+			) {
341
+				$registrations_for_free_events[$registration->event()->ID()] = $registration;
342
+			}
343
+		}
344
+		$subsections = array();
345
+		// now decide which template to load
346
+		if (! empty($sold_out_events)) {
347
+			$subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
348
+		}
349
+		if (! empty($insufficient_spaces_available)) {
350
+			$subsections['insufficient_space'] = $this->_insufficient_spaces_available(
351
+				$insufficient_spaces_available
352
+			);
353
+		}
354
+		if (! empty($registrations_requiring_pre_approval)) {
355
+			$subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
356
+				$registrations_requiring_pre_approval
357
+			);
358
+		}
359
+		if (! empty($registrations_for_free_events)) {
360
+			$subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
361
+		}
362
+		if (! empty($registrations_requiring_payment)) {
363
+			if ($this->checkout->amount_owing > 0) {
364
+				// autoload Line_Item_Display classes
365
+				EEH_Autoloader::register_line_item_filter_autoloaders();
366
+				$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
367
+					apply_filters(
368
+						'FHEE__SPCO__EE_Line_Item_Filter_Collection',
369
+						new EE_Line_Item_Filter_Collection()
370
+					),
371
+					$this->checkout->cart->get_grand_total()
372
+				);
373
+				/** @var EE_Line_Item $filtered_line_item_tree */
374
+				$filtered_line_item_tree = $line_item_filter_processor->process();
375
+				EEH_Autoloader::register_line_item_display_autoloaders();
376
+				$this->set_line_item_display(new EE_Line_Item_Display('spco'));
377
+				$subsections['payment_options'] = $this->_display_payment_options(
378
+					$this->line_item_display->display_line_item(
379
+						$filtered_line_item_tree,
380
+						array('registrations' => $registrations)
381
+					)
382
+				);
383
+				$this->checkout->amount_owing   = $filtered_line_item_tree->total();
384
+				$this->_apply_registration_payments_to_amount_owing($registrations);
385
+			}
386
+			$no_payment_required = false;
387
+		} else {
388
+			$this->_hide_reg_step_submit_button_if_revisit();
389
+		}
390
+		$this->_save_selected_method_of_payment();
391
+
392
+		$subsections['default_hidden_inputs'] = $this->reg_step_hidden_inputs();
393
+		$subsections['extra_hidden_inputs']   = $this->_extra_hidden_inputs($no_payment_required);
394
+
395
+		return new EE_Form_Section_Proper(
396
+			array(
397
+				'name'            => $this->reg_form_name(),
398
+				'html_id'         => $this->reg_form_name(),
399
+				'subsections'     => $subsections,
400
+				'layout_strategy' => new EE_No_Layout(),
401
+			)
402
+		);
403
+	}
404
+
405
+
406
+	/**
407
+	 * add line item filters required for this reg step
408
+	 * these filters are applied via this line in EE_SPCO_Reg_Step_Payment_Options::set_hooks():
409
+	 *        add_filter( 'FHEE__SPCO__EE_Line_Item_Filter_Collection', array( 'EE_SPCO_Reg_Step_Payment_Options',
410
+	 *        'add_spco_line_item_filters' ) ); so any code that wants to use the same set of filters during the
411
+	 *        payment options reg step, can apply these filters via the following: apply_filters(
412
+	 *        'FHEE__SPCO__EE_Line_Item_Filter_Collection', new EE_Line_Item_Filter_Collection() ) or to an existing
413
+	 *        filter collection by passing that instead of instantiating a new collection
414
+	 *
415
+	 * @param \EE_Line_Item_Filter_Collection $line_item_filter_collection
416
+	 * @return \EE_Line_Item_Filter_Collection
417
+	 * @throws \EE_Error
418
+	 */
419
+	public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
420
+	{
421
+		if (! EE_Registry::instance()->SSN instanceof EE_Session) {
422
+			return $line_item_filter_collection;
423
+		}
424
+		if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
425
+			return $line_item_filter_collection;
426
+		}
427
+		if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
428
+			return $line_item_filter_collection;
429
+		}
430
+		$line_item_filter_collection->add(
431
+			new EE_Billable_Line_Item_Filter(
432
+				EE_SPCO_Reg_Step_Payment_Options::remove_ejected_registrations(
433
+					EE_Registry::instance()->SSN->checkout()->transaction->registrations(
434
+						EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
435
+					)
436
+				)
437
+			)
438
+		);
439
+		$line_item_filter_collection->add(new EE_Non_Zero_Line_Item_Filter());
440
+		return $line_item_filter_collection;
441
+	}
442
+
443
+
444
+	/**
445
+	 * remove_ejected_registrations
446
+	 * if a registrant has lost their potential space at an event due to lack of payment,
447
+	 * then this method removes them from the list of registrations being paid for during this request
448
+	 *
449
+	 * @param \EE_Registration[] $registrations
450
+	 * @return \EE_Registration[]
451
+	 * @throws \EE_Error
452
+	 */
453
+	public static function remove_ejected_registrations(array $registrations)
454
+	{
455
+		$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
456
+			$registrations,
457
+			EE_Registry::instance()->SSN->checkout()->revisit
458
+		);
459
+		foreach ($registrations as $REG_ID => $registration) {
460
+			// has this registration lost it's space ?
461
+			if (isset($ejected_registrations[$REG_ID])) {
462
+				unset($registrations[$REG_ID]);
463
+				continue;
464
+			}
465
+		}
466
+		return $registrations;
467
+	}
468
+
469
+
470
+	/**
471
+	 * find_registrations_that_lost_their_space
472
+	 * If a registrant chooses an offline payment method like Invoice,
473
+	 * then no space is reserved for them at the event until they fully pay fo that site
474
+	 * (unless the event's default reg status is set to APPROVED)
475
+	 * if a registrant then later returns to pay, but the number of spaces available has been reduced due to sales,
476
+	 * then this method will determine which registrations have lost the ability to complete the reg process.
477
+	 *
478
+	 * @param \EE_Registration[] $registrations
479
+	 * @param bool               $revisit
480
+	 * @return array
481
+	 * @throws \EE_Error
482
+	 */
483
+	public static function find_registrations_that_lost_their_space(array $registrations, $revisit = false)
484
+	{
485
+		// registrations per event
486
+		$event_reg_count = array();
487
+		// spaces left per event
488
+		$event_spaces_remaining = array();
489
+		// tickets left sorted by ID
490
+		$tickets_remaining = array();
491
+		// registrations that have lost their space
492
+		$ejected_registrations = array();
493
+		foreach ($registrations as $REG_ID => $registration) {
494
+			if (
495
+				$registration->status_ID() === EEM_Registration::status_id_approved
496
+				|| apply_filters(
497
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__find_registrations_that_lost_their_space__allow_reg_payment',
498
+					false,
499
+					$registration,
500
+					$revisit
501
+				)
502
+			) {
503
+				continue;
504
+			}
505
+			$EVT_ID = $registration->event_ID();
506
+			$ticket = $registration->ticket();
507
+			if (! isset($tickets_remaining[$ticket->ID()])) {
508
+				$tickets_remaining[$ticket->ID()] = $ticket->remaining();
509
+			}
510
+			if ($tickets_remaining[$ticket->ID()] > 0) {
511
+				if (! isset($event_reg_count[$EVT_ID])) {
512
+					$event_reg_count[$EVT_ID] = 0;
513
+				}
514
+				$event_reg_count[$EVT_ID]++;
515
+				if (! isset($event_spaces_remaining[$EVT_ID])) {
516
+					$event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
517
+				}
518
+			}
519
+			if (
520
+				$revisit
521
+				&& (
522
+					$tickets_remaining[$ticket->ID()] === 0
523
+					|| $event_reg_count[$EVT_ID] > $event_spaces_remaining[$EVT_ID]
524
+				)
525
+			) {
526
+				$ejected_registrations[$REG_ID] = $registration->event();
527
+				if ($registration->status_ID() !== EEM_Registration::status_id_wait_list) {
528
+					/** @type EE_Registration_Processor $registration_processor */
529
+					$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
530
+					// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
531
+					$registration_processor->manually_update_registration_status(
532
+						$registration,
533
+						EEM_Registration::status_id_wait_list
534
+					);
535
+				}
536
+
537
+			}
538
+		}
539
+		return $ejected_registrations;
540
+	}
541
+
542
+
543
+	/**
544
+	 * _hide_reg_step_submit_button
545
+	 * removes the html for the reg step submit button
546
+	 * by replacing it with an empty string via filter callback
547
+	 *
548
+	 * @return void
549
+	 */
550
+	protected function _adjust_registration_status_if_event_old_sold()
551
+	{
552
+	}
553
+
554
+
555
+	/**
556
+	 * _hide_reg_step_submit_button
557
+	 * removes the html for the reg step submit button
558
+	 * by replacing it with an empty string via filter callback
559
+	 *
560
+	 * @return void
561
+	 */
562
+	protected function _hide_reg_step_submit_button_if_revisit()
563
+	{
564
+		if ($this->checkout->revisit) {
565
+			add_filter('FHEE__EE_SPCO_Reg_Step__reg_step_submit_button__sbmt_btn_html', '__return_empty_string');
566
+		}
567
+	}
568
+
569
+
570
+	/**
571
+	 * sold_out_events
572
+	 * displays notices regarding events that have sold out since hte registrant first signed up
573
+	 *
574
+	 * @param \EE_Event[] $sold_out_events_array
575
+	 * @return \EE_Form_Section_Proper
576
+	 * @throws \EE_Error
577
+	 */
578
+	private function _sold_out_events($sold_out_events_array = array())
579
+	{
580
+		// set some defaults
581
+		$this->checkout->selected_method_of_payment = 'events_sold_out';
582
+		$sold_out_events                            = '';
583
+		foreach ($sold_out_events_array as $sold_out_event) {
584
+			$sold_out_events .= EEH_HTML::li(
585
+				EEH_HTML::span('  ' . $sold_out_event->name(), '',
586
+					'dashicons dashicons-marker ee-icon-size-16 pink-text')
587
+			);
588
+		}
589
+		return new EE_Form_Section_Proper(
590
+			array(
591
+				'layout_strategy' => new EE_Template_Layout(
592
+					array(
593
+						'layout_template_file' => SPCO_REG_STEPS_PATH
594
+												  . $this->_slug
595
+												  . DS
596
+												  . 'sold_out_events.template.php',
597
+						'template_args'        => apply_filters(
598
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
599
+							array(
600
+								'sold_out_events'     => $sold_out_events,
601
+								'sold_out_events_msg' => apply_filters(
602
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__sold_out_events_msg',
603
+									sprintf(
604
+										__('It appears that the event you were about to make a payment for has sold out since you first registered. If you have already made a partial payment towards this event, please contact the event administrator for a refund.%3$s%3$s%1$sPlease note that availability can change at any time due to cancellations, so please check back again later if registration for this event(s) is important to you.%2$s',
605
+											'event_espresso'),
606
+										'<strong>',
607
+										'</strong>',
608
+										'<br />'
609
+									)
610
+								),
611
+							)
612
+						),
613
+					)
614
+				),
615
+			)
616
+		);
617
+	}
618
+
619
+
620
+	/**
621
+	 * _insufficient_spaces_available
622
+	 * displays notices regarding events that do not have enough remaining spaces
623
+	 * to satisfy the current number of registrations looking to pay
624
+	 *
625
+	 * @param \EE_Event[] $insufficient_spaces_events_array
626
+	 * @return \EE_Form_Section_Proper
627
+	 * @throws \EE_Error
628
+	 */
629
+	private function _insufficient_spaces_available($insufficient_spaces_events_array = array())
630
+	{
631
+		// set some defaults
632
+		$this->checkout->selected_method_of_payment = 'invoice';
633
+		$insufficient_space_events                  = '';
634
+		foreach ($insufficient_spaces_events_array as $event) {
635
+			if ($event instanceof EE_Event) {
636
+				$insufficient_space_events .= EEH_HTML::li(
637
+					EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
638
+				);
639
+			}
640
+		}
641
+		return new EE_Form_Section_Proper(
642
+			array(
643
+				'subsections'     => array(
644
+					'default_hidden_inputs' => $this->reg_step_hidden_inputs(),
645
+					'extra_hidden_inputs'   => $this->_extra_hidden_inputs(),
646
+				),
647
+				'layout_strategy' => new EE_Template_Layout(
648
+					array(
649
+						'layout_template_file' => SPCO_REG_STEPS_PATH
650
+												  . $this->_slug
651
+												  . DS
652
+												  . 'sold_out_events.template.php',
653
+						'template_args'        => apply_filters(
654
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__template_args',
655
+							array(
656
+								'sold_out_events'     => $insufficient_space_events,
657
+								'sold_out_events_msg' => apply_filters(
658
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___insufficient_spaces_available__insufficient_space_msg',
659
+									__(
660
+										'It appears that the event you were about to make a payment for has sold additional tickets since you first registered, and there are no longer enough spaces left to accommodate your selections. You may continue to pay and secure the available space(s) remaining, or simply cancel if you no longer wish to purchase. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
661
+										'event_espresso'
662
+									)
663
+								),
664
+							)
665
+						),
666
+					)
667
+				),
668
+			)
669
+		);
670
+	}
671
+
672
+
673
+	/**
674
+	 * registrations_requiring_pre_approval
675
+	 *
676
+	 * @param array $registrations_requiring_pre_approval
677
+	 * @return \EE_Form_Section_Proper
678
+	 * @throws \EE_Error
679
+	 */
680
+	private function _registrations_requiring_pre_approval($registrations_requiring_pre_approval = array())
681
+	{
682
+		$events_requiring_pre_approval = '';
683
+		foreach ($registrations_requiring_pre_approval as $registration) {
684
+			if ($registration instanceof EE_Registration && $registration->event() instanceof EE_Event) {
685
+				$events_requiring_pre_approval[$registration->event()->ID()] = EEH_HTML::li(
686
+					EEH_HTML::span(
687
+						'',
688
+						'',
689
+						'dashicons dashicons-marker ee-icon-size-16 orange-text'
690
+					)
691
+					. EEH_HTML::span($registration->event()->name(), '', 'orange-text')
692
+				);
693
+			}
694
+		}
695
+		return new EE_Form_Section_Proper(
696
+			array(
697
+				'layout_strategy' => new EE_Template_Layout(
698
+					array(
699
+						'layout_template_file' => SPCO_REG_STEPS_PATH
700
+												  . $this->_slug
701
+												  . DS
702
+												  . 'events_requiring_pre_approval.template.php', // layout_template
703
+						'template_args'        => apply_filters(
704
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___sold_out_events__template_args',
705
+							array(
706
+								'events_requiring_pre_approval'     => implode('', $events_requiring_pre_approval),
707
+								'events_requiring_pre_approval_msg' => apply_filters(
708
+									'FHEE__EE_SPCO_Reg_Step_Payment_Options___events_requiring_pre_approval__events_requiring_pre_approval_msg',
709
+									__(
710
+										'The following events do not require payment at this time and will not be billed during this transaction. Billing will only occur after the attendee has been approved by the event organizer. You will be notified when your registration has been processed. If this is a free event, then no billing will occur.',
711
+										'event_espresso'
712
+									)
713
+								),
714
+							)
715
+						),
716
+					)
717
+				),
718
+			)
719
+		);
720
+	}
721
+
722
+
723
+	/**
724
+	 * _no_payment_required
725
+	 *
726
+	 * @param \EE_Event[] $registrations_for_free_events
727
+	 * @return \EE_Form_Section_Proper
728
+	 * @throws \EE_Error
729
+	 */
730
+	private function _no_payment_required($registrations_for_free_events = array())
731
+	{
732
+		// set some defaults
733
+		$this->checkout->selected_method_of_payment = 'no_payment_required';
734
+		// generate no_payment_required form
735
+		return new EE_Form_Section_Proper(
736
+			array(
737
+				'layout_strategy' => new EE_Template_Layout(
738
+					array(
739
+						'layout_template_file' => SPCO_REG_STEPS_PATH
740
+												  . $this->_slug
741
+												  . DS
742
+												  . 'no_payment_required.template.php', // layout_template
743
+						'template_args'        => apply_filters(
744
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___no_payment_required__template_args',
745
+							array(
746
+								'revisit'                       => $this->checkout->revisit,
747
+								'registrations'                 => array(),
748
+								'ticket_count'                  => array(),
749
+								'registrations_for_free_events' => $registrations_for_free_events,
750
+								'no_payment_required_msg'       => EEH_HTML::p(
751
+									__('This is a free event, so no billing will occur.', 'event_espresso')
752
+								),
753
+							)
754
+						),
755
+					)
756
+				),
757
+			)
758
+		);
759
+	}
760
+
761
+
762
+	/**
763
+	 * _display_payment_options
764
+	 *
765
+	 * @param string $transaction_details
766
+	 * @return \EE_Form_Section_Proper
767
+	 * @throws \EE_Error
768
+	 */
769
+	private function _display_payment_options($transaction_details = '')
770
+	{
771
+		// has method_of_payment been set by no-js user?
772
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment();
773
+		// build payment options form
774
+		return apply_filters(
775
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__payment_options_form',
776
+			new EE_Form_Section_Proper(
777
+				array(
778
+					'subsections'     => array(
779
+						'before_payment_options' => apply_filters(
780
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__before_payment_options',
781
+							new EE_Form_Section_Proper(
782
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
783
+							)
784
+						),
785
+						'payment_options'        => $this->_setup_payment_options(),
786
+						'after_payment_options'  => apply_filters(
787
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__after_payment_options',
788
+							new EE_Form_Section_Proper(
789
+								array('layout_strategy' => new EE_Div_Per_Section_Layout())
790
+							)
791
+						),
792
+					),
793
+					'layout_strategy' => new EE_Template_Layout(
794
+						array(
795
+							'layout_template_file' => $this->_template,
796
+							'template_args'        => apply_filters(
797
+								'FHEE__EE_SPCO_Reg_Step_Payment_Options___display_payment_options__template_args',
798
+								array(
799
+									'reg_count'                 => $this->line_item_display->total_items(),
800
+									'transaction_details'       => $transaction_details,
801
+									'available_payment_methods' => array(),
802
+								)
803
+							),
804
+						)
805
+					),
806
+				)
807
+			)
808
+		);
809
+	}
810
+
811
+
812
+	/**
813
+	 * _extra_hidden_inputs
814
+	 *
815
+	 * @param bool $no_payment_required
816
+	 * @return \EE_Form_Section_Proper
817
+	 * @throws \EE_Error
818
+	 */
819
+	private function _extra_hidden_inputs($no_payment_required = true)
820
+	{
821
+		return new EE_Form_Section_Proper(
822
+			array(
823
+				'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
824
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
825
+				'subsections'     => array(
826
+					'spco_no_payment_required' => new EE_Hidden_Input(
827
+						array(
828
+							'normalization_strategy' => new EE_Boolean_Normalization(),
829
+							'html_name'              => 'spco_no_payment_required',
830
+							'html_id'                => 'spco-no-payment-required-payment_options',
831
+							'default'                => $no_payment_required,
832
+						)
833
+					),
834
+					'spco_transaction_id'      => new EE_Fixed_Hidden_Input(
835
+						array(
836
+							'normalization_strategy' => new EE_Int_Normalization(),
837
+							'html_name'              => 'spco_transaction_id',
838
+							'html_id'                => 'spco-transaction-id',
839
+							'default'                => $this->checkout->transaction->ID(),
840
+						)
841
+					),
842
+				),
843
+			)
844
+		);
845
+	}
846
+
847
+
848
+	/**
849
+	 *    _apply_registration_payments_to_amount_owing
850
+	 *
851
+	 * @access protected
852
+	 * @param array $registrations
853
+	 */
854
+	protected function _apply_registration_payments_to_amount_owing(array $registrations)
855
+	{
856
+		$payments = array();
857
+		foreach ($registrations as $registration) {
858
+			if ($registration instanceof EE_Registration && $registration->owes_monies_and_can_pay()) {
859
+				$payments += $registration->registration_payments();
860
+			}
861
+		}
862
+		if (! empty($payments)) {
863
+			foreach ($payments as $payment) {
864
+				if ($payment instanceof EE_Registration_Payment) {
865
+					$this->checkout->amount_owing -= $payment->amount();
866
+				}
867
+			}
868
+		}
869
+	}
870
+
871
+
872
+	/**
873
+	 *    _reset_selected_method_of_payment
874
+	 *
875
+	 * @access    private
876
+	 * @param    bool $force_reset
877
+	 * @return    void
878
+	 */
879
+	private function _reset_selected_method_of_payment($force_reset = false)
880
+	{
881
+		$reset_payment_method = $force_reset
882
+			? true
883
+			: sanitize_text_field(EE_Registry::instance()->REQ->get('reset_payment_method', false));
884
+		if ($reset_payment_method) {
885
+			$this->checkout->selected_method_of_payment = null;
886
+			$this->checkout->payment_method             = null;
887
+			$this->checkout->billing_form               = null;
888
+			$this->_save_selected_method_of_payment();
889
+		}
890
+	}
891
+
892
+
893
+	/**
894
+	 * _save_selected_method_of_payment
895
+	 * stores the selected_method_of_payment in the session
896
+	 * so that it's available for all subsequent requests including AJAX
897
+	 *
898
+	 * @access        private
899
+	 * @param string $selected_method_of_payment
900
+	 * @return  void
901
+	 */
902
+	private function _save_selected_method_of_payment($selected_method_of_payment = '')
903
+	{
904
+		$selected_method_of_payment = ! empty($selected_method_of_payment)
905
+			? $selected_method_of_payment
906
+			: $this->checkout->selected_method_of_payment;
907
+		EE_Registry::instance()->SSN->set_session_data(
908
+			array('selected_method_of_payment' => $selected_method_of_payment)
909
+		);
910
+	}
911
+
912
+
913
+	/**
914
+	 * _setup_payment_options
915
+	 *
916
+	 * @return \EE_Form_Section_Proper
917
+	 * @throws \EE_Error
918
+	 */
919
+	public function _setup_payment_options()
920
+	{
921
+		// load payment method classes
922
+		$this->checkout->available_payment_methods = $this->_get_available_payment_methods();
923
+		// switch up header depending on number of available payment methods
924
+		$payment_method_header     = count($this->checkout->available_payment_methods) > 1
925
+			? apply_filters(
926
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
927
+				__('Please Select Your Method of Payment', 'event_espresso')
928
+			)
929
+			: apply_filters(
930
+				'FHEE__registration_page_payment_options__method_of_payment_hdr',
931
+				__('Method of Payment', 'event_espresso')
932
+			);
933
+		$available_payment_methods = array(
934
+			// display the "Payment Method" header
935
+			'payment_method_header' => new EE_Form_Section_HTML(
936
+				EEH_HTML::h4($payment_method_header, 'method-of-payment-hdr')
937
+			),
938
+		);
939
+		// the list of actual payment methods ( invoice, paypal, etc ) in a  ( slug => HTML )  format
940
+		$available_payment_method_options = array();
941
+		$default_payment_method_option    = array();
942
+		// additional instructions to be displayed and hidden below payment methods (adding a clearing div to start)
943
+		$payment_methods_billing_info = array(
944
+			new EE_Form_Section_HTML(
945
+				EEH_HTML::div('<br />', '', '', 'clear:both;')
946
+			),
947
+		);
948
+		// loop through payment methods
949
+		foreach ($this->checkout->available_payment_methods as $payment_method) {
950
+			if ($payment_method instanceof EE_Payment_Method) {
951
+				$payment_method_button = EEH_HTML::img(
952
+					$payment_method->button_url(),
953
+					$payment_method->name(),
954
+					'spco-payment-method-' . $payment_method->slug() . '-btn-img',
955
+					'spco-payment-method-btn-img'
956
+				);
957
+				// check if any payment methods are set as default
958
+				// if payment method is already selected OR nothing is selected and this payment method should be open_by_default
959
+				if (
960
+					($this->checkout->selected_method_of_payment === $payment_method->slug())
961
+					|| (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
962
+				) {
963
+					$this->checkout->selected_method_of_payment = $payment_method->slug();
964
+					$this->_save_selected_method_of_payment();
965
+					$default_payment_method_option[$payment_method->slug()] = $payment_method_button;
966
+				} else {
967
+					$available_payment_method_options[$payment_method->slug()] = $payment_method_button;
968
+				}
969
+				$payment_methods_billing_info[$payment_method->slug()
970
+											  . '-info'] = $this->_payment_method_billing_info(
971
+					$payment_method
972
+				);
973
+			}
974
+		}
975
+		// prepend available_payment_method_options with default_payment_method_option so that it appears first in list of PMs
976
+		$available_payment_method_options = $default_payment_method_option + $available_payment_method_options;
977
+		// now generate the actual form  inputs
978
+		$available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
979
+			$available_payment_method_options
980
+		);
981
+		$available_payment_methods                              += $payment_methods_billing_info;
982
+		// build the available payment methods form
983
+		return new EE_Form_Section_Proper(
984
+			array(
985
+				'html_id'         => 'spco-available-methods-of-payment-dv',
986
+				'subsections'     => $available_payment_methods,
987
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
988
+			)
989
+		);
990
+	}
991
+
992
+
993
+	/**
994
+	 * _get_available_payment_methods
995
+	 *
996
+	 * @return EE_Payment_Method[]
997
+	 */
998
+	protected function _get_available_payment_methods()
999
+	{
1000
+		if (! empty($this->checkout->available_payment_methods)) {
1001
+			return $this->checkout->available_payment_methods;
1002
+		}
1003
+		$available_payment_methods = array();
1004
+		// load EEM_Payment_Method
1005
+		EE_Registry::instance()->load_model('Payment_Method');
1006
+		/** @type EEM_Payment_Method $EEM_Payment_Method */
1007
+		$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
1008
+		// get all active payment methods
1009
+		$payment_methods = $EEM_Payment_Method->get_all_for_transaction(
1010
+			$this->checkout->transaction,
1011
+			EEM_Payment_Method::scope_cart
1012
+		);
1013
+		foreach ($payment_methods as $payment_method) {
1014
+			if ($payment_method instanceof EE_Payment_Method) {
1015
+				$available_payment_methods[$payment_method->slug()] = $payment_method;
1016
+			}
1017
+		}
1018
+		return $available_payment_methods;
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 *    _available_payment_method_inputs
1024
+	 *
1025
+	 * @access    private
1026
+	 * @param    array $available_payment_method_options
1027
+	 * @return    \EE_Form_Section_Proper
1028
+	 */
1029
+	private function _available_payment_method_inputs($available_payment_method_options = array())
1030
+	{
1031
+		// generate inputs
1032
+		return new EE_Form_Section_Proper(
1033
+			array(
1034
+				'html_id'         => 'ee-available-payment-method-inputs',
1035
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1036
+				'subsections'     => array(
1037
+					'' => new EE_Radio_Button_Input (
1038
+						$available_payment_method_options,
1039
+						array(
1040
+							'html_name'          => 'selected_method_of_payment',
1041
+							'html_class'         => 'spco-payment-method',
1042
+							'default'            => $this->checkout->selected_method_of_payment,
1043
+							'label_size'         => 11,
1044
+							'enforce_label_size' => true,
1045
+						)
1046
+					),
1047
+				),
1048
+			)
1049
+		);
1050
+	}
1051
+
1052
+
1053
+	/**
1054
+	 *    _payment_method_billing_info
1055
+	 *
1056
+	 * @access    private
1057
+	 * @param    EE_Payment_Method $payment_method
1058
+	 * @return    \EE_Form_Section_Proper
1059
+	 * @throws \EE_Error
1060
+	 */
1061
+	private function _payment_method_billing_info(EE_Payment_Method $payment_method)
1062
+	{
1063
+		$currently_selected = $this->checkout->selected_method_of_payment === $payment_method->slug()
1064
+			? true
1065
+			: false;
1066
+		// generate the billing form for payment method
1067
+		$billing_form                 = $currently_selected
1068
+			? $this->_get_billing_form_for_payment_method($payment_method)
1069
+			: new EE_Form_Section_HTML();
1070
+		$this->checkout->billing_form = $currently_selected
1071
+			? $billing_form
1072
+			: $this->checkout->billing_form;
1073
+		// it's all in the details
1074
+		$info_html = EEH_HTML::h3(
1075
+			__('Important information regarding your payment', 'event_espresso'),
1076
+			'',
1077
+			'spco-payment-method-hdr'
1078
+		);
1079
+		// add some info regarding the step, either from what's saved in the admin,
1080
+		// or a default string depending on whether the PM has a billing form or not
1081
+		if ($payment_method->description()) {
1082
+			$payment_method_info = $payment_method->description();
1083
+		} elseif ($billing_form instanceof EE_Billing_Info_Form) {
1084
+			$payment_method_info = sprintf(
1085
+				__(
1086
+					'Please provide the following billing information, then click the "%1$s" button below in order to proceed.',
1087
+					'event_espresso'
1088
+				),
1089
+				$this->submit_button_text()
1090
+			);
1091
+		} else {
1092
+			$payment_method_info = sprintf(
1093
+				__('Please click the "%1$s" button below in order to proceed.', 'event_espresso'),
1094
+				$this->submit_button_text()
1095
+			);
1096
+		}
1097
+		$info_html .= EEH_HTML::p(
1098
+			apply_filters(
1099
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___payment_method_billing_info__payment_method_info',
1100
+				$payment_method_info
1101
+			),
1102
+			'',
1103
+			'spco-payment-method-desc ee-attention'
1104
+		);
1105
+		return new EE_Form_Section_Proper(
1106
+			array(
1107
+				'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1108
+				'html_class'      => 'spco-payment-method-info-dv',
1109
+				// only display the selected or default PM
1110
+				'html_style'      => $currently_selected ? '' : 'display:none;',
1111
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1112
+				'subsections'     => array(
1113
+					'info'         => new EE_Form_Section_HTML($info_html),
1114
+					'billing_form' => $currently_selected ? $billing_form : new EE_Form_Section_HTML(),
1115
+				),
1116
+			)
1117
+		);
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * get_billing_form_html_for_payment_method
1123
+	 *
1124
+	 * @access public
1125
+	 * @return string
1126
+	 * @throws \EE_Error
1127
+	 */
1128
+	public function get_billing_form_html_for_payment_method()
1129
+	{
1130
+		// how have they chosen to pay?
1131
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1132
+		$this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1133
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1134
+			return false;
1135
+		}
1136
+		if (apply_filters(
1137
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1138
+			false
1139
+		)) {
1140
+			EE_Error::add_success(
1141
+				apply_filters(
1142
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1143
+					sprintf(
1144
+						__(
1145
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1146
+							'event_espresso'
1147
+						),
1148
+						$this->checkout->payment_method->name()
1149
+					)
1150
+				)
1151
+			);
1152
+		}
1153
+		// now generate billing form for selected method of payment
1154
+		$payment_method_billing_form = $this->_get_billing_form_for_payment_method($this->checkout->payment_method);
1155
+		// fill form with attendee info if applicable
1156
+		if (
1157
+			$payment_method_billing_form instanceof EE_Billing_Attendee_Info_Form
1158
+			&& $this->checkout->transaction_has_primary_registrant()
1159
+		) {
1160
+			$payment_method_billing_form->populate_from_attendee(
1161
+				$this->checkout->transaction->primary_registration()->attendee()
1162
+			);
1163
+		}
1164
+		// and debug content
1165
+		if (
1166
+			$payment_method_billing_form instanceof EE_Billing_Info_Form
1167
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1168
+		) {
1169
+			$payment_method_billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1170
+				$payment_method_billing_form
1171
+			);
1172
+		}
1173
+		$billing_info = $payment_method_billing_form instanceof EE_Form_Section_Proper
1174
+			? $payment_method_billing_form->get_html()
1175
+			: '';
1176
+		$this->checkout->json_response->set_return_data(array('payment_method_info' => $billing_info));
1177
+		// localize validation rules for main form
1178
+		$this->checkout->current_step->reg_form->localize_validation_rules();
1179
+		$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1180
+		return true;
1181
+	}
1182
+
1183
+
1184
+	/**
1185
+	 * _get_billing_form_for_payment_method
1186
+	 *
1187
+	 * @access private
1188
+	 * @param EE_Payment_Method $payment_method
1189
+	 * @return \EE_Billing_Info_Form|\EE_Form_Section_HTML
1190
+	 * @throws \EE_Error
1191
+	 */
1192
+	private function _get_billing_form_for_payment_method(EE_Payment_Method $payment_method)
1193
+	{
1194
+		$billing_form = $payment_method->type_obj()->billing_form(
1195
+			$this->checkout->transaction,
1196
+			array('amount_owing' => $this->checkout->amount_owing)
1197
+		);
1198
+		if ($billing_form instanceof EE_Billing_Info_Form) {
1199
+			if (
1200
+				apply_filters(
1201
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1202
+					false
1203
+				)
1204
+				&& EE_Registry::instance()->REQ->is_set('payment_method')
1205
+			) {
1206
+				EE_Error::add_success(
1207
+					apply_filters(
1208
+						'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1209
+						sprintf(
1210
+							__(
1211
+								'You have selected "%s" as your method of payment. Please note the important payment information below.',
1212
+								'event_espresso'
1213
+							),
1214
+							$payment_method->name()
1215
+						)
1216
+					)
1217
+				);
1218
+			}
1219
+			return apply_filters(
1220
+				'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
1221
+				$billing_form,
1222
+				$payment_method
1223
+			);
1224
+		}
1225
+		// no actual billing form, so return empty HTML form section
1226
+		return new EE_Form_Section_HTML();
1227
+	}
1228
+
1229
+
1230
+	/**
1231
+	 * _get_selected_method_of_payment
1232
+	 *
1233
+	 * @access private
1234
+	 * @param boolean $required whether to throw an error if the "selected_method_of_payment"
1235
+	 *                          is not found in the incoming request
1236
+	 * @param string  $request_param
1237
+	 * @return NULL|string
1238
+	 * @throws \EE_Error
1239
+	 */
1240
+	private function _get_selected_method_of_payment(
1241
+		$required = false,
1242
+		$request_param = 'selected_method_of_payment'
1243
+	) {
1244
+		// is selected_method_of_payment set in the request ?
1245
+		$selected_method_of_payment = EE_Registry::instance()->REQ->get($request_param, false);
1246
+		if ($selected_method_of_payment) {
1247
+			// sanitize it
1248
+			$selected_method_of_payment = is_array($selected_method_of_payment)
1249
+				? array_shift($selected_method_of_payment)
1250
+				: $selected_method_of_payment;
1251
+			$selected_method_of_payment = sanitize_text_field($selected_method_of_payment);
1252
+			// store it in the session so that it's available for all subsequent requests including AJAX
1253
+			$this->_save_selected_method_of_payment($selected_method_of_payment);
1254
+		} else {
1255
+			// or is is set in the session ?
1256
+			$selected_method_of_payment = EE_Registry::instance()->SSN->get_session_data(
1257
+				'selected_method_of_payment'
1258
+			);
1259
+		}
1260
+		// do ya really really gotta have it?
1261
+		if (empty($selected_method_of_payment) && $required) {
1262
+			EE_Error::add_error(
1263
+				sprintf(
1264
+					__(
1265
+						'The selected method of payment could not be determined.%sPlease ensure that you have selected one before proceeding.%sIf you continue to experience difficulties, then refresh your browser and try again, or contact %s for assistance.',
1266
+						'event_espresso'
1267
+					),
1268
+					'<br/>',
1269
+					'<br/>',
1270
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1271
+				),
1272
+				__FILE__,
1273
+				__FUNCTION__,
1274
+				__LINE__
1275
+			);
1276
+			return null;
1277
+		}
1278
+		return $selected_method_of_payment;
1279
+	}
1280
+
1281
+
1282
+
1283
+
1284
+
1285
+
1286
+	/********************************************************************************************************/
1287
+	/***********************************  SWITCH PAYMENT METHOD  ************************************/
1288
+	/********************************************************************************************************/
1289
+	/**
1290
+	 * switch_payment_method
1291
+	 *
1292
+	 * @access public
1293
+	 * @return string
1294
+	 * @throws \EE_Error
1295
+	 */
1296
+	public function switch_payment_method()
1297
+	{
1298
+		if (! $this->_verify_payment_method_is_set()) {
1299
+			return false;
1300
+		}
1301
+		if (apply_filters(
1302
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options__registration_checkout__selected_payment_method__display_success',
1303
+			false
1304
+		)) {
1305
+			EE_Error::add_success(
1306
+				apply_filters(
1307
+					'FHEE__Single_Page_Checkout__registration_checkout__selected_payment_method',
1308
+					sprintf(
1309
+						__(
1310
+							'You have selected "%s" as your method of payment. Please note the important payment information below.',
1311
+							'event_espresso'
1312
+						),
1313
+						$this->checkout->payment_method->name()
1314
+					)
1315
+				)
1316
+			);
1317
+		}
1318
+		// generate billing form for selected method of payment if it hasn't been done already
1319
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1320
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1321
+				$this->checkout->payment_method
1322
+			);
1323
+		}
1324
+		// fill form with attendee info if applicable
1325
+		if (
1326
+		apply_filters(
1327
+			'FHEE__populate_billing_form_fields_from_attendee',
1328
+			(
1329
+				$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1330
+				&& $this->checkout->transaction_has_primary_registrant()
1331
+			),
1332
+			$this->checkout->billing_form,
1333
+			$this->checkout->transaction
1334
+		)
1335
+		) {
1336
+			$this->checkout->billing_form->populate_from_attendee(
1337
+				$this->checkout->transaction->primary_registration()->attendee()
1338
+			);
1339
+		}
1340
+		// and debug content
1341
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form
1342
+			&& $this->checkout->payment_method->type_obj() instanceof EE_PMT_Base
1343
+		) {
1344
+			$this->checkout->billing_form = $this->checkout->payment_method->type_obj()->apply_billing_form_debug_settings(
1345
+				$this->checkout->billing_form
1346
+			);
1347
+		}
1348
+		// get html and validation rules for form
1349
+		if ($this->checkout->billing_form instanceof EE_Form_Section_Proper) {
1350
+			$this->checkout->json_response->set_return_data(
1351
+				array('payment_method_info' => $this->checkout->billing_form->get_html())
1352
+			);
1353
+			// localize validation rules for main form
1354
+			$this->checkout->billing_form->localize_validation_rules(true);
1355
+			$this->checkout->json_response->add_validation_rules(EE_Form_Section_Proper::js_localization());
1356
+		} else {
1357
+			$this->checkout->json_response->set_return_data(array('payment_method_info' => ''));
1358
+		}
1359
+		//prevents advancement to next step
1360
+		$this->checkout->continue_reg = false;
1361
+		return true;
1362
+	}
1363
+
1364
+
1365
+	/**
1366
+	 * _verify_payment_method_is_set
1367
+	 *
1368
+	 * @return boolean
1369
+	 * @throws \EE_Error
1370
+	 */
1371
+	protected function _verify_payment_method_is_set()
1372
+	{
1373
+		// generate billing form for selected method of payment if it hasn't been done already
1374
+		if (empty($this->checkout->selected_method_of_payment)) {
1375
+			// how have they chosen to pay?
1376
+			$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1377
+		} else {
1378
+			// choose your own adventure based on method_of_payment
1379
+			switch ($this->checkout->selected_method_of_payment) {
1380
+				case 'events_sold_out' :
1381
+					EE_Error::add_attention(
1382
+						apply_filters(
1383
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__sold_out_events_msg',
1384
+							__('It appears that the event you were about to make a payment for has sold out since this form first loaded. Please contact the event administrator if you believe this is an error.',
1385
+								'event_espresso')
1386
+						),
1387
+						__FILE__, __FUNCTION__, __LINE__
1388
+					);
1389
+					return false;
1390
+					break;
1391
+				case 'payments_closed' :
1392
+					EE_Error::add_attention(
1393
+						apply_filters(
1394
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__payments_closed_msg',
1395
+							__('It appears that the event you were about to make a payment for is not accepting payments at this time. Please contact the event administrator if you believe this is an error.',
1396
+								'event_espresso')
1397
+						),
1398
+						__FILE__, __FUNCTION__, __LINE__
1399
+					);
1400
+					return false;
1401
+					break;
1402
+				case 'no_payment_required' :
1403
+					EE_Error::add_attention(
1404
+						apply_filters(
1405
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___verify_payment_method_is_set__no_payment_required_msg',
1406
+							__('It appears that the event you were about to make a payment for does not require payment. Please contact the event administrator if you believe this is an error.',
1407
+								'event_espresso')
1408
+						),
1409
+						__FILE__, __FUNCTION__, __LINE__
1410
+					);
1411
+					return false;
1412
+					break;
1413
+				default:
1414
+			}
1415
+		}
1416
+		// verify payment method
1417
+		if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1418
+			// get payment method for selected method of payment
1419
+			$this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1420
+		}
1421
+		return $this->checkout->payment_method instanceof EE_Payment_Method ? true : false;
1422
+	}
1423
+
1424
+
1425
+
1426
+	/********************************************************************************************************/
1427
+	/***************************************  SAVE PAYER DETAILS  ****************************************/
1428
+	/********************************************************************************************************/
1429
+	/**
1430
+	 * save_payer_details_via_ajax
1431
+	 *
1432
+	 * @return void
1433
+	 * @throws \EE_Error
1434
+	 */
1435
+	public function save_payer_details_via_ajax()
1436
+	{
1437
+		if (! $this->_verify_payment_method_is_set()) {
1438
+			return;
1439
+		}
1440
+		// generate billing form for selected method of payment if it hasn't been done already
1441
+		if ($this->checkout->payment_method->type_obj()->has_billing_form()) {
1442
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1443
+				$this->checkout->payment_method
1444
+			);
1445
+		}
1446
+		// generate primary attendee from payer info if applicable
1447
+		if (! $this->checkout->transaction_has_primary_registrant()) {
1448
+			$attendee = $this->_create_attendee_from_request_data();
1449
+			if ($attendee instanceof EE_Attendee) {
1450
+				foreach ($this->checkout->transaction->registrations() as $registration) {
1451
+					if ($registration->is_primary_registrant()) {
1452
+						$this->checkout->primary_attendee_obj = $attendee;
1453
+						$registration->_add_relation_to($attendee, 'Attendee');
1454
+						$registration->set_attendee_id($attendee->ID());
1455
+						$registration->update_cache_after_object_save('Attendee', $attendee);
1456
+					}
1457
+				}
1458
+			}
1459
+		}
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * create_attendee_from_request_data
1465
+	 * uses info from alternate GET or POST data (such as AJAX) to create a new attendee
1466
+	 *
1467
+	 * @return \EE_Attendee
1468
+	 * @throws \EE_Error
1469
+	 */
1470
+	protected function _create_attendee_from_request_data()
1471
+	{
1472
+		// get State ID
1473
+		$STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1474
+		if (! empty($STA_ID)) {
1475
+			// can we get state object from name ?
1476
+			EE_Registry::instance()->load_model('State');
1477
+			$state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
1478
+			$STA_ID = is_array($state) && ! empty($state) ? reset($state) : $STA_ID;
1479
+		}
1480
+		// get Country ISO
1481
+		$CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1482
+		if (! empty($CNT_ISO)) {
1483
+			// can we get country object from name ?
1484
+			EE_Registry::instance()->load_model('Country');
1485
+			$country = EEM_Country::instance()->get_col(
1486
+				array(array('CNT_name' => $CNT_ISO), 'limit' => 1),
1487
+				'CNT_ISO'
1488
+			);
1489
+			$CNT_ISO = is_array($country) && ! empty($country) ? reset($country) : $CNT_ISO;
1490
+		}
1491
+		// grab attendee data
1492
+		$attendee_data = array(
1493
+			'ATT_fname'    => ! empty($_REQUEST['first_name']) ? sanitize_text_field($_REQUEST['first_name']) : '',
1494
+			'ATT_lname'    => ! empty($_REQUEST['last_name']) ? sanitize_text_field($_REQUEST['last_name']) : '',
1495
+			'ATT_email'    => ! empty($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '',
1496
+			'ATT_address'  => ! empty($_REQUEST['address']) ? sanitize_text_field($_REQUEST['address']) : '',
1497
+			'ATT_address2' => ! empty($_REQUEST['address2']) ? sanitize_text_field($_REQUEST['address2']) : '',
1498
+			'ATT_city'     => ! empty($_REQUEST['city']) ? sanitize_text_field($_REQUEST['city']) : '',
1499
+			'STA_ID'       => $STA_ID,
1500
+			'CNT_ISO'      => $CNT_ISO,
1501
+			'ATT_zip'      => ! empty($_REQUEST['zip']) ? sanitize_text_field($_REQUEST['zip']) : '',
1502
+			'ATT_phone'    => ! empty($_REQUEST['phone']) ? sanitize_text_field($_REQUEST['phone']) : '',
1503
+		);
1504
+		// validate the email address since it is the most important piece of info
1505
+		if (empty($attendee_data['ATT_email']) || $attendee_data['ATT_email'] !== $_REQUEST['email']) {
1506
+			EE_Error::add_error(
1507
+				__('An invalid email address was submitted.', 'event_espresso'),
1508
+				__FILE__,
1509
+				__FUNCTION__,
1510
+				__LINE__
1511
+			);
1512
+		}
1513
+		// does this attendee already exist in the db ? we're searching using a combination of first name, last name, AND email address
1514
+		if (! empty($attendee_data['ATT_fname'])
1515
+			&& ! empty($attendee_data['ATT_lname'])
1516
+			&& ! empty($attendee_data['ATT_email'])
1517
+		) {
1518
+			$existing_attendee = EE_Registry::instance()->LIB->EEM_Attendee->find_existing_attendee(
1519
+				array(
1520
+					'ATT_fname' => $attendee_data['ATT_fname'],
1521
+					'ATT_lname' => $attendee_data['ATT_lname'],
1522
+					'ATT_email' => $attendee_data['ATT_email'],
1523
+				)
1524
+			);
1525
+			if ($existing_attendee instanceof EE_Attendee) {
1526
+				return $existing_attendee;
1527
+			}
1528
+		}
1529
+		// no existing attendee? kk let's create a new one
1530
+		// kinda lame, but we need a first and last name to create an attendee, so use the email address if those don't exist
1531
+		$attendee_data['ATT_fname'] = ! empty($attendee_data['ATT_fname'])
1532
+			? $attendee_data['ATT_fname']
1533
+			: $attendee_data['ATT_email'];
1534
+		$attendee_data['ATT_lname'] = ! empty($attendee_data['ATT_lname'])
1535
+			? $attendee_data['ATT_lname']
1536
+			: $attendee_data['ATT_email'];
1537
+		return EE_Attendee::new_instance($attendee_data);
1538
+	}
1539
+
1540
+
1541
+
1542
+	/********************************************************************************************************/
1543
+	/****************************************  PROCESS REG STEP  *****************************************/
1544
+	/********************************************************************************************************/
1545
+	/**
1546
+	 * process_reg_step
1547
+	 *
1548
+	 * @return boolean
1549
+	 * @throws \EE_Error
1550
+	 */
1551
+	public function process_reg_step()
1552
+	{
1553
+		// how have they chosen to pay?
1554
+		$this->checkout->selected_method_of_payment = $this->checkout->transaction->is_free()
1555
+			? 'no_payment_required'
1556
+			: $this->_get_selected_method_of_payment(true);
1557
+		// choose your own adventure based on method_of_payment
1558
+		switch ($this->checkout->selected_method_of_payment) {
1559
+
1560
+			case 'events_sold_out' :
1561
+				$this->checkout->redirect     = true;
1562
+				$this->checkout->redirect_url = $this->checkout->cancel_page_url;
1563
+				$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1564
+				// mark this reg step as completed
1565
+				$this->set_completed();
1566
+				return false;
1567
+				break;
1568
+
1569
+			case 'payments_closed' :
1570
+				if (apply_filters(
1571
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__payments_closed__display_success',
1572
+					false
1573
+				)) {
1574
+					EE_Error::add_success(
1575
+						__('no payment required at this time.', 'event_espresso'),
1576
+						__FILE__,
1577
+						__FUNCTION__,
1578
+						__LINE__
1579
+					);
1580
+				}
1581
+				// mark this reg step as completed
1582
+				$this->set_completed();
1583
+				return true;
1584
+				break;
1585
+
1586
+			case 'no_payment_required' :
1587
+				if (apply_filters(
1588
+					'FHEE__EE_SPCO_Reg_Step_Payment_Options__process_reg_step__no_payment_required__display_success',
1589
+					false
1590
+				)) {
1591
+					EE_Error::add_success(
1592
+						__('no payment required.', 'event_espresso'),
1593
+						__FILE__,
1594
+						__FUNCTION__,
1595
+						__LINE__
1596
+					);
1597
+				}
1598
+				// mark this reg step as completed
1599
+				$this->set_completed();
1600
+				return true;
1601
+				break;
1602
+
1603
+			default:
1604
+				$registrations         = EE_Registry::instance()->SSN->checkout()->transaction->registrations(
1605
+					EE_Registry::instance()->SSN->checkout()->reg_cache_where_params
1606
+				);
1607
+				$ejected_registrations = EE_SPCO_Reg_Step_Payment_Options::find_registrations_that_lost_their_space(
1608
+					$registrations,
1609
+					EE_Registry::instance()->SSN->checkout()->revisit
1610
+				);
1611
+				// calculate difference between the two arrays
1612
+				$registrations = array_diff($registrations, $ejected_registrations);
1613
+				if (empty($registrations)) {
1614
+					$this->_redirect_because_event_sold_out();
1615
+					return false;
1616
+				}
1617
+				$payment_successful = $this->_process_payment();
1618
+				if ($payment_successful) {
1619
+					$this->checkout->continue_reg = true;
1620
+					$this->_maybe_set_completed($this->checkout->payment_method);
1621
+				} else {
1622
+					$this->checkout->continue_reg = false;
1623
+				}
1624
+				return $payment_successful;
1625
+
1626
+		}
1627
+	}
1628
+
1629
+
1630
+	/**
1631
+	 * _redirect_because_event_sold_out
1632
+	 *
1633
+	 * @access protected
1634
+	 * @return void
1635
+	 */
1636
+	protected function _redirect_because_event_sold_out()
1637
+	{
1638
+		$this->checkout->continue_reg = false;
1639
+		// set redirect URL
1640
+		$this->checkout->redirect_url = add_query_arg(
1641
+			array('e_reg_url_link' => $this->checkout->reg_url_link),
1642
+			$this->checkout->current_step->reg_step_url()
1643
+		);
1644
+		$this->checkout->json_response->set_redirect_url($this->checkout->redirect_url);
1645
+	}
1646
+
1647
+
1648
+	/**
1649
+	 * _maybe_set_completed
1650
+	 *
1651
+	 * @access protected
1652
+	 * @param \EE_Payment_Method $payment_method
1653
+	 * @return void
1654
+	 * @throws \EE_Error
1655
+	 */
1656
+	protected function _maybe_set_completed(EE_Payment_Method $payment_method)
1657
+	{
1658
+		switch ($payment_method->type_obj()->payment_occurs()) {
1659
+			case EE_PMT_Base::offsite :
1660
+				break;
1661
+			case EE_PMT_Base::onsite :
1662
+			case EE_PMT_Base::offline :
1663
+				// mark this reg step as completed
1664
+				$this->set_completed();
1665
+				break;
1666
+		}
1667
+	}
1668
+
1669
+
1670
+	/**
1671
+	 *    update_reg_step
1672
+	 *    this is the final step after a user  revisits the site to retry a payment
1673
+	 *
1674
+	 * @return boolean
1675
+	 * @throws \EE_Error
1676
+	 */
1677
+	public function update_reg_step()
1678
+	{
1679
+		$success = true;
1680
+		// if payment required
1681
+		if ($this->checkout->transaction->total() > 0) {
1682
+			do_action(
1683
+				'AHEE__EE_Single_Page_Checkout__process_finalize_registration__before_gateway',
1684
+				$this->checkout->transaction
1685
+			);
1686
+			// attempt payment via payment method
1687
+			$success = $this->process_reg_step();
1688
+		}
1689
+		if ($success && ! $this->checkout->redirect) {
1690
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn(
1691
+				$this->checkout->transaction->ID()
1692
+			);
1693
+			// set return URL
1694
+			$this->checkout->redirect_url = add_query_arg(
1695
+				array('e_reg_url_link' => $this->checkout->reg_url_link),
1696
+				$this->checkout->thank_you_page_url
1697
+			);
1698
+		}
1699
+		return $success;
1700
+	}
1701
+
1702
+
1703
+	/**
1704
+	 *    _process_payment
1705
+	 *
1706
+	 * @access private
1707
+	 * @return    bool
1708
+	 * @throws \EE_Error
1709
+	 */
1710
+	private function _process_payment()
1711
+	{
1712
+		// basically confirm that the event hasn't sold out since they hit the page
1713
+		if (! $this->_last_second_ticket_verifications()) {
1714
+			return false;
1715
+		}
1716
+		// ya gotta make a choice man
1717
+		if (empty($this->checkout->selected_method_of_payment)) {
1718
+			$this->checkout->json_response->set_plz_select_method_of_payment(
1719
+				__('Please select a method of payment before proceeding.', 'event_espresso')
1720
+			);
1721
+			return false;
1722
+		}
1723
+		// get EE_Payment_Method object
1724
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1725
+			return false;
1726
+		}
1727
+		// setup billing form
1728
+		if ($this->checkout->payment_method->is_on_site()) {
1729
+			$this->checkout->billing_form = $this->_get_billing_form_for_payment_method(
1730
+				$this->checkout->payment_method
1731
+			);
1732
+			// bad billing form ?
1733
+			if (! $this->_billing_form_is_valid()) {
1734
+				return false;
1735
+			}
1736
+		}
1737
+		// ensure primary registrant has been fully processed
1738
+		if (! $this->_setup_primary_registrant_prior_to_payment()) {
1739
+			return false;
1740
+		}
1741
+		// if session is close to expiring (under 10 minutes by default)
1742
+		if ((time() - EE_Registry::instance()->SSN->expiration()) < EE_Registry::instance()->SSN->extension()) {
1743
+			// add some time to session expiration so that payment can be completed
1744
+			EE_Registry::instance()->SSN->extend_expiration();
1745
+		}
1746
+		/** @type EE_Transaction_Processor $transaction_processor */
1747
+		//$transaction_processor = EE_Registry::instance()->load_class( 'Transaction_Processor' );
1748
+		// in case a registrant leaves to an Off-Site Gateway and never returns, we want to approve any registrations for events with a default reg status of Approved
1749
+		//$transaction_processor->toggle_registration_statuses_for_default_approved_events( $this->checkout->transaction, $this->checkout->reg_cache_where_params );
1750
+		// attempt payment
1751
+		$payment = $this->_attempt_payment($this->checkout->payment_method);
1752
+		// process results
1753
+		$payment = $this->_validate_payment($payment);
1754
+		$payment = $this->_post_payment_processing($payment);
1755
+		// verify payment
1756
+		if ($payment instanceof EE_Payment) {
1757
+			// store that for later
1758
+			$this->checkout->payment = $payment;
1759
+			// we can also consider the TXN to not have been failed, so temporarily upgrade it's status to abandoned
1760
+			$this->checkout->transaction->toggle_failed_transaction_status();
1761
+			$payment_status = $payment->status();
1762
+			if (
1763
+				$payment_status === EEM_Payment::status_id_approved
1764
+				|| $payment_status === EEM_Payment::status_id_pending
1765
+			) {
1766
+				return true;
1767
+			} else {
1768
+				return false;
1769
+			}
1770
+		} else if ($payment === true) {
1771
+			// please note that offline payment methods will NOT make a payment,
1772
+			// but instead just mark themselves as the PMD_ID on the transaction, and return true
1773
+			$this->checkout->payment = $payment;
1774
+			return true;
1775
+		}
1776
+		// where's my money?
1777
+		return false;
1778
+	}
1779
+
1780
+
1781
+	/**
1782
+	 * _last_second_ticket_verifications
1783
+	 *
1784
+	 * @access public
1785
+	 * @return bool
1786
+	 */
1787
+	protected function _last_second_ticket_verifications()
1788
+	{
1789
+		// don't bother re-validating if not a return visit
1790
+		if (! $this->checkout->revisit) {
1791
+			return true;
1792
+		}
1793
+		$registrations = $this->checkout->transaction->registrations();
1794
+		if (empty($registrations)) {
1795
+			return false;
1796
+		}
1797
+		foreach ($registrations as $registration) {
1798
+			if ($registration instanceof EE_Registration) {
1799
+				$event = $registration->event_obj();
1800
+				if ($event instanceof EE_Event && $event->is_sold_out(true)) {
1801
+					EE_Error::add_error(
1802
+						apply_filters(
1803
+							'FHEE__EE_SPCO_Reg_Step_Payment_Options___last_second_ticket_verifications__sold_out_events_msg',
1804
+							sprintf(
1805
+								__('It appears that the %1$s event that you were about to make a payment for has sold out since you first registered and/or arrived at this page. Please refresh the page and try again. If you have already made a partial payment towards this event, please contact the event administrator for a refund.',
1806
+									'event_espresso'),
1807
+								$event->name()
1808
+							)
1809
+						),
1810
+						__FILE__,
1811
+						__FUNCTION__,
1812
+						__LINE__
1813
+					);
1814
+					return false;
1815
+				}
1816
+			}
1817
+		}
1818
+		return true;
1819
+	}
1820
+
1821
+
1822
+	/**
1823
+	 * redirect_form
1824
+	 *
1825
+	 * @access public
1826
+	 * @return bool
1827
+	 * @throws \EE_Error
1828
+	 */
1829
+	public function redirect_form()
1830
+	{
1831
+		$payment_method_billing_info = $this->_payment_method_billing_info(
1832
+			$this->_get_payment_method_for_selected_method_of_payment()
1833
+		);
1834
+		$html                        = $payment_method_billing_info->get_html();
1835
+		$html                        .= $this->checkout->redirect_form;
1836
+		EE_Registry::instance()->REQ->add_output($html);
1837
+		return true;
1838
+	}
1839
+
1840
+
1841
+	/**
1842
+	 * _billing_form_is_valid
1843
+	 *
1844
+	 * @access private
1845
+	 * @return bool
1846
+	 * @throws \EE_Error
1847
+	 */
1848
+	private function _billing_form_is_valid()
1849
+	{
1850
+		if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1851
+			return true;
1852
+		}
1853
+		if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
1854
+			if ($this->checkout->billing_form->was_submitted()) {
1855
+				$this->checkout->billing_form->receive_form_submission();
1856
+				if ($this->checkout->billing_form->is_valid()) {
1857
+					return true;
1858
+				}
1859
+				$validation_errors = $this->checkout->billing_form->get_validation_errors_accumulated();
1860
+				$error_strings     = array();
1861
+				foreach ($validation_errors as $validation_error) {
1862
+					if ($validation_error instanceof EE_Validation_Error) {
1863
+						$form_section = $validation_error->get_form_section();
1864
+						if ($form_section instanceof EE_Form_Input_Base) {
1865
+							$label = $form_section->html_label_text();
1866
+						} elseif ($form_section instanceof EE_Form_Section_Base) {
1867
+							$label = $form_section->name();
1868
+						} else {
1869
+							$label = __('Validation Error', 'event_espresso');
1870
+						}
1871
+						$error_strings[] = sprintf('%1$s: %2$s', $label, $validation_error->getMessage());
1872
+					}
1873
+				}
1874
+				EE_Error::add_error(
1875
+					sprintf(
1876
+						__(
1877
+							'One or more billing form inputs are invalid and require correction before proceeding. %1$s %2$s',
1878
+							'event_espresso'
1879
+						),
1880
+						'<br/>',
1881
+						implode('<br/>', $error_strings)
1882
+					),
1883
+					__FILE__,
1884
+					__FUNCTION__,
1885
+					__LINE__
1886
+				);
1887
+			} else {
1888
+				EE_Error::add_error(
1889
+					__(
1890
+						'The billing form was not submitted or something prevented it\'s submission.',
1891
+						'event_espresso'
1892
+					),
1893
+					__FILE__,
1894
+					__FUNCTION__,
1895
+					__LINE__
1896
+				);
1897
+			}
1898
+		} else {
1899
+			EE_Error::add_error(
1900
+				__('The submitted billing form is invalid possibly due to a technical reason.', 'event_espresso'),
1901
+				__FILE__,
1902
+				__FUNCTION__,
1903
+				__LINE__
1904
+			);
1905
+		}
1906
+		return false;
1907
+	}
1908
+
1909
+
1910
+	/**
1911
+	 * _setup_primary_registrant_prior_to_payment
1912
+	 * ensures that the primary registrant has a valid attendee object created with the critical details populated
1913
+	 * (first & last name & email) and that both the transaction object and primary registration object have been saved
1914
+	 * plz note that any other registrations will NOT be saved at this point (because they may not have any details
1915
+	 * yet)
1916
+	 *
1917
+	 * @access private
1918
+	 * @return bool
1919
+	 * @throws \EE_Error
1920
+	 */
1921
+	private function _setup_primary_registrant_prior_to_payment()
1922
+	{
1923
+		// check if transaction has a primary registrant and that it has a related Attendee object
1924
+		// if not, then we need to at least gather some primary registrant data before attempting payment
1925
+		if (
1926
+			$this->checkout->billing_form instanceof EE_Billing_Attendee_Info_Form
1927
+			&& ! $this->checkout->transaction_has_primary_registrant()
1928
+			&& ! $this->_capture_primary_registration_data_from_billing_form()
1929
+		) {
1930
+			return false;
1931
+		}
1932
+		// because saving an object clears it's cache, we need to do the chevy shuffle
1933
+		// grab the primary_registration object
1934
+		$primary_registration = $this->checkout->transaction->primary_registration();
1935
+		// at this point we'll consider a TXN to not have been failed
1936
+		$this->checkout->transaction->toggle_failed_transaction_status();
1937
+		// save the TXN ( which clears cached copy of primary_registration)
1938
+		$this->checkout->transaction->save();
1939
+		// grab TXN ID and save it to the primary_registration
1940
+		$primary_registration->set_transaction_id($this->checkout->transaction->ID());
1941
+		// save what we have so far
1942
+		$primary_registration->save();
1943
+		return true;
1944
+	}
1945
+
1946
+
1947
+	/**
1948
+	 * _capture_primary_registration_data_from_billing_form
1949
+	 *
1950
+	 * @access private
1951
+	 * @return bool
1952
+	 * @throws \EE_Error
1953
+	 */
1954
+	private function _capture_primary_registration_data_from_billing_form()
1955
+	{
1956
+		// convert billing form data into an attendee
1957
+		$this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
1958
+		if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
1959
+			EE_Error::add_error(
1960
+				sprintf(
1961
+					__(
1962
+						'The billing form details could not be used for attendee details due to a technical issue.%sPlease try again or contact %s for assistance.',
1963
+						'event_espresso'
1964
+					),
1965
+					'<br/>',
1966
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1967
+				),
1968
+				__FILE__,
1969
+				__FUNCTION__,
1970
+				__LINE__
1971
+			);
1972
+			return false;
1973
+		}
1974
+		$primary_registration = $this->checkout->transaction->primary_registration();
1975
+		if (! $primary_registration instanceof EE_Registration) {
1976
+			EE_Error::add_error(
1977
+				sprintf(
1978
+					__(
1979
+						'The primary registrant for this transaction could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
1980
+						'event_espresso'
1981
+					),
1982
+					'<br/>',
1983
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
1984
+				),
1985
+				__FILE__,
1986
+				__FUNCTION__,
1987
+				__LINE__
1988
+			);
1989
+			return false;
1990
+		}
1991
+		if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
1992
+			  instanceof
1993
+			  EE_Attendee
1994
+		) {
1995
+			EE_Error::add_error(
1996
+				sprintf(
1997
+					__(
1998
+						'The primary registrant could not be associated with this transaction due to a technical issue.%sPlease try again or contact %s for assistance.',
1999
+						'event_espresso'
2000
+					),
2001
+					'<br/>',
2002
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2003
+				),
2004
+				__FILE__,
2005
+				__FUNCTION__,
2006
+				__LINE__
2007
+			);
2008
+			return false;
2009
+		}
2010
+		/** @type EE_Registration_Processor $registration_processor */
2011
+		$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
2012
+		// at this point, we should have enough details about the registrant to consider the registration NOT incomplete
2013
+		$registration_processor->toggle_incomplete_registration_status_to_default($primary_registration);
2014
+		return true;
2015
+	}
2016
+
2017
+
2018
+	/**
2019
+	 * _get_payment_method_for_selected_method_of_payment
2020
+	 * retrieves a valid payment method
2021
+	 *
2022
+	 * @access public
2023
+	 * @return \EE_Payment_Method
2024
+	 * @throws \EE_Error
2025
+	 */
2026
+	private function _get_payment_method_for_selected_method_of_payment()
2027
+	{
2028
+		if ($this->checkout->selected_method_of_payment === 'events_sold_out') {
2029
+			$this->_redirect_because_event_sold_out();
2030
+			return null;
2031
+		}
2032
+		// get EE_Payment_Method object
2033
+		if (isset($this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment])) {
2034
+			$payment_method = $this->checkout->available_payment_methods[$this->checkout->selected_method_of_payment];
2035
+		} else {
2036
+			// load EEM_Payment_Method
2037
+			EE_Registry::instance()->load_model('Payment_Method');
2038
+			/** @type EEM_Payment_Method $EEM_Payment_Method */
2039
+			$EEM_Payment_Method = EE_Registry::instance()->LIB->EEM_Payment_Method;
2040
+			$payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2041
+		}
2042
+		// verify $payment_method
2043
+		if (! $payment_method instanceof EE_Payment_Method) {
2044
+			// not a payment
2045
+			EE_Error::add_error(
2046
+				sprintf(
2047
+					__(
2048
+						'The selected method of payment could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2049
+						'event_espresso'
2050
+					),
2051
+					'<br/>',
2052
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2053
+				),
2054
+				__FILE__,
2055
+				__FUNCTION__,
2056
+				__LINE__
2057
+			);
2058
+			return null;
2059
+		}
2060
+		// and verify it has a valid Payment_Method Type object
2061
+		if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2062
+			// not a payment
2063
+			EE_Error::add_error(
2064
+				sprintf(
2065
+					__(
2066
+						'A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.',
2067
+						'event_espresso'
2068
+					),
2069
+					'<br/>',
2070
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2071
+				),
2072
+				__FILE__,
2073
+				__FUNCTION__,
2074
+				__LINE__
2075
+			);
2076
+			return null;
2077
+		}
2078
+		return $payment_method;
2079
+	}
2080
+
2081
+
2082
+	/**
2083
+	 *    _attempt_payment
2084
+	 *
2085
+	 * @access    private
2086
+	 * @type    EE_Payment_Method $payment_method
2087
+	 * @return    mixed    EE_Payment | boolean
2088
+	 * @throws \EE_Error
2089
+	 */
2090
+	private function _attempt_payment(EE_Payment_Method $payment_method)
2091
+	{
2092
+		$payment = null;
2093
+		$this->checkout->transaction->save();
2094
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2095
+		if (! $payment_processor instanceof EE_Payment_Processor) {
2096
+			return false;
2097
+		}
2098
+		try {
2099
+			$payment_processor->set_revisit($this->checkout->revisit);
2100
+			// generate payment object
2101
+			$payment = $payment_processor->process_payment(
2102
+				$payment_method,
2103
+				$this->checkout->transaction,
2104
+				$this->checkout->amount_owing,
2105
+				$this->checkout->billing_form,
2106
+				$this->_get_return_url($payment_method),
2107
+				'CART',
2108
+				$this->checkout->admin_request,
2109
+				true,
2110
+				$this->reg_step_url()
2111
+			);
2112
+		} catch (Exception $e) {
2113
+			$this->_handle_payment_processor_exception($e);
2114
+		}
2115
+		return $payment;
2116
+	}
2117
+
2118
+
2119
+	/**
2120
+	 * _handle_payment_processor_exception
2121
+	 *
2122
+	 * @access protected
2123
+	 * @param \Exception $e
2124
+	 * @return void
2125
+	 * @throws \EE_Error
2126
+	 */
2127
+	protected function _handle_payment_processor_exception(Exception $e)
2128
+	{
2129
+		EE_Error::add_error(
2130
+			sprintf(
2131
+				__(
2132
+					'The payment could not br processed due to a technical issue.%1$sPlease try again or contact %2$s for assistance.||The following Exception was thrown in %4$s on line %5$s:%1$s%3$s',
2133
+					'event_espresso'
2134
+				),
2135
+				'<br/>',
2136
+				EE_Registry::instance()->CFG->organization->get_pretty('email'),
2137
+				$e->getMessage(),
2138
+				$e->getFile(),
2139
+				$e->getLine()
2140
+			),
2141
+			__FILE__,
2142
+			__FUNCTION__,
2143
+			__LINE__
2144
+		);
2145
+	}
2146
+
2147
+
2148
+	/**
2149
+	 * _get_return_url
2150
+	 *
2151
+	 * @access protected
2152
+	 * @param \EE_Payment_Method $payment_method
2153
+	 * @return string
2154
+	 * @throws \EE_Error
2155
+	 */
2156
+	protected function _get_return_url(EE_Payment_Method $payment_method)
2157
+	{
2158
+		$return_url = '';
2159
+		switch ($payment_method->type_obj()->payment_occurs()) {
2160
+			case EE_PMT_Base::offsite :
2161
+				$return_url = add_query_arg(
2162
+					array(
2163
+						'action'                     => 'process_gateway_response',
2164
+						'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2165
+						'spco_txn'                   => $this->checkout->transaction->ID(),
2166
+					),
2167
+					$this->reg_step_url()
2168
+				);
2169
+				break;
2170
+			case EE_PMT_Base::onsite :
2171
+			case EE_PMT_Base::offline :
2172
+				$return_url = $this->checkout->next_step->reg_step_url();
2173
+				break;
2174
+		}
2175
+		return $return_url;
2176
+	}
2177
+
2178
+
2179
+	/**
2180
+	 * _validate_payment
2181
+	 *
2182
+	 * @access private
2183
+	 * @param EE_Payment $payment
2184
+	 * @return EE_Payment | FALSE
2185
+	 * @throws \EE_Error
2186
+	 */
2187
+	private function _validate_payment($payment = null)
2188
+	{
2189
+		if ($this->checkout->payment_method->is_off_line()) {
2190
+			return true;
2191
+		}
2192
+		// verify payment object
2193
+		if (! $payment instanceof EE_Payment) {
2194
+			// not a payment
2195
+			EE_Error::add_error(
2196
+				sprintf(
2197
+					__(
2198
+						'A valid payment was not generated due to a technical issue.%1$sPlease try again or contact %2$s for assistance.',
2199
+						'event_espresso'
2200
+					),
2201
+					'<br/>',
2202
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2203
+				),
2204
+				__FILE__,
2205
+				__FUNCTION__,
2206
+				__LINE__
2207
+			);
2208
+			return false;
2209
+		}
2210
+		return $payment;
2211
+	}
2212
+
2213
+
2214
+	/**
2215
+	 * _post_payment_processing
2216
+	 *
2217
+	 * @access private
2218
+	 * @param EE_Payment|bool $payment
2219
+	 * @return bool
2220
+	 * @throws \EE_Error
2221
+	 */
2222
+	private function _post_payment_processing($payment = null)
2223
+	{
2224
+		// Off-Line payment?
2225
+		if ($payment === true) {
2226
+			//$this->_setup_redirect_for_next_step();
2227
+			return true;
2228
+			// On-Site payment?
2229
+		} else if ($this->checkout->payment_method->is_on_site()) {
2230
+			if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2231
+				//$this->_setup_redirect_for_next_step();
2232
+				$this->checkout->continue_reg = false;
2233
+			}
2234
+			// Off-Site payment?
2235
+		} else if ($this->checkout->payment_method->is_off_site()) {
2236
+			// if a payment object was made and it specifies a redirect url, then we'll setup that redirect info
2237
+			if ($payment instanceof EE_Payment && $payment->redirect_url()) {
2238
+				do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->redirect_url(), '$payment->redirect_url()');
2239
+				$this->checkout->redirect      = true;
2240
+				$this->checkout->redirect_form = $payment->redirect_form();
2241
+				$this->checkout->redirect_url  = $this->reg_step_url('redirect_form');
2242
+				// set JSON response
2243
+				$this->checkout->json_response->set_redirect_form($this->checkout->redirect_form);
2244
+				// set cron job for finalizing the TXN
2245
+				// in case the user does not return from the off-site gateway
2246
+				EE_Cron_Tasks::schedule_finalize_abandoned_transactions_check(
2247
+					EE_Registry::instance()->SSN->expiration() + 1,
2248
+					$this->checkout->transaction->ID()
2249
+				);
2250
+				// and lastly, let's bump the payment status to pending
2251
+				$payment->set_status(EEM_Payment::status_id_pending);
2252
+				$payment->save();
2253
+			} else {
2254
+				// not a payment
2255
+				$this->checkout->continue_reg = false;
2256
+				EE_Error::add_error(
2257
+					sprintf(
2258
+						__(
2259
+							'It appears the Off Site Payment Method was not configured properly.%sPlease try again or contact %s for assistance.',
2260
+							'event_espresso'
2261
+						),
2262
+						'<br/>',
2263
+						EE_Registry::instance()->CFG->organization->get_pretty('email')
2264
+					),
2265
+					__FILE__,
2266
+					__FUNCTION__,
2267
+					__LINE__
2268
+				);
2269
+			}
2270
+		} else {
2271
+			// ummm ya... not Off-Line, not On-Site, not off-Site ????
2272
+			$this->checkout->continue_reg = false;
2273
+			return false;
2274
+		}
2275
+		return $payment;
2276
+	}
2277
+
2278
+
2279
+
2280
+	/**
2281
+	 *    _setup_redirect_for_next_step
2282
+	 *
2283
+	 * @access private
2284
+	 * @return    void
2285
+	 */
2286
+	//private function _setup_redirect_for_next_step() {
2287
+	//$this->checkout->redirect = TRUE;
2288
+	//$this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
2289
+	// set JSON response
2290
+	//$this->checkout->json_response->set_redirect_url( $this->checkout->redirect_url );
2291
+	//}
2292
+	/**
2293
+	 *    _process_payment_status
2294
+	 *
2295
+	 * @access private
2296
+	 * @type    EE_Payment $payment
2297
+	 * @param string       $payment_occurs
2298
+	 * @return bool
2299
+	 * @throws \EE_Error
2300
+	 */
2301
+	private function _process_payment_status($payment, $payment_occurs = EE_PMT_Base::offline)
2302
+	{
2303
+		// off-line payment? carry on
2304
+		if ($payment_occurs === EE_PMT_Base::offline) {
2305
+			return true;
2306
+		}
2307
+		// verify payment validity
2308
+		if ($payment instanceof EE_Payment) {
2309
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $payment->status(), '$payment->status()');
2310
+			$msg = $payment->gateway_response();
2311
+			// check results
2312
+			switch ($payment->status()) {
2313
+				// good payment
2314
+				case EEM_Payment::status_id_approved :
2315
+					EE_Error::add_success(
2316
+						__('Your payment was processed successfully.', 'event_espresso'),
2317
+						__FILE__,
2318
+						__FUNCTION__,
2319
+						__LINE__
2320
+					);
2321
+					return true;
2322
+					break;
2323
+				// slow payment
2324
+				case EEM_Payment::status_id_pending :
2325
+					if (empty($msg)) {
2326
+						$msg = __(
2327
+							'Your payment appears to have been processed successfully, but the Instant Payment Notification has not yet been received. It should arrive shortly.',
2328
+							'event_espresso'
2329
+						);
2330
+					}
2331
+					EE_Error::add_success($msg, __FILE__, __FUNCTION__, __LINE__);
2332
+					return true;
2333
+					break;
2334
+				// don't wanna payment
2335
+				case EEM_Payment::status_id_cancelled :
2336
+					if (empty($msg)) {
2337
+						$msg = _n(
2338
+							'Payment cancelled. Please try again.',
2339
+							'Payment cancelled. Please try again or select another method of payment.',
2340
+							count($this->checkout->available_payment_methods),
2341
+							'event_espresso'
2342
+						);
2343
+					}
2344
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2345
+					return false;
2346
+					break;
2347
+				// not enough payment
2348
+				case EEM_Payment::status_id_declined :
2349
+					if (empty($msg)) {
2350
+						$msg = _n(
2351
+							'We\'re sorry but your payment was declined. Please try again.',
2352
+							'We\'re sorry but your payment was declined. Please try again or select another method of payment.',
2353
+							count($this->checkout->available_payment_methods),
2354
+							'event_espresso'
2355
+						);
2356
+					}
2357
+					EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
2358
+					return false;
2359
+					break;
2360
+				// bad payment
2361
+				case EEM_Payment::status_id_failed :
2362
+					if (! empty($msg)) {
2363
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2364
+						return false;
2365
+					}
2366
+					// default to error below
2367
+					break;
2368
+			}
2369
+		}
2370
+		// off-site payment gateway responses are too unreliable, so let's just assume that
2371
+		// the payment processing is just running slower than the registrant's request
2372
+		if ($payment_occurs === EE_PMT_Base::offsite) {
2373
+			return true;
2374
+		}
2375
+		EE_Error::add_error(
2376
+			sprintf(
2377
+				__(
2378
+					'Your payment could not be processed successfully due to a technical issue.%sPlease try again or contact %s for assistance.',
2379
+					'event_espresso'
2380
+				),
2381
+				'<br/>',
2382
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
2383
+			),
2384
+			__FILE__,
2385
+			__FUNCTION__,
2386
+			__LINE__
2387
+		);
2388
+		return false;
2389
+	}
2390
+
2391
+
2392
+
2393
+
2394
+
2395
+
2396
+	/********************************************************************************************************/
2397
+	/**********************************  PROCESS GATEWAY RESPONSE  **********************************/
2398
+	/********************************************************************************************************/
2399
+	/**
2400
+	 * process_gateway_response
2401
+	 * this is the return point for Off-Site Payment Methods
2402
+	 * It will attempt to "handle the IPN" if it appears that this has not already occurred,
2403
+	 * otherwise, it will load up the last payment made for the TXN.
2404
+	 * If the payment retrieved looks good, it will then either:
2405
+	 *    complete the current step and allow advancement to the next reg step
2406
+	 *        or present the payment options again
2407
+	 *
2408
+	 * @access private
2409
+	 * @return EE_Payment | FALSE
2410
+	 * @throws \EE_Error
2411
+	 */
2412
+	public function process_gateway_response()
2413
+	{
2414
+		$payment = null;
2415
+		// how have they chosen to pay?
2416
+		$this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2417
+		// get EE_Payment_Method object
2418
+		if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2419
+			$this->checkout->continue_reg = false;
2420
+			return false;
2421
+		}
2422
+		if (! $this->checkout->payment_method->is_off_site()) {
2423
+			return false;
2424
+		}
2425
+		$this->_validate_offsite_return();
2426
+		// DEBUG LOG
2427
+		//$this->checkout->log(
2428
+		//	__CLASS__, __FUNCTION__, __LINE__,
2429
+		//	array(
2430
+		//		'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2431
+		//		'payment_method' => $this->checkout->payment_method,
2432
+		//	),
2433
+		//	true
2434
+		//);
2435
+		// verify TXN
2436
+		if ($this->checkout->transaction instanceof EE_Transaction) {
2437
+			$gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2438
+			if (! $gateway instanceof EE_Offsite_Gateway) {
2439
+				$this->checkout->continue_reg = false;
2440
+				return false;
2441
+			}
2442
+			$payment = $this->_process_off_site_payment($gateway);
2443
+			$payment = $this->_process_cancelled_payments($payment);
2444
+			$payment = $this->_validate_payment($payment);
2445
+			// if payment was not declined by the payment gateway or cancelled by the registrant
2446
+			if ($this->_process_payment_status($payment, EE_PMT_Base::offsite)) {
2447
+				//$this->_setup_redirect_for_next_step();
2448
+				// store that for later
2449
+				$this->checkout->payment = $payment;
2450
+				// mark this reg step as completed, as long as gateway doesn't use a separate IPN request,
2451
+				// because we will complete this step during the IPN processing then
2452
+				if ($gateway instanceof EE_Offsite_Gateway && ! $this->handle_IPN_in_this_request()) {
2453
+					$this->set_completed();
2454
+				}
2455
+				return true;
2456
+			}
2457
+		}
2458
+		// DEBUG LOG
2459
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2460
+		//	array( 'payment' => $payment )
2461
+		//);
2462
+		$this->checkout->continue_reg = false;
2463
+		return false;
2464
+	}
2465
+
2466
+
2467
+	/**
2468
+	 * _validate_return
2469
+	 *
2470
+	 * @access private
2471
+	 * @return void
2472
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
2473
+	 * @throws \EE_Error
2474
+	 */
2475
+	private function _validate_offsite_return()
2476
+	{
2477
+		$TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2478
+		if ($TXN_ID !== $this->checkout->transaction->ID()) {
2479
+			// Houston... we might have a problem
2480
+			$invalid_TXN = false;
2481
+			// first gather some info
2482
+			$valid_TXN          = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2483
+			$primary_registrant = $valid_TXN instanceof EE_Transaction
2484
+				? $valid_TXN->primary_registration()
2485
+				: null;
2486
+			// let's start by retrieving the cart for this TXN
2487
+			$cart = $this->checkout->get_cart_for_transaction($this->checkout->transaction);
2488
+			if ($cart instanceof EE_Cart) {
2489
+				// verify that the current cart has tickets
2490
+				$tickets = $cart->get_tickets();
2491
+				if (empty($tickets)) {
2492
+					$invalid_TXN = true;
2493
+				}
2494
+			} else {
2495
+				$invalid_TXN = true;
2496
+			}
2497
+			$valid_TXN_SID = $primary_registrant instanceof EE_Registration
2498
+				? $primary_registrant->session_ID()
2499
+				: null;
2500
+			// validate current Session ID and compare against valid TXN session ID
2501
+			if (
2502
+				$invalid_TXN // if this is already true, then skip other checks
2503
+				|| EE_Session::instance()->id() === null
2504
+				|| (
2505
+					// WARNING !!!
2506
+					// this could be PayPal sending back duplicate requests (ya they do that)
2507
+					// or it **could** mean someone is simply registering AGAIN after having just done so
2508
+					// so now we need to determine if this current TXN looks valid or not
2509
+					// and whether this reg step has even been started ?
2510
+					EE_Session::instance()->id() === $valid_TXN_SID
2511
+					// really? you're half way through this reg step, but you never started it ?
2512
+					&& $this->checkout->transaction->reg_step_completed($this->slug()) === false
2513
+				)
2514
+			) {
2515
+				$invalid_TXN = true;
2516
+			}
2517
+			if ($invalid_TXN) {
2518
+				// is the valid TXN completed ?
2519
+				if ($valid_TXN instanceof EE_Transaction) {
2520
+					// has this step even been started ?
2521
+					$reg_step_completed = $valid_TXN->reg_step_completed($this->slug());
2522
+					if ($reg_step_completed !== false && $reg_step_completed !== true) {
2523
+						// so it **looks** like this is a double request from PayPal
2524
+						// so let's try to pick up where we left off
2525
+						$this->checkout->transaction = $valid_TXN;
2526
+						$this->checkout->refresh_all_entities(true);
2527
+						return;
2528
+					}
2529
+				}
2530
+				// you appear to be lost?
2531
+				$this->_redirect_wayward_request($primary_registrant);
2532
+			}
2533
+		}
2534
+	}
2535
+
2536
+
2537
+	/**
2538
+	 * _redirect_wayward_request
2539
+	 *
2540
+	 * @access private
2541
+	 * @param \EE_Registration|null $primary_registrant
2542
+	 * @return bool
2543
+	 * @throws \EE_Error
2544
+	 */
2545
+	private function _redirect_wayward_request(EE_Registration $primary_registrant)
2546
+	{
2547
+		if (! $primary_registrant instanceof EE_Registration) {
2548
+			// try redirecting based on the current TXN
2549
+			$primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2550
+				? $this->checkout->transaction->primary_registration()
2551
+				: null;
2552
+		}
2553
+		if (! $primary_registrant instanceof EE_Registration) {
2554
+			EE_Error::add_error(
2555
+				sprintf(
2556
+					__(
2557
+						'Invalid information was received from the Off-Site Payment Processor and your Transaction details could not be retrieved from the database.%1$sPlease try again or contact %2$s for assistance.',
2558
+						'event_espresso'
2559
+					),
2560
+					'<br/>',
2561
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
2562
+				),
2563
+				__FILE__,
2564
+				__FUNCTION__,
2565
+				__LINE__
2566
+			);
2567
+			return false;
2568
+		}
2569
+		// make sure transaction is not locked
2570
+		$this->checkout->transaction->unlock();
2571
+		wp_safe_redirect(
2572
+			add_query_arg(
2573
+				array(
2574
+					'e_reg_url_link' => $primary_registrant->reg_url_link(),
2575
+				),
2576
+				$this->checkout->thank_you_page_url
2577
+			)
2578
+		);
2579
+		exit();
2580
+	}
2581
+
2582
+
2583
+	/**
2584
+	 * _process_off_site_payment
2585
+	 *
2586
+	 * @access private
2587
+	 * @param \EE_Offsite_Gateway $gateway
2588
+	 * @return \EE_Payment
2589
+	 * @throws \EE_Error
2590
+	 */
2591
+	private function _process_off_site_payment(EE_Offsite_Gateway $gateway)
2592
+	{
2593
+		try {
2594
+			$request_data = \EE_Registry::instance()->REQ->params();
2595
+			// if gateway uses_separate_IPN_request, then we don't have to process the IPN manually
2596
+			$this->set_handle_IPN_in_this_request(
2597
+				$gateway->handle_IPN_in_this_request($request_data, false)
2598
+			);
2599
+			if ($this->handle_IPN_in_this_request()) {
2600
+				// get payment details and process results
2601
+				/** @type EE_Payment_Processor $payment_processor */
2602
+				$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2603
+				$payment           = $payment_processor->process_ipn(
2604
+					$request_data,
2605
+					$this->checkout->transaction,
2606
+					$this->checkout->payment_method,
2607
+					true,
2608
+					false
2609
+				);
2610
+				//$payment_source = 'process_ipn';
2611
+			} else {
2612
+				$payment = $this->checkout->transaction->last_payment();
2613
+				//$payment_source = 'last_payment';
2614
+			}
2615
+		} catch (Exception $e) {
2616
+			// let's just eat the exception and try to move on using any previously set payment info
2617
+			$payment = $this->checkout->transaction->last_payment();
2618
+			//$payment_source = 'last_payment after Exception';
2619
+			// but if we STILL don't have a payment object
2620
+			if (! $payment instanceof EE_Payment) {
2621
+				// then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2622
+				$this->_handle_payment_processor_exception($e);
2623
+			}
2624
+		}
2625
+		// DEBUG LOG
2626
+		//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__,
2627
+		//	array(
2628
+		//		'process_ipn_payment' => $payment,
2629
+		//		'payment_source'      => $payment_source,
2630
+		//	)
2631
+		//);
2632
+		return $payment;
2633
+	}
2634
+
2635
+
2636
+	/**
2637
+	 * _process_cancelled_payments
2638
+	 * just makes sure that the payment status gets updated correctly
2639
+	 * so tha tan error isn't generated during payment validation
2640
+	 *
2641
+	 * @access private
2642
+	 * @param EE_Payment $payment
2643
+	 * @return EE_Payment | FALSE
2644
+	 * @throws \EE_Error
2645
+	 */
2646
+	private function _process_cancelled_payments($payment = null)
2647
+	{
2648
+		if (
2649
+			$payment instanceof EE_Payment
2650
+			&& isset($_REQUEST['ee_cancel_payment'])
2651
+			&& $payment->status() === EEM_Payment::status_id_failed
2652
+		) {
2653
+			$payment->set_status(EEM_Payment::status_id_cancelled);
2654
+		}
2655
+		return $payment;
2656
+	}
2657
+
2658
+
2659
+	/**
2660
+	 *    get_transaction_details_for_gateways
2661
+	 *
2662
+	 * @access    public
2663
+	 * @return    int
2664
+	 * @throws \EE_Error
2665
+	 */
2666
+	public function get_transaction_details_for_gateways()
2667
+	{
2668
+		$txn_details = array();
2669
+		// ya gotta make a choice man
2670
+		if (empty($this->checkout->selected_method_of_payment)) {
2671
+			$txn_details = array(
2672
+				'error' => __('Please select a method of payment before proceeding.', 'event_espresso'),
2673
+			);
2674
+		}
2675
+		// get EE_Payment_Method object
2676
+		if (
2677
+			empty($txn_details)
2678
+			&&
2679
+			! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()
2680
+		) {
2681
+			$txn_details = array(
2682
+				'selected_method_of_payment' => $this->checkout->selected_method_of_payment,
2683
+				'error'                      => __(
2684
+					'A valid Payment Method could not be determined.',
2685
+					'event_espresso'
2686
+				),
2687
+			);
2688
+		}
2689
+		if (empty($txn_details) && $this->checkout->transaction instanceof EE_Transaction) {
2690
+			$return_url  = $this->_get_return_url($this->checkout->payment_method);
2691
+			$txn_details = array(
2692
+				'TXN_ID'         => $this->checkout->transaction->ID(),
2693
+				'TXN_timestamp'  => $this->checkout->transaction->datetime(),
2694
+				'TXN_total'      => $this->checkout->transaction->total(),
2695
+				'TXN_paid'       => $this->checkout->transaction->paid(),
2696
+				'TXN_reg_steps'  => $this->checkout->transaction->reg_steps(),
2697
+				'STS_ID'         => $this->checkout->transaction->status_ID(),
2698
+				'PMD_ID'         => $this->checkout->transaction->payment_method_ID(),
2699
+				'payment_amount' => $this->checkout->amount_owing,
2700
+				'return_url'     => $return_url,
2701
+				'cancel_url'     => add_query_arg(array('ee_cancel_payment' => true), $return_url),
2702
+				'notify_url'     => EE_Config::instance()->core->txn_page_url(
2703
+					array(
2704
+						'e_reg_url_link'    => $this->checkout->transaction->primary_registration()->reg_url_link(),
2705
+						'ee_payment_method' => $this->checkout->payment_method->slug(),
2706
+					)
2707
+				),
2708
+			);
2709
+		}
2710
+		echo wp_json_encode($txn_details);
2711
+		exit();
2712
+	}
2713
+
2714
+
2715
+	/**
2716
+	 *    __sleep
2717
+	 * to conserve db space, let's remove the reg_form and the EE_Checkout object from EE_SPCO_Reg_Step objects upon
2718
+	 * serialization EE_Checkout will handle the reimplementation of itself upon waking, but we won't bother with the
2719
+	 * reg form, because if needed, it will be regenerated anyways
2720
+	 *
2721
+	 * @return array
2722
+	 */
2723
+	public function __sleep()
2724
+	{
2725
+		// remove the reg form and the checkout
2726
+		return array_diff(array_keys(get_object_vars($this)), array('reg_form', 'checkout', 'line_item_display'));
2727
+	}
2728 2728
 
2729 2729
 
2730 2730
 }
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     {
130 130
         $this->_slug     = 'payment_options';
131 131
         $this->_name     = __('Payment Options', 'event_espresso');
132
-        $this->_template = SPCO_REG_STEPS_PATH . $this->_slug . DS . 'payment_options_main.template.php';
132
+        $this->_template = SPCO_REG_STEPS_PATH.$this->_slug.DS.'payment_options_main.template.php';
133 133
         $this->checkout  = $checkout;
134 134
         $this->_reset_success_message();
135 135
         $this->set_instructions(
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
      */
185 185
     public function translate_js_strings()
186 186
     {
187
-        EE_Registry::$i18n_js_strings['no_payment_method']      = __(
187
+        EE_Registry::$i18n_js_strings['no_payment_method'] = __(
188 188
             'Please select a method of payment in order to continue.',
189 189
             'event_espresso'
190 190
         );
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
             'A valid method of payment could not be determined. Please refresh the page and try again.',
193 193
             'event_espresso'
194 194
         );
195
-        EE_Registry::$i18n_js_strings['forwarding_to_offsite']  = __(
195
+        EE_Registry::$i18n_js_strings['forwarding_to_offsite'] = __(
196 196
             'Forwarding to Secure Payment Provider.',
197 197
             'event_espresso'
198 198
         );
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
     {
209 209
         $transaction = $this->checkout->transaction;
210 210
         //if the transaction isn't set or nothing is owed on it, don't enqueue any JS
211
-        if (! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
211
+        if ( ! $transaction instanceof EE_Transaction || EEH_Money::compare_floats($transaction->remaining(), 0)) {
212 212
             return;
213 213
         }
214 214
         foreach (
@@ -343,23 +343,23 @@  discard block
 block discarded – undo
343 343
         }
344 344
         $subsections = array();
345 345
         // now decide which template to load
346
-        if (! empty($sold_out_events)) {
346
+        if ( ! empty($sold_out_events)) {
347 347
             $subsections['sold_out_events'] = $this->_sold_out_events($sold_out_events);
348 348
         }
349
-        if (! empty($insufficient_spaces_available)) {
349
+        if ( ! empty($insufficient_spaces_available)) {
350 350
             $subsections['insufficient_space'] = $this->_insufficient_spaces_available(
351 351
                 $insufficient_spaces_available
352 352
             );
353 353
         }
354
-        if (! empty($registrations_requiring_pre_approval)) {
354
+        if ( ! empty($registrations_requiring_pre_approval)) {
355 355
             $subsections['registrations_requiring_pre_approval'] = $this->_registrations_requiring_pre_approval(
356 356
                 $registrations_requiring_pre_approval
357 357
             );
358 358
         }
359
-        if (! empty($registrations_for_free_events)) {
359
+        if ( ! empty($registrations_for_free_events)) {
360 360
             $subsections['no_payment_required'] = $this->_no_payment_required($registrations_for_free_events);
361 361
         }
362
-        if (! empty($registrations_requiring_payment)) {
362
+        if ( ! empty($registrations_requiring_payment)) {
363 363
             if ($this->checkout->amount_owing > 0) {
364 364
                 // autoload Line_Item_Display classes
365 365
                 EEH_Autoloader::register_line_item_filter_autoloaders();
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
                         array('registrations' => $registrations)
381 381
                     )
382 382
                 );
383
-                $this->checkout->amount_owing   = $filtered_line_item_tree->total();
383
+                $this->checkout->amount_owing = $filtered_line_item_tree->total();
384 384
                 $this->_apply_registration_payments_to_amount_owing($registrations);
385 385
             }
386 386
             $no_payment_required = false;
@@ -418,13 +418,13 @@  discard block
 block discarded – undo
418 418
      */
419 419
     public static function add_spco_line_item_filters(EE_Line_Item_Filter_Collection $line_item_filter_collection)
420 420
     {
421
-        if (! EE_Registry::instance()->SSN instanceof EE_Session) {
421
+        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
422 422
             return $line_item_filter_collection;
423 423
         }
424
-        if (! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
424
+        if ( ! EE_Registry::instance()->SSN->checkout() instanceof EE_Checkout) {
425 425
             return $line_item_filter_collection;
426 426
         }
427
-        if (! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
427
+        if ( ! EE_Registry::instance()->SSN->checkout()->transaction instanceof EE_Transaction) {
428 428
             return $line_item_filter_collection;
429 429
         }
430 430
         $line_item_filter_collection->add(
@@ -504,15 +504,15 @@  discard block
 block discarded – undo
504 504
             }
505 505
             $EVT_ID = $registration->event_ID();
506 506
             $ticket = $registration->ticket();
507
-            if (! isset($tickets_remaining[$ticket->ID()])) {
507
+            if ( ! isset($tickets_remaining[$ticket->ID()])) {
508 508
                 $tickets_remaining[$ticket->ID()] = $ticket->remaining();
509 509
             }
510 510
             if ($tickets_remaining[$ticket->ID()] > 0) {
511
-                if (! isset($event_reg_count[$EVT_ID])) {
511
+                if ( ! isset($event_reg_count[$EVT_ID])) {
512 512
                     $event_reg_count[$EVT_ID] = 0;
513 513
                 }
514 514
                 $event_reg_count[$EVT_ID]++;
515
-                if (! isset($event_spaces_remaining[$EVT_ID])) {
515
+                if ( ! isset($event_spaces_remaining[$EVT_ID])) {
516 516
                     $event_spaces_remaining[$EVT_ID] = $registration->event()->spaces_remaining_for_sale();
517 517
                 }
518 518
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
         $sold_out_events                            = '';
583 583
         foreach ($sold_out_events_array as $sold_out_event) {
584 584
             $sold_out_events .= EEH_HTML::li(
585
-                EEH_HTML::span('  ' . $sold_out_event->name(), '',
585
+                EEH_HTML::span('  '.$sold_out_event->name(), '',
586 586
                     'dashicons dashicons-marker ee-icon-size-16 pink-text')
587 587
             );
588 588
         }
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
         foreach ($insufficient_spaces_events_array as $event) {
635 635
             if ($event instanceof EE_Event) {
636 636
                 $insufficient_space_events .= EEH_HTML::li(
637
-                    EEH_HTML::span(' ' . $event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
637
+                    EEH_HTML::span(' '.$event->name(), '', 'dashicons dashicons-marker ee-icon-size-16 pink-text')
638 638
                 );
639 639
             }
640 640
         }
@@ -820,7 +820,7 @@  discard block
 block discarded – undo
820 820
     {
821 821
         return new EE_Form_Section_Proper(
822 822
             array(
823
-                'html_id'         => 'ee-' . $this->slug() . '-extra-hidden-inputs',
823
+                'html_id'         => 'ee-'.$this->slug().'-extra-hidden-inputs',
824 824
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
825 825
                 'subsections'     => array(
826 826
                     'spco_no_payment_required' => new EE_Hidden_Input(
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
                 $payments += $registration->registration_payments();
860 860
             }
861 861
         }
862
-        if (! empty($payments)) {
862
+        if ( ! empty($payments)) {
863 863
             foreach ($payments as $payment) {
864 864
                 if ($payment instanceof EE_Registration_Payment) {
865 865
                     $this->checkout->amount_owing -= $payment->amount();
@@ -921,7 +921,7 @@  discard block
 block discarded – undo
921 921
         // load payment method classes
922 922
         $this->checkout->available_payment_methods = $this->_get_available_payment_methods();
923 923
         // switch up header depending on number of available payment methods
924
-        $payment_method_header     = count($this->checkout->available_payment_methods) > 1
924
+        $payment_method_header = count($this->checkout->available_payment_methods) > 1
925 925
             ? apply_filters(
926 926
                 'FHEE__registration_page_payment_options__method_of_payment_hdr',
927 927
                 __('Please Select Your Method of Payment', 'event_espresso')
@@ -951,14 +951,14 @@  discard block
 block discarded – undo
951 951
                 $payment_method_button = EEH_HTML::img(
952 952
                     $payment_method->button_url(),
953 953
                     $payment_method->name(),
954
-                    'spco-payment-method-' . $payment_method->slug() . '-btn-img',
954
+                    'spco-payment-method-'.$payment_method->slug().'-btn-img',
955 955
                     'spco-payment-method-btn-img'
956 956
                 );
957 957
                 // check if any payment methods are set as default
958 958
                 // if payment method is already selected OR nothing is selected and this payment method should be open_by_default
959 959
                 if (
960 960
                     ($this->checkout->selected_method_of_payment === $payment_method->slug())
961
-                    || (! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
961
+                    || ( ! $this->checkout->selected_method_of_payment && $payment_method->open_by_default())
962 962
                 ) {
963 963
                     $this->checkout->selected_method_of_payment = $payment_method->slug();
964 964
                     $this->_save_selected_method_of_payment();
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
         $available_payment_methods['available_payment_methods'] = $this->_available_payment_method_inputs(
979 979
             $available_payment_method_options
980 980
         );
981
-        $available_payment_methods                              += $payment_methods_billing_info;
981
+        $available_payment_methods += $payment_methods_billing_info;
982 982
         // build the available payment methods form
983 983
         return new EE_Form_Section_Proper(
984 984
             array(
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
      */
998 998
     protected function _get_available_payment_methods()
999 999
     {
1000
-        if (! empty($this->checkout->available_payment_methods)) {
1000
+        if ( ! empty($this->checkout->available_payment_methods)) {
1001 1001
             return $this->checkout->available_payment_methods;
1002 1002
         }
1003 1003
         $available_payment_methods = array();
@@ -1034,7 +1034,7 @@  discard block
 block discarded – undo
1034 1034
                 'html_id'         => 'ee-available-payment-method-inputs',
1035 1035
                 'layout_strategy' => new EE_Div_Per_Section_Layout(),
1036 1036
                 'subsections'     => array(
1037
-                    '' => new EE_Radio_Button_Input (
1037
+                    '' => new EE_Radio_Button_Input(
1038 1038
                         $available_payment_method_options,
1039 1039
                         array(
1040 1040
                             'html_name'          => 'selected_method_of_payment',
@@ -1104,7 +1104,7 @@  discard block
 block discarded – undo
1104 1104
         );
1105 1105
         return new EE_Form_Section_Proper(
1106 1106
             array(
1107
-                'html_id'         => 'spco-payment-method-info-' . $payment_method->slug(),
1107
+                'html_id'         => 'spco-payment-method-info-'.$payment_method->slug(),
1108 1108
                 'html_class'      => 'spco-payment-method-info-dv',
1109 1109
                 // only display the selected or default PM
1110 1110
                 'html_style'      => $currently_selected ? '' : 'display:none;',
@@ -1130,7 +1130,7 @@  discard block
 block discarded – undo
1130 1130
         // how have they chosen to pay?
1131 1131
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
1132 1132
         $this->checkout->payment_method             = $this->_get_payment_method_for_selected_method_of_payment();
1133
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1133
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1134 1134
             return false;
1135 1135
         }
1136 1136
         if (apply_filters(
@@ -1295,7 +1295,7 @@  discard block
 block discarded – undo
1295 1295
      */
1296 1296
     public function switch_payment_method()
1297 1297
     {
1298
-        if (! $this->_verify_payment_method_is_set()) {
1298
+        if ( ! $this->_verify_payment_method_is_set()) {
1299 1299
             return false;
1300 1300
         }
1301 1301
         if (apply_filters(
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
             }
1415 1415
         }
1416 1416
         // verify payment method
1417
-        if (! $this->checkout->payment_method instanceof EE_Payment_Method) {
1417
+        if ( ! $this->checkout->payment_method instanceof EE_Payment_Method) {
1418 1418
             // get payment method for selected method of payment
1419 1419
             $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment();
1420 1420
         }
@@ -1434,7 +1434,7 @@  discard block
 block discarded – undo
1434 1434
      */
1435 1435
     public function save_payer_details_via_ajax()
1436 1436
     {
1437
-        if (! $this->_verify_payment_method_is_set()) {
1437
+        if ( ! $this->_verify_payment_method_is_set()) {
1438 1438
             return;
1439 1439
         }
1440 1440
         // generate billing form for selected method of payment if it hasn't been done already
@@ -1444,7 +1444,7 @@  discard block
 block discarded – undo
1444 1444
             );
1445 1445
         }
1446 1446
         // generate primary attendee from payer info if applicable
1447
-        if (! $this->checkout->transaction_has_primary_registrant()) {
1447
+        if ( ! $this->checkout->transaction_has_primary_registrant()) {
1448 1448
             $attendee = $this->_create_attendee_from_request_data();
1449 1449
             if ($attendee instanceof EE_Attendee) {
1450 1450
                 foreach ($this->checkout->transaction->registrations() as $registration) {
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
     {
1472 1472
         // get State ID
1473 1473
         $STA_ID = ! empty($_REQUEST['state']) ? sanitize_text_field($_REQUEST['state']) : '';
1474
-        if (! empty($STA_ID)) {
1474
+        if ( ! empty($STA_ID)) {
1475 1475
             // can we get state object from name ?
1476 1476
             EE_Registry::instance()->load_model('State');
1477 1477
             $state  = EEM_State::instance()->get_col(array(array('STA_name' => $STA_ID), 'limit' => 1), 'STA_ID');
@@ -1479,7 +1479,7 @@  discard block
 block discarded – undo
1479 1479
         }
1480 1480
         // get Country ISO
1481 1481
         $CNT_ISO = ! empty($_REQUEST['country']) ? sanitize_text_field($_REQUEST['country']) : '';
1482
-        if (! empty($CNT_ISO)) {
1482
+        if ( ! empty($CNT_ISO)) {
1483 1483
             // can we get country object from name ?
1484 1484
             EE_Registry::instance()->load_model('Country');
1485 1485
             $country = EEM_Country::instance()->get_col(
@@ -1511,7 +1511,7 @@  discard block
 block discarded – undo
1511 1511
             );
1512 1512
         }
1513 1513
         // does this attendee already exist in the db ? we're searching using a combination of first name, last name, AND email address
1514
-        if (! empty($attendee_data['ATT_fname'])
1514
+        if ( ! empty($attendee_data['ATT_fname'])
1515 1515
             && ! empty($attendee_data['ATT_lname'])
1516 1516
             && ! empty($attendee_data['ATT_email'])
1517 1517
         ) {
@@ -1710,7 +1710,7 @@  discard block
 block discarded – undo
1710 1710
     private function _process_payment()
1711 1711
     {
1712 1712
         // basically confirm that the event hasn't sold out since they hit the page
1713
-        if (! $this->_last_second_ticket_verifications()) {
1713
+        if ( ! $this->_last_second_ticket_verifications()) {
1714 1714
             return false;
1715 1715
         }
1716 1716
         // ya gotta make a choice man
@@ -1721,7 +1721,7 @@  discard block
 block discarded – undo
1721 1721
             return false;
1722 1722
         }
1723 1723
         // get EE_Payment_Method object
1724
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1724
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
1725 1725
             return false;
1726 1726
         }
1727 1727
         // setup billing form
@@ -1730,12 +1730,12 @@  discard block
 block discarded – undo
1730 1730
                 $this->checkout->payment_method
1731 1731
             );
1732 1732
             // bad billing form ?
1733
-            if (! $this->_billing_form_is_valid()) {
1733
+            if ( ! $this->_billing_form_is_valid()) {
1734 1734
                 return false;
1735 1735
             }
1736 1736
         }
1737 1737
         // ensure primary registrant has been fully processed
1738
-        if (! $this->_setup_primary_registrant_prior_to_payment()) {
1738
+        if ( ! $this->_setup_primary_registrant_prior_to_payment()) {
1739 1739
             return false;
1740 1740
         }
1741 1741
         // if session is close to expiring (under 10 minutes by default)
@@ -1787,7 +1787,7 @@  discard block
 block discarded – undo
1787 1787
     protected function _last_second_ticket_verifications()
1788 1788
     {
1789 1789
         // don't bother re-validating if not a return visit
1790
-        if (! $this->checkout->revisit) {
1790
+        if ( ! $this->checkout->revisit) {
1791 1791
             return true;
1792 1792
         }
1793 1793
         $registrations = $this->checkout->transaction->registrations();
@@ -1832,7 +1832,7 @@  discard block
 block discarded – undo
1832 1832
             $this->_get_payment_method_for_selected_method_of_payment()
1833 1833
         );
1834 1834
         $html                        = $payment_method_billing_info->get_html();
1835
-        $html                        .= $this->checkout->redirect_form;
1835
+        $html .= $this->checkout->redirect_form;
1836 1836
         EE_Registry::instance()->REQ->add_output($html);
1837 1837
         return true;
1838 1838
     }
@@ -1847,7 +1847,7 @@  discard block
 block discarded – undo
1847 1847
      */
1848 1848
     private function _billing_form_is_valid()
1849 1849
     {
1850
-        if (! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1850
+        if ( ! $this->checkout->payment_method->type_obj()->has_billing_form()) {
1851 1851
             return true;
1852 1852
         }
1853 1853
         if ($this->checkout->billing_form instanceof EE_Billing_Info_Form) {
@@ -1955,7 +1955,7 @@  discard block
 block discarded – undo
1955 1955
     {
1956 1956
         // convert billing form data into an attendee
1957 1957
         $this->checkout->primary_attendee_obj = $this->checkout->billing_form->create_attendee_from_billing_form_data();
1958
-        if (! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
1958
+        if ( ! $this->checkout->primary_attendee_obj instanceof EE_Attendee) {
1959 1959
             EE_Error::add_error(
1960 1960
                 sprintf(
1961 1961
                     __(
@@ -1972,7 +1972,7 @@  discard block
 block discarded – undo
1972 1972
             return false;
1973 1973
         }
1974 1974
         $primary_registration = $this->checkout->transaction->primary_registration();
1975
-        if (! $primary_registration instanceof EE_Registration) {
1975
+        if ( ! $primary_registration instanceof EE_Registration) {
1976 1976
             EE_Error::add_error(
1977 1977
                 sprintf(
1978 1978
                     __(
@@ -1988,7 +1988,7 @@  discard block
 block discarded – undo
1988 1988
             );
1989 1989
             return false;
1990 1990
         }
1991
-        if (! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
1991
+        if ( ! $primary_registration->_add_relation_to($this->checkout->primary_attendee_obj, 'Attendee')
1992 1992
               instanceof
1993 1993
               EE_Attendee
1994 1994
         ) {
@@ -2040,7 +2040,7 @@  discard block
 block discarded – undo
2040 2040
             $payment_method     = $EEM_Payment_Method->get_one_by_slug($this->checkout->selected_method_of_payment);
2041 2041
         }
2042 2042
         // verify $payment_method
2043
-        if (! $payment_method instanceof EE_Payment_Method) {
2043
+        if ( ! $payment_method instanceof EE_Payment_Method) {
2044 2044
             // not a payment
2045 2045
             EE_Error::add_error(
2046 2046
                 sprintf(
@@ -2058,7 +2058,7 @@  discard block
 block discarded – undo
2058 2058
             return null;
2059 2059
         }
2060 2060
         // and verify it has a valid Payment_Method Type object
2061
-        if (! $payment_method->type_obj() instanceof EE_PMT_Base) {
2061
+        if ( ! $payment_method->type_obj() instanceof EE_PMT_Base) {
2062 2062
             // not a payment
2063 2063
             EE_Error::add_error(
2064 2064
                 sprintf(
@@ -2092,7 +2092,7 @@  discard block
 block discarded – undo
2092 2092
         $payment = null;
2093 2093
         $this->checkout->transaction->save();
2094 2094
         $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2095
-        if (! $payment_processor instanceof EE_Payment_Processor) {
2095
+        if ( ! $payment_processor instanceof EE_Payment_Processor) {
2096 2096
             return false;
2097 2097
         }
2098 2098
         try {
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
             return true;
2191 2191
         }
2192 2192
         // verify payment object
2193
-        if (! $payment instanceof EE_Payment) {
2193
+        if ( ! $payment instanceof EE_Payment) {
2194 2194
             // not a payment
2195 2195
             EE_Error::add_error(
2196 2196
                 sprintf(
@@ -2227,7 +2227,7 @@  discard block
 block discarded – undo
2227 2227
             return true;
2228 2228
             // On-Site payment?
2229 2229
         } else if ($this->checkout->payment_method->is_on_site()) {
2230
-            if (! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2230
+            if ( ! $this->_process_payment_status($payment, EE_PMT_Base::onsite)) {
2231 2231
                 //$this->_setup_redirect_for_next_step();
2232 2232
                 $this->checkout->continue_reg = false;
2233 2233
             }
@@ -2359,7 +2359,7 @@  discard block
 block discarded – undo
2359 2359
                     break;
2360 2360
                 // bad payment
2361 2361
                 case EEM_Payment::status_id_failed :
2362
-                    if (! empty($msg)) {
2362
+                    if ( ! empty($msg)) {
2363 2363
                         EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
2364 2364
                         return false;
2365 2365
                     }
@@ -2415,11 +2415,11 @@  discard block
 block discarded – undo
2415 2415
         // how have they chosen to pay?
2416 2416
         $this->checkout->selected_method_of_payment = $this->_get_selected_method_of_payment(true);
2417 2417
         // get EE_Payment_Method object
2418
-        if (! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2418
+        if ( ! $this->checkout->payment_method = $this->_get_payment_method_for_selected_method_of_payment()) {
2419 2419
             $this->checkout->continue_reg = false;
2420 2420
             return false;
2421 2421
         }
2422
-        if (! $this->checkout->payment_method->is_off_site()) {
2422
+        if ( ! $this->checkout->payment_method->is_off_site()) {
2423 2423
             return false;
2424 2424
         }
2425 2425
         $this->_validate_offsite_return();
@@ -2435,7 +2435,7 @@  discard block
 block discarded – undo
2435 2435
         // verify TXN
2436 2436
         if ($this->checkout->transaction instanceof EE_Transaction) {
2437 2437
             $gateway = $this->checkout->payment_method->type_obj()->get_gateway();
2438
-            if (! $gateway instanceof EE_Offsite_Gateway) {
2438
+            if ( ! $gateway instanceof EE_Offsite_Gateway) {
2439 2439
                 $this->checkout->continue_reg = false;
2440 2440
                 return false;
2441 2441
             }
@@ -2474,7 +2474,7 @@  discard block
 block discarded – undo
2474 2474
      */
2475 2475
     private function _validate_offsite_return()
2476 2476
     {
2477
-        $TXN_ID = (int)EE_Registry::instance()->REQ->get('spco_txn', 0);
2477
+        $TXN_ID = (int) EE_Registry::instance()->REQ->get('spco_txn', 0);
2478 2478
         if ($TXN_ID !== $this->checkout->transaction->ID()) {
2479 2479
             // Houston... we might have a problem
2480 2480
             $invalid_TXN = false;
@@ -2544,13 +2544,13 @@  discard block
 block discarded – undo
2544 2544
      */
2545 2545
     private function _redirect_wayward_request(EE_Registration $primary_registrant)
2546 2546
     {
2547
-        if (! $primary_registrant instanceof EE_Registration) {
2547
+        if ( ! $primary_registrant instanceof EE_Registration) {
2548 2548
             // try redirecting based on the current TXN
2549 2549
             $primary_registrant = $this->checkout->transaction instanceof EE_Transaction
2550 2550
                 ? $this->checkout->transaction->primary_registration()
2551 2551
                 : null;
2552 2552
         }
2553
-        if (! $primary_registrant instanceof EE_Registration) {
2553
+        if ( ! $primary_registrant instanceof EE_Registration) {
2554 2554
             EE_Error::add_error(
2555 2555
                 sprintf(
2556 2556
                     __(
@@ -2617,7 +2617,7 @@  discard block
 block discarded – undo
2617 2617
             $payment = $this->checkout->transaction->last_payment();
2618 2618
             //$payment_source = 'last_payment after Exception';
2619 2619
             // but if we STILL don't have a payment object
2620
-            if (! $payment instanceof EE_Payment) {
2620
+            if ( ! $payment instanceof EE_Payment) {
2621 2621
                 // then we'll object ! ( not object like a thing... but object like what a lawyer says ! )
2622 2622
                 $this->_handle_payment_processor_exception($e);
2623 2623
             }
Please login to merge, or discard this patch.
modules/messages/EED_Messages.module.php 1 patch
Indentation   +1090 added lines, -1090 removed lines patch added patch discarded remove patch
@@ -16,1105 +16,1105 @@
 block discarded – undo
16 16
 class EED_Messages extends EED_Module
17 17
 {
18 18
 
19
-    /**
20
-     * This holds the EE_messages controller
21
-     *
22
-     * @deprecated 4.9.0
23
-     * @var EE_messages $_EEMSG
24
-     */
25
-    protected static $_EEMSG;
26
-
27
-    /**
28
-     * @type EE_Message_Resource_Manager $_message_resource_manager
29
-     */
30
-    protected static $_message_resource_manager;
31
-
32
-    /**
33
-     * This holds the EE_Messages_Processor business class.
34
-     *
35
-     * @type EE_Messages_Processor
36
-     */
37
-    protected static $_MSG_PROCESSOR;
38
-
39
-    /**
40
-     * holds all the paths for various messages components.
41
-     * Utilized by autoloader registry
42
-     *
43
-     * @var array
44
-     */
45
-    protected static $_MSG_PATHS;
46
-
47
-
48
-    /**
49
-     * This will hold an array of messages template packs that are registered in the messages system.
50
-     * Format is:
51
-     * array(
52
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
-     * )
54
-     *
55
-     * @var EE_Messages_Template_Pack[]
56
-     */
57
-    protected static $_TMP_PACKS = array();
58
-
59
-
60
-    /**
61
-     * @return EED_Messages
62
-     */
63
-    public static function instance()
64
-    {
65
-        return parent::get_instance(__CLASS__);
66
-    }
67
-
68
-
69
-    /**
70
-     *  set_hooks - for hooking into EE Core, other modules, etc
71
-     *
72
-     * @since 4.5.0
73
-     * @return    void
74
-     */
75
-    public static function set_hooks()
76
-    {
77
-        //actions
78
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
80
-            array('EED_Messages', 'maybe_registration'), 10, 2);
81
-        //filters
82
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
83
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
84
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
85
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
-        //register routes
87
-        self::_register_routes();
88
-    }
89
-
90
-    /**
91
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
92
-     *
93
-     * @access    public
94
-     * @return    void
95
-     */
96
-    public static function set_hooks_admin()
97
-    {
98
-        //actions
99
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
100
-        add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
101
-            array('EED_Messages', 'payment_reminder'), 10);
102
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
103
-            array('EED_Messages', 'maybe_registration'), 10, 3);
104
-        add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
105
-            array('EED_Messages', 'send_newsletter_message'), 10, 2);
106
-        add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
107
-            array('EED_Messages', 'cancelled_registration'), 10);
108
-        add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
109
-            array('EED_Messages', 'process_admin_payment'), 10, 1);
110
-        //filters
111
-        add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
112
-            array('EED_Messages', 'process_resend'), 10, 2);
113
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
114
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
115
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
116
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
-    }
118
-
119
-
120
-    /**
121
-     * All the message triggers done by route go in here.
122
-     *
123
-     * @since 4.5.0
124
-     * @return void
125
-     */
126
-    protected static function _register_routes()
127
-    {
128
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
129
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
130
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
131
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
132
-        do_action('AHEE__EED_Messages___register_routes');
133
-    }
134
-
135
-
136
-    /**
137
-     * This is called when a browser display trigger is executed.
138
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
139
-     * browser.
140
-     *
141
-     * @since 4.9.0
142
-     * @param WP $WP
143
-     */
144
-    public function browser_trigger($WP)
145
-    {
146
-        //ensure controller is loaded
147
-        self::_load_controller();
148
-        $token = EE_Registry::instance()->REQ->get('token');
149
-        try {
150
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
151
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
152
-        } catch (EE_Error $e) {
153
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
154
-                'event_espresso');
155
-            // add specific message for developers if WP_DEBUG in on
156
-            $error_msg .= '||' . $e->getMessage();
157
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
158
-        }
159
-    }
160
-
161
-
162
-    /**
163
-     * This is called when a browser error trigger is executed.
164
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
165
-     * message and display it.
166
-     *
167
-     * @since 4.9.0
168
-     * @param $WP
169
-     */
170
-    public function browser_error_trigger($WP)
171
-    {
172
-        $token = EE_Registry::instance()->REQ->get('token');
173
-        if ($token) {
174
-            $message = EEM_Message::instance()->get_one_by_token($token);
175
-            if ($message instanceof EE_Message) {
176
-                header('HTTP/1.1 200 OK');
177
-                $error_msg = nl2br($message->error_message());
178
-                ?>
19
+	/**
20
+	 * This holds the EE_messages controller
21
+	 *
22
+	 * @deprecated 4.9.0
23
+	 * @var EE_messages $_EEMSG
24
+	 */
25
+	protected static $_EEMSG;
26
+
27
+	/**
28
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
29
+	 */
30
+	protected static $_message_resource_manager;
31
+
32
+	/**
33
+	 * This holds the EE_Messages_Processor business class.
34
+	 *
35
+	 * @type EE_Messages_Processor
36
+	 */
37
+	protected static $_MSG_PROCESSOR;
38
+
39
+	/**
40
+	 * holds all the paths for various messages components.
41
+	 * Utilized by autoloader registry
42
+	 *
43
+	 * @var array
44
+	 */
45
+	protected static $_MSG_PATHS;
46
+
47
+
48
+	/**
49
+	 * This will hold an array of messages template packs that are registered in the messages system.
50
+	 * Format is:
51
+	 * array(
52
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
53
+	 * )
54
+	 *
55
+	 * @var EE_Messages_Template_Pack[]
56
+	 */
57
+	protected static $_TMP_PACKS = array();
58
+
59
+
60
+	/**
61
+	 * @return EED_Messages
62
+	 */
63
+	public static function instance()
64
+	{
65
+		return parent::get_instance(__CLASS__);
66
+	}
67
+
68
+
69
+	/**
70
+	 *  set_hooks - for hooking into EE Core, other modules, etc
71
+	 *
72
+	 * @since 4.5.0
73
+	 * @return    void
74
+	 */
75
+	public static function set_hooks()
76
+	{
77
+		//actions
78
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
79
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
80
+			array('EED_Messages', 'maybe_registration'), 10, 2);
81
+		//filters
82
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
83
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
84
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
85
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
+		//register routes
87
+		self::_register_routes();
88
+	}
89
+
90
+	/**
91
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
92
+	 *
93
+	 * @access    public
94
+	 * @return    void
95
+	 */
96
+	public static function set_hooks_admin()
97
+	{
98
+		//actions
99
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
100
+		add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
101
+			array('EED_Messages', 'payment_reminder'), 10);
102
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
103
+			array('EED_Messages', 'maybe_registration'), 10, 3);
104
+		add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
105
+			array('EED_Messages', 'send_newsletter_message'), 10, 2);
106
+		add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
107
+			array('EED_Messages', 'cancelled_registration'), 10);
108
+		add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
109
+			array('EED_Messages', 'process_admin_payment'), 10, 1);
110
+		//filters
111
+		add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
112
+			array('EED_Messages', 'process_resend'), 10, 2);
113
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
114
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
115
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
116
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
+	}
118
+
119
+
120
+	/**
121
+	 * All the message triggers done by route go in here.
122
+	 *
123
+	 * @since 4.5.0
124
+	 * @return void
125
+	 */
126
+	protected static function _register_routes()
127
+	{
128
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
129
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
130
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
131
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
132
+		do_action('AHEE__EED_Messages___register_routes');
133
+	}
134
+
135
+
136
+	/**
137
+	 * This is called when a browser display trigger is executed.
138
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
139
+	 * browser.
140
+	 *
141
+	 * @since 4.9.0
142
+	 * @param WP $WP
143
+	 */
144
+	public function browser_trigger($WP)
145
+	{
146
+		//ensure controller is loaded
147
+		self::_load_controller();
148
+		$token = EE_Registry::instance()->REQ->get('token');
149
+		try {
150
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
151
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
152
+		} catch (EE_Error $e) {
153
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
154
+				'event_espresso');
155
+			// add specific message for developers if WP_DEBUG in on
156
+			$error_msg .= '||' . $e->getMessage();
157
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
158
+		}
159
+	}
160
+
161
+
162
+	/**
163
+	 * This is called when a browser error trigger is executed.
164
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
165
+	 * message and display it.
166
+	 *
167
+	 * @since 4.9.0
168
+	 * @param $WP
169
+	 */
170
+	public function browser_error_trigger($WP)
171
+	{
172
+		$token = EE_Registry::instance()->REQ->get('token');
173
+		if ($token) {
174
+			$message = EEM_Message::instance()->get_one_by_token($token);
175
+			if ($message instanceof EE_Message) {
176
+				header('HTTP/1.1 200 OK');
177
+				$error_msg = nl2br($message->error_message());
178
+				?>
179 179
                 <!DOCTYPE html>
180 180
                 <html>
181 181
                 <head></head>
182 182
                 <body>
183 183
                 <?php echo empty($error_msg)
184
-                    ? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
185
-                        'event_espresso')
186
-                    : wp_kses(
187
-                        $error_msg,
188
-                        array(
189
-                            'a'      => array(
190
-                                'href'  => array(),
191
-                                'title' => array(),
192
-                            ),
193
-                            'span'   => array(),
194
-                            'div'    => array(),
195
-                            'p'      => array(),
196
-                            'strong' => array(),
197
-                            'em'     => array(),
198
-                            'br'     => array(),
199
-                        )
200
-                    ); ?>
184
+					? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
185
+						'event_espresso')
186
+					: wp_kses(
187
+						$error_msg,
188
+						array(
189
+							'a'      => array(
190
+								'href'  => array(),
191
+								'title' => array(),
192
+							),
193
+							'span'   => array(),
194
+							'div'    => array(),
195
+							'p'      => array(),
196
+							'strong' => array(),
197
+							'em'     => array(),
198
+							'br'     => array(),
199
+						)
200
+					); ?>
201 201
                 </body>
202 202
                 </html>
203 203
                 <?php
204
-                exit;
205
-            }
206
-        }
207
-        return;
208
-    }
209
-
210
-
211
-    /**
212
-     *  This runs when the msg_url_trigger route has initiated.
213
-     *
214
-     * @since 4.5.0
215
-     * @param WP $WP
216
-     * @throws EE_Error
217
-     * @return    void
218
-     */
219
-    public function run($WP)
220
-    {
221
-        //ensure controller is loaded
222
-        self::_load_controller();
223
-        // attempt to process message
224
-        try {
225
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
226
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
227
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
228
-        } catch (EE_Error $e) {
229
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
230
-                'event_espresso');
231
-            // add specific message for developers if WP_DEBUG in on
232
-            $error_msg .= '||' . $e->getMessage();
233
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
234
-        }
235
-    }
236
-
237
-
238
-    /**
239
-     * This is triggered by the 'msg_cron_trigger' route.
240
-     *
241
-     * @param WP $WP
242
-     */
243
-    public function execute_batch_request($WP)
244
-    {
245
-        $this->run_cron();
246
-        header('HTTP/1.1 200 OK');
247
-        exit();
248
-    }
249
-
250
-
251
-    /**
252
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
253
-     * request.
254
-     */
255
-    public function run_cron()
256
-    {
257
-        self::_load_controller();
258
-        //get required vars
259
-        $cron_type     = EE_Registry::instance()->REQ->get('type');
260
-        $transient_key = EE_Registry::instance()->REQ->get('key');
261
-
262
-        //now let's verify transient, if not valid exit immediately
263
-        if (! get_transient($transient_key)) {
264
-            /**
265
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
266
-             */
267
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
268
-        }
269
-
270
-        //if made it here, lets' delete the transient to keep the db clean
271
-        delete_transient($transient_key);
272
-
273
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
274
-
275
-            $method = 'batch_' . $cron_type . '_from_queue';
276
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
277
-                self::$_MSG_PROCESSOR->$method();
278
-            } else {
279
-                //no matching task
280
-                /**
281
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
282
-                 */
283
-                trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
284
-                    $cron_type)));
285
-            }
286
-        }
287
-
288
-        do_action('FHEE__EED_Messages__run_cron__end');
289
-    }
290
-
291
-
292
-    /**
293
-     * This is used to retrieve the template pack for the given name.
294
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
295
-     * the default template pack is returned.
296
-     *
297
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
298
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
299
-     *                                   in generating the Pack class name).
300
-     * @return EE_Messages_Template_Pack
301
-     */
302
-    public static function get_template_pack($template_pack_name)
303
-    {
304
-        EE_Registry::instance()->load_helper('MSG_Template');
305
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
306
-    }
307
-
308
-
309
-    /**
310
-     * Retrieves an array of all template packs.
311
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
312
-     *
313
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
314
-     * @return EE_Messages_Template_Pack[]
315
-     */
316
-    public static function get_template_packs()
317
-    {
318
-        EE_Registry::instance()->load_helper('MSG_Template');
319
-
320
-        //for backward compat, let's make sure this returns in the same format as originally.
321
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
322
-        $template_pack_collection->rewind();
323
-        $template_packs = array();
324
-        while ($template_pack_collection->valid()) {
325
-            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
326
-            $template_pack_collection->next();
327
-        }
328
-        return $template_packs;
329
-    }
330
-
331
-
332
-    /**
333
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
334
-     *
335
-     * @since 4.5.0
336
-     * @return void
337
-     */
338
-    public static function set_autoloaders()
339
-    {
340
-        if (empty(self::$_MSG_PATHS)) {
341
-            self::_set_messages_paths();
342
-            foreach (self::$_MSG_PATHS as $path) {
343
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
344
-            }
345
-            // add aliases
346
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
347
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
348
-        }
349
-    }
350
-
351
-
352
-    /**
353
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
354
-     * for use by the Messages Autoloaders
355
-     *
356
-     * @since 4.5.0
357
-     * @return void.
358
-     */
359
-    protected static function _set_messages_paths()
360
-    {
361
-        $dir_ref = array(
362
-            'messages/message_type',
363
-            'messages/messenger',
364
-            'messages/defaults',
365
-            'messages/defaults/email',
366
-            'messages/data_class',
367
-            'messages/validators',
368
-            'messages/validators/email',
369
-            'messages/validators/html',
370
-            'shortcodes',
371
-        );
372
-        $paths   = array();
373
-        foreach ($dir_ref as $index => $dir) {
374
-            $paths[$index] = EE_LIBRARIES . $dir;
375
-        }
376
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
377
-    }
378
-
379
-
380
-    /**
381
-     * Takes care of loading dependencies
382
-     *
383
-     * @since 4.5.0
384
-     * @return void
385
-     */
386
-    protected static function _load_controller()
387
-    {
388
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
389
-            EE_Registry::instance()->load_core('Request_Handler');
390
-            self::set_autoloaders();
391
-            self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
392
-            self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
393
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
394
-        }
395
-    }
396
-
397
-
398
-    /**
399
-     * @param EE_Transaction $transaction
400
-     */
401
-    public static function payment_reminder(EE_Transaction $transaction)
402
-    {
403
-        self::_load_controller();
404
-        $data = array($transaction, null);
405
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
406
-    }
407
-
408
-
409
-    /**
410
-     * Any messages triggers for after successful gateway payments should go in here.
411
-     *
412
-     * @param  EE_Transaction object
413
-     * @param  EE_Payment     object
414
-     * @return void
415
-     */
416
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment)
417
-    {
418
-        self::_load_controller();
419
-        $data = array($transaction, $payment);
420
-        EE_Registry::instance()->load_helper('MSG_Template');
421
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
422
-        //if payment amount is less than 0 then switch to payment_refund message type.
423
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
424
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
425
-    }
426
-
427
-
428
-    /**
429
-     * @param EE_Transaction $transaction
430
-     */
431
-    public static function cancelled_registration(EE_Transaction $transaction)
432
-    {
433
-        self::_load_controller();
434
-        $data = array($transaction, null);
435
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * Trigger for Registration messages
442
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
443
-     * incoming transaction.
444
-     *
445
-     * @param EE_Registration $registration
446
-     * @param array           $extra_details
447
-     * @return void
448
-     * @throws EE_Error
449
-     * @throws EntityNotFoundException
450
-     */
451
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
452
-    {
453
-
454
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
455
-            //no messages please
456
-            return;
457
-        }
458
-
459
-        // get all non-trashed registrations so we make sure we send messages for the right status.
460
-        $all_registrations = $registration->transaction()->registrations(
461
-            array(
462
-                array('REG_deleted' => false),
463
-                'order_by' => array(
464
-                    'Event.EVT_name'     => 'ASC',
465
-                    'Attendee.ATT_lname' => 'ASC',
466
-                    'Attendee.ATT_fname' => 'ASC'
467
-                )
468
-            )
469
-        );
470
-        //cached array of statuses so we only trigger messages once per status.
471
-        $statuses_sent = array();
472
-        self::_load_controller();
473
-        $mtgs = array();
474
-
475
-        //loop through registrations and trigger messages once per status.
476
-        foreach ($all_registrations as $reg) {
477
-
478
-            //already triggered?
479
-            if (in_array($reg->status_ID(), $statuses_sent)) {
480
-                continue;
481
-            }
482
-
483
-            $message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
484
-            $mtgs            = array_merge(
485
-                    $mtgs,
486
-                    self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
487
-                            $message_type,
488
-                            array($registration->transaction(), null, $reg->status_ID())
489
-                    )
490
-            );
491
-            $statuses_sent[] = $reg->status_ID();
492
-        }
493
-
494
-        if (count($statuses_sent) > 1) {
495
-            $mtgs = array_merge(
496
-                $mtgs,
497
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
498
-                    'registration_summary',
499
-                    array($registration->transaction(), null)
500
-                )
501
-            );
502
-        }
503
-
504
-        //batch queue and initiate request
505
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
506
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
507
-    }
508
-
509
-
510
-    /**
511
-     * This is a helper method used to very whether a registration notification should be sent or
512
-     * not.  Prevents duplicate notifications going out for registration context notifications.
513
-     *
514
-     * @param EE_Registration $registration  [description]
515
-     * @param array           $extra_details [description]
516
-     * @return bool          true = send away, false = nope halt the presses.
517
-     */
518
-    protected static function _verify_registration_notification_send(
519
-        EE_Registration $registration,
520
-        $extra_details = array()
521
-    ) {
522
-        //self::log(
523
-        //	__CLASS__, __FUNCTION__, __LINE__,
524
-        //	$registration->transaction(),
525
-        //	array( '$extra_details' => $extra_details )
526
-        //);
527
-        // currently only using this to send messages for the primary registrant
528
-        if (! $registration->is_primary_registrant()) {
529
-            return false;
530
-        }
531
-        // first we check if we're in admin and not doing front ajax
532
-        if (is_admin() && ! EE_FRONT_AJAX) {
533
-            //make sure appropriate admin params are set for sending messages
534
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
535
-                //no messages sent please.
536
-                return false;
537
-            }
538
-        } else {
539
-            // frontend request (either regular or via AJAX)
540
-            // TXN is NOT finalized ?
541
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
542
-                return false;
543
-            }
544
-            // return visit but nothing changed ???
545
-            if (
546
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
547
-                $extra_details['revisit'] && ! $extra_details['status_updates']
548
-            ) {
549
-                return false;
550
-            }
551
-            // NOT sending messages && reg status is something other than "Not-Approved"
552
-            if (
553
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
554
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
555
-            ) {
556
-                return false;
557
-            }
558
-        }
559
-        // release the kraken
560
-        return true;
561
-    }
562
-
563
-
564
-    /**
565
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
566
-     * status id.
567
-     *
568
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
569
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
570
-     * @param string $reg_status
571
-     * @return array
572
-     */
573
-    protected static function _get_reg_status_array($reg_status = '')
574
-    {
575
-        EE_Registry::instance()->load_helper('MSG_Template');
576
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
577
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
578
-            : EEH_MSG_Template::reg_status_to_message_type_array();
579
-    }
580
-
581
-
582
-    /**
583
-     * Simply returns the payment message type for the given payment status.
584
-     *
585
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
586
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
587
-     * @param string $payment_status The payment status being matched.
588
-     * @return string|bool The payment message type slug matching the status or false if no match.
589
-     */
590
-    protected static function _get_payment_message_type($payment_status)
591
-    {
592
-        EE_Registry::instance()->load_helper('MSG_Template');
593
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
594
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
595
-            : false;
596
-    }
597
-
598
-
599
-    /**
600
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
601
-     *
602
-     * @access public
603
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
604
-     * @return bool          success/fail
605
-     */
606
-    public static function process_resend($req_data)
607
-    {
608
-        self::_load_controller();
609
-
610
-        //if $msgID in this request then skip to the new resend_message
611
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
612
-            return self::resend_message();
613
-        }
614
-
615
-        //make sure any incoming request data is set on the REQ so that it gets picked up later.
616
-        $req_data = (array)$req_data;
617
-        foreach ($req_data as $request_key => $request_value) {
618
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
619
-        }
620
-
621
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
622
-            return false;
623
-        }
624
-
625
-        try {
626
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
627
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
628
-        } catch (EE_Error $e) {
629
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
630
-            return false;
631
-        }
632
-        EE_Error::add_success(
633
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
634
-        );
635
-        return true; //everything got queued.
636
-    }
637
-
638
-
639
-    /**
640
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
641
-     *
642
-     * @return bool
643
-     */
644
-    public static function resend_message()
645
-    {
646
-        self::_load_controller();
647
-
648
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
649
-        if (! $msgID) {
650
-            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
651
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
652
-            return false;
653
-        }
654
-
655
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
656
-
657
-        //setup success message.
658
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
659
-        EE_Error::add_success(sprintf(
660
-            _n(
661
-                'There was %d message queued for resending.',
662
-                'There were %d messages queued for resending.',
663
-                $count_ready_for_resend,
664
-                'event_espresso'
665
-            ),
666
-            $count_ready_for_resend
667
-        ));
668
-        return true;
669
-    }
670
-
671
-
672
-    /**
673
-     * Message triggers for manual payment applied by admin
674
-     *
675
-     * @param  EE_Payment $payment EE_payment object
676
-     * @return bool              success/fail
677
-     */
678
-    public static function process_admin_payment(EE_Payment $payment)
679
-    {
680
-        EE_Registry::instance()->load_helper('MSG_Template');
681
-        //we need to get the transaction object
682
-        $transaction = $payment->transaction();
683
-        if ($transaction instanceof EE_Transaction) {
684
-            $data         = array($transaction, $payment);
685
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
686
-
687
-            //if payment amount is less than 0 then switch to payment_refund message type.
688
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
689
-
690
-            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
691
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
692
-
693
-            self::_load_controller();
694
-
695
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
696
-
697
-            //get count of queued for generation
698
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
699
-                EEM_Message::status_incomplete,
700
-                EEM_Message::status_idle,
701
-            ));
702
-
703
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
704
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
705
-                return true;
706
-            } else {
707
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
708
-                /**
709
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
710
-                 * IMMEDIATE generation.
711
-                 */
712
-                if ($count_failed > 0) {
713
-                    EE_Error::add_error(sprintf(
714
-                        _n(
715
-                            'The payment notification generation failed.',
716
-                            '%d payment notifications failed being sent.',
717
-                            $count_failed,
718
-                            'event_espresso'
719
-                        ),
720
-                        $count_failed
721
-                    ), __FILE__, __FUNCTION__, __LINE__);
722
-
723
-                    return false;
724
-                } else {
725
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
726
-                    return true;
727
-                }
728
-            }
729
-        } else {
730
-            EE_Error::add_error(
731
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
732
-                'event_espresso'
733
-            );
734
-            return false;
735
-        }
736
-    }
737
-
738
-
739
-    /**
740
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
741
-     *
742
-     * @since   4.3.0
743
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
744
-     * @param  int               $grp_id        a specific message template group id.
745
-     * @return void
746
-     */
747
-    public static function send_newsletter_message($registrations, $grp_id)
748
-    {
749
-        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
750
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
751
-        self::_load_controller();
752
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
753
-    }
754
-
755
-
756
-    /**
757
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
758
-     *
759
-     * @since   4.3.0
760
-     * @param    string          $registration_message_trigger_url
761
-     * @param    EE_Registration $registration
762
-     * @param string             $messenger
763
-     * @param string             $message_type
764
-     * @return    string
765
-     */
766
-    public static function registration_message_trigger_url(
767
-        $registration_message_trigger_url,
768
-        EE_Registration $registration,
769
-        $messenger = 'html',
770
-        $message_type = 'invoice'
771
-    ) {
772
-        // whitelist $messenger
773
-        switch ($messenger) {
774
-            case 'pdf' :
775
-                $sending_messenger    = 'pdf';
776
-                $generating_messenger = 'html';
777
-                break;
778
-            case 'html' :
779
-            default :
780
-                $sending_messenger    = 'html';
781
-                $generating_messenger = 'html';
782
-                break;
783
-        }
784
-        // whitelist $message_type
785
-        switch ($message_type) {
786
-            case 'receipt' :
787
-                $message_type = 'receipt';
788
-                break;
789
-            case 'invoice' :
790
-            default :
791
-                $message_type = 'invoice';
792
-                break;
793
-        }
794
-        // verify that both the messenger AND the message type are active
795
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
796
-            //need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
797
-            $template_query_params = array(
798
-                'MTP_is_active'    => true,
799
-                'MTP_messenger'    => $generating_messenger,
800
-                'MTP_message_type' => $message_type,
801
-                'Event.EVT_ID'     => $registration->event_ID(),
802
-            );
803
-            //get the message template group.
804
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
805
-            //if we don't have an EE_Message_Template_Group then return
806
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
807
-                // remove EVT_ID from query params so that global templates get picked up
808
-                unset($template_query_params['Event.EVT_ID']);
809
-                //get global template as the fallback
810
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
811
-            }
812
-            //if we don't have an EE_Message_Template_Group then return
813
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
814
-                return '';
815
-            }
816
-            // generate the URL
817
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
818
-                $sending_messenger,
819
-                $generating_messenger,
820
-                'purchaser',
821
-                $message_type,
822
-                $registration,
823
-                $msg_template_group->ID(),
824
-                $registration->transaction_ID()
825
-            );
826
-
827
-        }
828
-        return $registration_message_trigger_url;
829
-    }
830
-
831
-
832
-    /**
833
-     * Use to generate and return a message preview!
834
-     *
835
-     * @param  string $type      This should correspond with a valid message type
836
-     * @param  string $context   This should correspond with a valid context for the message type
837
-     * @param  string $messenger This should correspond with a valid messenger.
838
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
839
-     *                           preview
840
-     * @return bool|string The body of the message or if send is requested, sends.
841
-     * @throws EE_Error
842
-     */
843
-    public static function preview_message($type, $context, $messenger, $send = false)
844
-    {
845
-        self::_load_controller();
846
-        $mtg                     = new EE_Message_To_Generate(
847
-            $messenger,
848
-            $type,
849
-            array(),
850
-            $context,
851
-            true
852
-        );
853
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
854
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
855
-            $content = $generated_preview_queue->get_message_repository()->current()->content();
856
-            //if the current message was persisted to the db (which will happen with any extra fields on a message) then
857
-            //let's delete it because we don't need previews cluttering up the db.
858
-            if ($generated_preview_queue->get_message_repository()->current()->ID() > 0
859
-                && $generated_preview_queue->get_message_repository()->current()->STS_ID() !== EEM_Message::status_failed
860
-            ) {
861
-                $generated_preview_queue->get_message_repository()->delete();
862
-            }
863
-            return $content;
864
-        } else {
865
-            return $generated_preview_queue;
866
-        }
867
-    }
868
-
869
-
870
-    /**
871
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
872
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
873
-     * content found in the EE_Message objects in the queue.
874
-     *
875
-     * @since 4.9.0
876
-     * @param string            $messenger            a string matching a valid active messenger in the system
877
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
878
-     *                                                type name is still required to send along the message type to the
879
-     *                                                messenger because this is used for determining what specific
880
-     *                                                variations might be loaded for the generated message.
881
-     * @param EE_Messages_Queue $queue
882
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
883
-     *                                                aggregate EE_Message object.
884
-     * @return bool          success or fail.
885
-     */
886
-    public static function send_message_with_messenger_only(
887
-        $messenger,
888
-        $message_type,
889
-        EE_Messages_Queue $queue,
890
-        $custom_subject = ''
891
-    ) {
892
-        self::_load_controller();
893
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
894
-        $message_to_generate = EE_Registry::instance()->load_lib(
895
-            'Message_To_Generate_From_Queue',
896
-            array(
897
-                $messenger,
898
-                $message_type,
899
-                $queue,
900
-                $custom_subject,
901
-            )
902
-        );
903
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
904
-    }
905
-
906
-
907
-    /**
908
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
909
-     *
910
-     * @since 4.9.0
911
-     * @param array $message_ids An array of message ids
912
-     * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
913
-     *              messages.
914
-     */
915
-    public static function generate_now($message_ids)
916
-    {
917
-        self::_load_controller();
918
-        $messages        = EEM_Message::instance()->get_all(
919
-            array(
920
-                0 => array(
921
-                    'MSG_ID' => array('IN', $message_ids),
922
-                    'STS_ID' => EEM_Message::status_incomplete,
923
-                ),
924
-            )
925
-        );
926
-        $generated_queue = false;
927
-        if ($messages) {
928
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
929
-        }
930
-
931
-        if (! $generated_queue instanceof EE_Messages_Queue) {
932
-            EE_Error::add_error(
933
-                __('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
934
-                    'event_espresso'),
935
-                __FILE__, __FUNCTION__, __LINE__
936
-            );
937
-        }
938
-        return $generated_queue;
939
-    }
940
-
941
-
942
-    /**
943
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
944
-     * EEM_Message::status_idle
945
-     *
946
-     * @since 4.9.0
947
-     * @param $message_ids
948
-     * @return bool | EE_Messages_Queue  false if no messages sent.
949
-     */
950
-    public static function send_now($message_ids)
951
-    {
952
-        self::_load_controller();
953
-        $messages   = EEM_Message::instance()->get_all(
954
-            array(
955
-                0 => array(
956
-                    'MSG_ID' => array('IN', $message_ids),
957
-                    'STS_ID' => array(
958
-                        'IN',
959
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
960
-                    ),
961
-                ),
962
-            )
963
-        );
964
-        $sent_queue = false;
965
-        if ($messages) {
966
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
967
-        }
968
-
969
-        if (! $sent_queue instanceof EE_Messages_Queue) {
970
-            EE_Error::add_error(
971
-                __('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
972
-                    'event_espresso'),
973
-                __FILE__, __FUNCTION__, __LINE__
974
-            );
975
-        } else {
976
-            //can count how many sent by using the messages in the queue
977
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
978
-            if ($sent_count > 0) {
979
-                EE_Error::add_success(
980
-                    sprintf(
981
-                        _n(
982
-                            'There was %d message successfully sent.',
983
-                            'There were %d messages successfully sent.',
984
-                            $sent_count,
985
-                            'event_espresso'
986
-                        ),
987
-                        $sent_count
988
-                    )
989
-                );
990
-            } else {
991
-                EE_Error::overwrite_errors();
992
-                EE_Error::add_error(
993
-                    __('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
204
+				exit;
205
+			}
206
+		}
207
+		return;
208
+	}
209
+
210
+
211
+	/**
212
+	 *  This runs when the msg_url_trigger route has initiated.
213
+	 *
214
+	 * @since 4.5.0
215
+	 * @param WP $WP
216
+	 * @throws EE_Error
217
+	 * @return    void
218
+	 */
219
+	public function run($WP)
220
+	{
221
+		//ensure controller is loaded
222
+		self::_load_controller();
223
+		// attempt to process message
224
+		try {
225
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
226
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
227
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
228
+		} catch (EE_Error $e) {
229
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
230
+				'event_espresso');
231
+			// add specific message for developers if WP_DEBUG in on
232
+			$error_msg .= '||' . $e->getMessage();
233
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
234
+		}
235
+	}
236
+
237
+
238
+	/**
239
+	 * This is triggered by the 'msg_cron_trigger' route.
240
+	 *
241
+	 * @param WP $WP
242
+	 */
243
+	public function execute_batch_request($WP)
244
+	{
245
+		$this->run_cron();
246
+		header('HTTP/1.1 200 OK');
247
+		exit();
248
+	}
249
+
250
+
251
+	/**
252
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
253
+	 * request.
254
+	 */
255
+	public function run_cron()
256
+	{
257
+		self::_load_controller();
258
+		//get required vars
259
+		$cron_type     = EE_Registry::instance()->REQ->get('type');
260
+		$transient_key = EE_Registry::instance()->REQ->get('key');
261
+
262
+		//now let's verify transient, if not valid exit immediately
263
+		if (! get_transient($transient_key)) {
264
+			/**
265
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
266
+			 */
267
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
268
+		}
269
+
270
+		//if made it here, lets' delete the transient to keep the db clean
271
+		delete_transient($transient_key);
272
+
273
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
274
+
275
+			$method = 'batch_' . $cron_type . '_from_queue';
276
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
277
+				self::$_MSG_PROCESSOR->$method();
278
+			} else {
279
+				//no matching task
280
+				/**
281
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
282
+				 */
283
+				trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
284
+					$cron_type)));
285
+			}
286
+		}
287
+
288
+		do_action('FHEE__EED_Messages__run_cron__end');
289
+	}
290
+
291
+
292
+	/**
293
+	 * This is used to retrieve the template pack for the given name.
294
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
295
+	 * the default template pack is returned.
296
+	 *
297
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
298
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
299
+	 *                                   in generating the Pack class name).
300
+	 * @return EE_Messages_Template_Pack
301
+	 */
302
+	public static function get_template_pack($template_pack_name)
303
+	{
304
+		EE_Registry::instance()->load_helper('MSG_Template');
305
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
306
+	}
307
+
308
+
309
+	/**
310
+	 * Retrieves an array of all template packs.
311
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
312
+	 *
313
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
314
+	 * @return EE_Messages_Template_Pack[]
315
+	 */
316
+	public static function get_template_packs()
317
+	{
318
+		EE_Registry::instance()->load_helper('MSG_Template');
319
+
320
+		//for backward compat, let's make sure this returns in the same format as originally.
321
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
322
+		$template_pack_collection->rewind();
323
+		$template_packs = array();
324
+		while ($template_pack_collection->valid()) {
325
+			$template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
326
+			$template_pack_collection->next();
327
+		}
328
+		return $template_packs;
329
+	}
330
+
331
+
332
+	/**
333
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
334
+	 *
335
+	 * @since 4.5.0
336
+	 * @return void
337
+	 */
338
+	public static function set_autoloaders()
339
+	{
340
+		if (empty(self::$_MSG_PATHS)) {
341
+			self::_set_messages_paths();
342
+			foreach (self::$_MSG_PATHS as $path) {
343
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
344
+			}
345
+			// add aliases
346
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
347
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
348
+		}
349
+	}
350
+
351
+
352
+	/**
353
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
354
+	 * for use by the Messages Autoloaders
355
+	 *
356
+	 * @since 4.5.0
357
+	 * @return void.
358
+	 */
359
+	protected static function _set_messages_paths()
360
+	{
361
+		$dir_ref = array(
362
+			'messages/message_type',
363
+			'messages/messenger',
364
+			'messages/defaults',
365
+			'messages/defaults/email',
366
+			'messages/data_class',
367
+			'messages/validators',
368
+			'messages/validators/email',
369
+			'messages/validators/html',
370
+			'shortcodes',
371
+		);
372
+		$paths   = array();
373
+		foreach ($dir_ref as $index => $dir) {
374
+			$paths[$index] = EE_LIBRARIES . $dir;
375
+		}
376
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
377
+	}
378
+
379
+
380
+	/**
381
+	 * Takes care of loading dependencies
382
+	 *
383
+	 * @since 4.5.0
384
+	 * @return void
385
+	 */
386
+	protected static function _load_controller()
387
+	{
388
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
389
+			EE_Registry::instance()->load_core('Request_Handler');
390
+			self::set_autoloaders();
391
+			self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
392
+			self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
393
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
394
+		}
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param EE_Transaction $transaction
400
+	 */
401
+	public static function payment_reminder(EE_Transaction $transaction)
402
+	{
403
+		self::_load_controller();
404
+		$data = array($transaction, null);
405
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
406
+	}
407
+
408
+
409
+	/**
410
+	 * Any messages triggers for after successful gateway payments should go in here.
411
+	 *
412
+	 * @param  EE_Transaction object
413
+	 * @param  EE_Payment     object
414
+	 * @return void
415
+	 */
416
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment)
417
+	{
418
+		self::_load_controller();
419
+		$data = array($transaction, $payment);
420
+		EE_Registry::instance()->load_helper('MSG_Template');
421
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
422
+		//if payment amount is less than 0 then switch to payment_refund message type.
423
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
424
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
425
+	}
426
+
427
+
428
+	/**
429
+	 * @param EE_Transaction $transaction
430
+	 */
431
+	public static function cancelled_registration(EE_Transaction $transaction)
432
+	{
433
+		self::_load_controller();
434
+		$data = array($transaction, null);
435
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * Trigger for Registration messages
442
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
443
+	 * incoming transaction.
444
+	 *
445
+	 * @param EE_Registration $registration
446
+	 * @param array           $extra_details
447
+	 * @return void
448
+	 * @throws EE_Error
449
+	 * @throws EntityNotFoundException
450
+	 */
451
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
452
+	{
453
+
454
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
455
+			//no messages please
456
+			return;
457
+		}
458
+
459
+		// get all non-trashed registrations so we make sure we send messages for the right status.
460
+		$all_registrations = $registration->transaction()->registrations(
461
+			array(
462
+				array('REG_deleted' => false),
463
+				'order_by' => array(
464
+					'Event.EVT_name'     => 'ASC',
465
+					'Attendee.ATT_lname' => 'ASC',
466
+					'Attendee.ATT_fname' => 'ASC'
467
+				)
468
+			)
469
+		);
470
+		//cached array of statuses so we only trigger messages once per status.
471
+		$statuses_sent = array();
472
+		self::_load_controller();
473
+		$mtgs = array();
474
+
475
+		//loop through registrations and trigger messages once per status.
476
+		foreach ($all_registrations as $reg) {
477
+
478
+			//already triggered?
479
+			if (in_array($reg->status_ID(), $statuses_sent)) {
480
+				continue;
481
+			}
482
+
483
+			$message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
484
+			$mtgs            = array_merge(
485
+					$mtgs,
486
+					self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
487
+							$message_type,
488
+							array($registration->transaction(), null, $reg->status_ID())
489
+					)
490
+			);
491
+			$statuses_sent[] = $reg->status_ID();
492
+		}
493
+
494
+		if (count($statuses_sent) > 1) {
495
+			$mtgs = array_merge(
496
+				$mtgs,
497
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
498
+					'registration_summary',
499
+					array($registration->transaction(), null)
500
+				)
501
+			);
502
+		}
503
+
504
+		//batch queue and initiate request
505
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
506
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
507
+	}
508
+
509
+
510
+	/**
511
+	 * This is a helper method used to very whether a registration notification should be sent or
512
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
513
+	 *
514
+	 * @param EE_Registration $registration  [description]
515
+	 * @param array           $extra_details [description]
516
+	 * @return bool          true = send away, false = nope halt the presses.
517
+	 */
518
+	protected static function _verify_registration_notification_send(
519
+		EE_Registration $registration,
520
+		$extra_details = array()
521
+	) {
522
+		//self::log(
523
+		//	__CLASS__, __FUNCTION__, __LINE__,
524
+		//	$registration->transaction(),
525
+		//	array( '$extra_details' => $extra_details )
526
+		//);
527
+		// currently only using this to send messages for the primary registrant
528
+		if (! $registration->is_primary_registrant()) {
529
+			return false;
530
+		}
531
+		// first we check if we're in admin and not doing front ajax
532
+		if (is_admin() && ! EE_FRONT_AJAX) {
533
+			//make sure appropriate admin params are set for sending messages
534
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
535
+				//no messages sent please.
536
+				return false;
537
+			}
538
+		} else {
539
+			// frontend request (either regular or via AJAX)
540
+			// TXN is NOT finalized ?
541
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
542
+				return false;
543
+			}
544
+			// return visit but nothing changed ???
545
+			if (
546
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
547
+				$extra_details['revisit'] && ! $extra_details['status_updates']
548
+			) {
549
+				return false;
550
+			}
551
+			// NOT sending messages && reg status is something other than "Not-Approved"
552
+			if (
553
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
554
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
555
+			) {
556
+				return false;
557
+			}
558
+		}
559
+		// release the kraken
560
+		return true;
561
+	}
562
+
563
+
564
+	/**
565
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
566
+	 * status id.
567
+	 *
568
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
569
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
570
+	 * @param string $reg_status
571
+	 * @return array
572
+	 */
573
+	protected static function _get_reg_status_array($reg_status = '')
574
+	{
575
+		EE_Registry::instance()->load_helper('MSG_Template');
576
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
577
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
578
+			: EEH_MSG_Template::reg_status_to_message_type_array();
579
+	}
580
+
581
+
582
+	/**
583
+	 * Simply returns the payment message type for the given payment status.
584
+	 *
585
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
586
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
587
+	 * @param string $payment_status The payment status being matched.
588
+	 * @return string|bool The payment message type slug matching the status or false if no match.
589
+	 */
590
+	protected static function _get_payment_message_type($payment_status)
591
+	{
592
+		EE_Registry::instance()->load_helper('MSG_Template');
593
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
594
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
595
+			: false;
596
+	}
597
+
598
+
599
+	/**
600
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
601
+	 *
602
+	 * @access public
603
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
604
+	 * @return bool          success/fail
605
+	 */
606
+	public static function process_resend($req_data)
607
+	{
608
+		self::_load_controller();
609
+
610
+		//if $msgID in this request then skip to the new resend_message
611
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
612
+			return self::resend_message();
613
+		}
614
+
615
+		//make sure any incoming request data is set on the REQ so that it gets picked up later.
616
+		$req_data = (array)$req_data;
617
+		foreach ($req_data as $request_key => $request_value) {
618
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
619
+		}
620
+
621
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
622
+			return false;
623
+		}
624
+
625
+		try {
626
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
627
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
628
+		} catch (EE_Error $e) {
629
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
630
+			return false;
631
+		}
632
+		EE_Error::add_success(
633
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
634
+		);
635
+		return true; //everything got queued.
636
+	}
637
+
638
+
639
+	/**
640
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
641
+	 *
642
+	 * @return bool
643
+	 */
644
+	public static function resend_message()
645
+	{
646
+		self::_load_controller();
647
+
648
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
649
+		if (! $msgID) {
650
+			EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
651
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
652
+			return false;
653
+		}
654
+
655
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
656
+
657
+		//setup success message.
658
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
659
+		EE_Error::add_success(sprintf(
660
+			_n(
661
+				'There was %d message queued for resending.',
662
+				'There were %d messages queued for resending.',
663
+				$count_ready_for_resend,
664
+				'event_espresso'
665
+			),
666
+			$count_ready_for_resend
667
+		));
668
+		return true;
669
+	}
670
+
671
+
672
+	/**
673
+	 * Message triggers for manual payment applied by admin
674
+	 *
675
+	 * @param  EE_Payment $payment EE_payment object
676
+	 * @return bool              success/fail
677
+	 */
678
+	public static function process_admin_payment(EE_Payment $payment)
679
+	{
680
+		EE_Registry::instance()->load_helper('MSG_Template');
681
+		//we need to get the transaction object
682
+		$transaction = $payment->transaction();
683
+		if ($transaction instanceof EE_Transaction) {
684
+			$data         = array($transaction, $payment);
685
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
686
+
687
+			//if payment amount is less than 0 then switch to payment_refund message type.
688
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
689
+
690
+			//if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
691
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
692
+
693
+			self::_load_controller();
694
+
695
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
696
+
697
+			//get count of queued for generation
698
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
699
+				EEM_Message::status_incomplete,
700
+				EEM_Message::status_idle,
701
+			));
702
+
703
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
704
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
705
+				return true;
706
+			} else {
707
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
708
+				/**
709
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
710
+				 * IMMEDIATE generation.
711
+				 */
712
+				if ($count_failed > 0) {
713
+					EE_Error::add_error(sprintf(
714
+						_n(
715
+							'The payment notification generation failed.',
716
+							'%d payment notifications failed being sent.',
717
+							$count_failed,
718
+							'event_espresso'
719
+						),
720
+						$count_failed
721
+					), __FILE__, __FUNCTION__, __LINE__);
722
+
723
+					return false;
724
+				} else {
725
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
726
+					return true;
727
+				}
728
+			}
729
+		} else {
730
+			EE_Error::add_error(
731
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
732
+				'event_espresso'
733
+			);
734
+			return false;
735
+		}
736
+	}
737
+
738
+
739
+	/**
740
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
741
+	 *
742
+	 * @since   4.3.0
743
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
744
+	 * @param  int               $grp_id        a specific message template group id.
745
+	 * @return void
746
+	 */
747
+	public static function send_newsletter_message($registrations, $grp_id)
748
+	{
749
+		//make sure mtp is id and set it in the EE_Request Handler later messages setup.
750
+		EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
751
+		self::_load_controller();
752
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
753
+	}
754
+
755
+
756
+	/**
757
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
758
+	 *
759
+	 * @since   4.3.0
760
+	 * @param    string          $registration_message_trigger_url
761
+	 * @param    EE_Registration $registration
762
+	 * @param string             $messenger
763
+	 * @param string             $message_type
764
+	 * @return    string
765
+	 */
766
+	public static function registration_message_trigger_url(
767
+		$registration_message_trigger_url,
768
+		EE_Registration $registration,
769
+		$messenger = 'html',
770
+		$message_type = 'invoice'
771
+	) {
772
+		// whitelist $messenger
773
+		switch ($messenger) {
774
+			case 'pdf' :
775
+				$sending_messenger    = 'pdf';
776
+				$generating_messenger = 'html';
777
+				break;
778
+			case 'html' :
779
+			default :
780
+				$sending_messenger    = 'html';
781
+				$generating_messenger = 'html';
782
+				break;
783
+		}
784
+		// whitelist $message_type
785
+		switch ($message_type) {
786
+			case 'receipt' :
787
+				$message_type = 'receipt';
788
+				break;
789
+			case 'invoice' :
790
+			default :
791
+				$message_type = 'invoice';
792
+				break;
793
+		}
794
+		// verify that both the messenger AND the message type are active
795
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
796
+			//need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
797
+			$template_query_params = array(
798
+				'MTP_is_active'    => true,
799
+				'MTP_messenger'    => $generating_messenger,
800
+				'MTP_message_type' => $message_type,
801
+				'Event.EVT_ID'     => $registration->event_ID(),
802
+			);
803
+			//get the message template group.
804
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
805
+			//if we don't have an EE_Message_Template_Group then return
806
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
807
+				// remove EVT_ID from query params so that global templates get picked up
808
+				unset($template_query_params['Event.EVT_ID']);
809
+				//get global template as the fallback
810
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
811
+			}
812
+			//if we don't have an EE_Message_Template_Group then return
813
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
814
+				return '';
815
+			}
816
+			// generate the URL
817
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
818
+				$sending_messenger,
819
+				$generating_messenger,
820
+				'purchaser',
821
+				$message_type,
822
+				$registration,
823
+				$msg_template_group->ID(),
824
+				$registration->transaction_ID()
825
+			);
826
+
827
+		}
828
+		return $registration_message_trigger_url;
829
+	}
830
+
831
+
832
+	/**
833
+	 * Use to generate and return a message preview!
834
+	 *
835
+	 * @param  string $type      This should correspond with a valid message type
836
+	 * @param  string $context   This should correspond with a valid context for the message type
837
+	 * @param  string $messenger This should correspond with a valid messenger.
838
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
839
+	 *                           preview
840
+	 * @return bool|string The body of the message or if send is requested, sends.
841
+	 * @throws EE_Error
842
+	 */
843
+	public static function preview_message($type, $context, $messenger, $send = false)
844
+	{
845
+		self::_load_controller();
846
+		$mtg                     = new EE_Message_To_Generate(
847
+			$messenger,
848
+			$type,
849
+			array(),
850
+			$context,
851
+			true
852
+		);
853
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
854
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
855
+			$content = $generated_preview_queue->get_message_repository()->current()->content();
856
+			//if the current message was persisted to the db (which will happen with any extra fields on a message) then
857
+			//let's delete it because we don't need previews cluttering up the db.
858
+			if ($generated_preview_queue->get_message_repository()->current()->ID() > 0
859
+				&& $generated_preview_queue->get_message_repository()->current()->STS_ID() !== EEM_Message::status_failed
860
+			) {
861
+				$generated_preview_queue->get_message_repository()->delete();
862
+			}
863
+			return $content;
864
+		} else {
865
+			return $generated_preview_queue;
866
+		}
867
+	}
868
+
869
+
870
+	/**
871
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
872
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
873
+	 * content found in the EE_Message objects in the queue.
874
+	 *
875
+	 * @since 4.9.0
876
+	 * @param string            $messenger            a string matching a valid active messenger in the system
877
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
878
+	 *                                                type name is still required to send along the message type to the
879
+	 *                                                messenger because this is used for determining what specific
880
+	 *                                                variations might be loaded for the generated message.
881
+	 * @param EE_Messages_Queue $queue
882
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
883
+	 *                                                aggregate EE_Message object.
884
+	 * @return bool          success or fail.
885
+	 */
886
+	public static function send_message_with_messenger_only(
887
+		$messenger,
888
+		$message_type,
889
+		EE_Messages_Queue $queue,
890
+		$custom_subject = ''
891
+	) {
892
+		self::_load_controller();
893
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
894
+		$message_to_generate = EE_Registry::instance()->load_lib(
895
+			'Message_To_Generate_From_Queue',
896
+			array(
897
+				$messenger,
898
+				$message_type,
899
+				$queue,
900
+				$custom_subject,
901
+			)
902
+		);
903
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
904
+	}
905
+
906
+
907
+	/**
908
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
909
+	 *
910
+	 * @since 4.9.0
911
+	 * @param array $message_ids An array of message ids
912
+	 * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
913
+	 *              messages.
914
+	 */
915
+	public static function generate_now($message_ids)
916
+	{
917
+		self::_load_controller();
918
+		$messages        = EEM_Message::instance()->get_all(
919
+			array(
920
+				0 => array(
921
+					'MSG_ID' => array('IN', $message_ids),
922
+					'STS_ID' => EEM_Message::status_incomplete,
923
+				),
924
+			)
925
+		);
926
+		$generated_queue = false;
927
+		if ($messages) {
928
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
929
+		}
930
+
931
+		if (! $generated_queue instanceof EE_Messages_Queue) {
932
+			EE_Error::add_error(
933
+				__('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
934
+					'event_espresso'),
935
+				__FILE__, __FUNCTION__, __LINE__
936
+			);
937
+		}
938
+		return $generated_queue;
939
+	}
940
+
941
+
942
+	/**
943
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
944
+	 * EEM_Message::status_idle
945
+	 *
946
+	 * @since 4.9.0
947
+	 * @param $message_ids
948
+	 * @return bool | EE_Messages_Queue  false if no messages sent.
949
+	 */
950
+	public static function send_now($message_ids)
951
+	{
952
+		self::_load_controller();
953
+		$messages   = EEM_Message::instance()->get_all(
954
+			array(
955
+				0 => array(
956
+					'MSG_ID' => array('IN', $message_ids),
957
+					'STS_ID' => array(
958
+						'IN',
959
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
960
+					),
961
+				),
962
+			)
963
+		);
964
+		$sent_queue = false;
965
+		if ($messages) {
966
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
967
+		}
968
+
969
+		if (! $sent_queue instanceof EE_Messages_Queue) {
970
+			EE_Error::add_error(
971
+				__('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
972
+					'event_espresso'),
973
+				__FILE__, __FUNCTION__, __LINE__
974
+			);
975
+		} else {
976
+			//can count how many sent by using the messages in the queue
977
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
978
+			if ($sent_count > 0) {
979
+				EE_Error::add_success(
980
+					sprintf(
981
+						_n(
982
+							'There was %d message successfully sent.',
983
+							'There were %d messages successfully sent.',
984
+							$sent_count,
985
+							'event_espresso'
986
+						),
987
+						$sent_count
988
+					)
989
+				);
990
+			} else {
991
+				EE_Error::overwrite_errors();
992
+				EE_Error::add_error(
993
+					__('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
994 994
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
995
-                        'event_espresso'),
996
-                    __FILE__, __FUNCTION__, __LINE__
997
-                );
998
-            }
999
-        }
1000
-        return $sent_queue;
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * This will queue the incoming message ids for resending.
1006
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1007
-     *
1008
-     * @since 4.9.0
1009
-     * @param array $message_ids An array of EE_Message IDs
1010
-     * @return bool  true means messages were successfully queued for resending, false means none were queued for
1011
-     *               resending.
1012
-     */
1013
-    public static function queue_for_resending($message_ids)
1014
-    {
1015
-        self::_load_controller();
1016
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1017
-
1018
-        //get queue and count
1019
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1020
-
1021
-        if (
1022
-            $queue_count > 0
1023
-        ) {
1024
-            EE_Error::add_success(
1025
-                sprintf(
1026
-                    _n(
1027
-                        '%d message successfully queued for resending.',
1028
-                        '%d messages successfully queued for resending.',
1029
-                        $queue_count,
1030
-                        'event_espresso'
1031
-                    ),
1032
-                    $queue_count
1033
-                )
1034
-            );
1035
-            /**
1036
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1037
-             */
1038
-        } elseif (
1039
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1040
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1041
-        ) {
1042
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1043
-            if ($queue_count > 0) {
1044
-                EE_Error::add_success(
1045
-                    sprintf(
1046
-                        _n(
1047
-                            '%d message successfully sent.',
1048
-                            '%d messages successfully sent.',
1049
-                            $queue_count,
1050
-                            'event_espresso'
1051
-                        ),
1052
-                        $queue_count
1053
-                    )
1054
-                );
1055
-            } else {
1056
-                EE_Error::add_error(
1057
-                    __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1058
-                        'event_espresso'),
1059
-                    __FILE__, __FUNCTION__, __LINE__
1060
-                );
1061
-            }
1062
-        } else {
1063
-            EE_Error::add_error(
1064
-                __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1065
-                    'event_espresso'),
1066
-                __FILE__, __FUNCTION__, __LINE__
1067
-            );
1068
-        }
1069
-        return (bool)$queue_count;
1070
-    }
1071
-
1072
-
1073
-    /**
1074
-     * debug
1075
-     *
1076
-     * @param string          $class
1077
-     * @param string          $func
1078
-     * @param string          $line
1079
-     * @param \EE_Transaction $transaction
1080
-     * @param array           $info
1081
-     * @param bool            $display_request
1082
-     */
1083
-    protected static function log(
1084
-        $class = '',
1085
-        $func = '',
1086
-        $line = '',
1087
-        EE_Transaction $transaction,
1088
-        $info = array(),
1089
-        $display_request = false
1090
-    ) {
1091
-        if (WP_DEBUG && false) {
1092
-            if ($transaction instanceof EE_Transaction) {
1093
-                // don't serialize objects
1094
-                $info                  = EEH_Debug_Tools::strip_objects($info);
1095
-                $info['TXN_status']    = $transaction->status_ID();
1096
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1097
-                if ($transaction->ID()) {
1098
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1099
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1100
-                }
1101
-            }
1102
-        }
1103
-
1104
-    }
1105
-
1106
-
1107
-    /**
1108
-     *  Resets all the static properties in this class when called.
1109
-     */
1110
-    public static function reset()
1111
-    {
1112
-        self::$_EEMSG                    = null;
1113
-        self::$_message_resource_manager = null;
1114
-        self::$_MSG_PROCESSOR            = null;
1115
-        self::$_MSG_PATHS                = null;
1116
-        self::$_TMP_PACKS                = array();
1117
-    }
995
+						'event_espresso'),
996
+					__FILE__, __FUNCTION__, __LINE__
997
+				);
998
+			}
999
+		}
1000
+		return $sent_queue;
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * This will queue the incoming message ids for resending.
1006
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1007
+	 *
1008
+	 * @since 4.9.0
1009
+	 * @param array $message_ids An array of EE_Message IDs
1010
+	 * @return bool  true means messages were successfully queued for resending, false means none were queued for
1011
+	 *               resending.
1012
+	 */
1013
+	public static function queue_for_resending($message_ids)
1014
+	{
1015
+		self::_load_controller();
1016
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1017
+
1018
+		//get queue and count
1019
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1020
+
1021
+		if (
1022
+			$queue_count > 0
1023
+		) {
1024
+			EE_Error::add_success(
1025
+				sprintf(
1026
+					_n(
1027
+						'%d message successfully queued for resending.',
1028
+						'%d messages successfully queued for resending.',
1029
+						$queue_count,
1030
+						'event_espresso'
1031
+					),
1032
+					$queue_count
1033
+				)
1034
+			);
1035
+			/**
1036
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1037
+			 */
1038
+		} elseif (
1039
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1040
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1041
+		) {
1042
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1043
+			if ($queue_count > 0) {
1044
+				EE_Error::add_success(
1045
+					sprintf(
1046
+						_n(
1047
+							'%d message successfully sent.',
1048
+							'%d messages successfully sent.',
1049
+							$queue_count,
1050
+							'event_espresso'
1051
+						),
1052
+						$queue_count
1053
+					)
1054
+				);
1055
+			} else {
1056
+				EE_Error::add_error(
1057
+					__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1058
+						'event_espresso'),
1059
+					__FILE__, __FUNCTION__, __LINE__
1060
+				);
1061
+			}
1062
+		} else {
1063
+			EE_Error::add_error(
1064
+				__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1065
+					'event_espresso'),
1066
+				__FILE__, __FUNCTION__, __LINE__
1067
+			);
1068
+		}
1069
+		return (bool)$queue_count;
1070
+	}
1071
+
1072
+
1073
+	/**
1074
+	 * debug
1075
+	 *
1076
+	 * @param string          $class
1077
+	 * @param string          $func
1078
+	 * @param string          $line
1079
+	 * @param \EE_Transaction $transaction
1080
+	 * @param array           $info
1081
+	 * @param bool            $display_request
1082
+	 */
1083
+	protected static function log(
1084
+		$class = '',
1085
+		$func = '',
1086
+		$line = '',
1087
+		EE_Transaction $transaction,
1088
+		$info = array(),
1089
+		$display_request = false
1090
+	) {
1091
+		if (WP_DEBUG && false) {
1092
+			if ($transaction instanceof EE_Transaction) {
1093
+				// don't serialize objects
1094
+				$info                  = EEH_Debug_Tools::strip_objects($info);
1095
+				$info['TXN_status']    = $transaction->status_ID();
1096
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1097
+				if ($transaction->ID()) {
1098
+					$index = 'EE_Transaction: ' . $transaction->ID();
1099
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1100
+				}
1101
+			}
1102
+		}
1103
+
1104
+	}
1105
+
1106
+
1107
+	/**
1108
+	 *  Resets all the static properties in this class when called.
1109
+	 */
1110
+	public static function reset()
1111
+	{
1112
+		self::$_EEMSG                    = null;
1113
+		self::$_message_resource_manager = null;
1114
+		self::$_MSG_PROCESSOR            = null;
1115
+		self::$_MSG_PATHS                = null;
1116
+		self::$_TMP_PACKS                = array();
1117
+	}
1118 1118
 
1119 1119
 }
1120 1120
 // End of file EED_Messages.module.php
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.054');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.46.rc.054');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
core/services/Benchmark.php 2 patches
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -17,309 +17,309 @@
 block discarded – undo
17 17
 class Benchmark
18 18
 {
19 19
 
20
-    /**
21
-     * array containing the start time for the timers
22
-     */
23
-    private static $start_times;
24
-
25
-    /**
26
-     * array containing all the timer'd times, which can be outputted via show_times()
27
-     */
28
-    private static $times = array();
29
-
30
-    /**
31
-     * @var array
32
-     */
33
-    protected static $memory_usage = array();
34
-
35
-
36
-
37
-    /**
38
-     * whether to benchmark code or not
39
-     */
40
-    public static function doNotRun()
41
-    {
42
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * resetTimes
49
-     */
50
-    public static function resetTimes()
51
-    {
52
-        Benchmark::$times = array();
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
-     *
60
-     * @param null $timer_name
61
-     */
62
-    public static function startTimer($timer_name = null)
63
-    {
64
-        if (Benchmark::doNotRun()) {
65
-            return;
66
-        }
67
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
-        Benchmark::$start_times[$timer_name] = microtime(true);
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
-     *
76
-     * @param string $timer_name
77
-     */
78
-    public static function stopTimer($timer_name = '')
79
-    {
80
-        if (Benchmark::doNotRun()) {
81
-            return;
82
-        }
83
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
-        if (isset(Benchmark::$start_times[$timer_name])) {
85
-            $start_time = Benchmark::$start_times[$timer_name];
86
-            unset(Benchmark::$start_times[$timer_name]);
87
-        } else {
88
-            $start_time = array_pop(Benchmark::$start_times);
89
-        }
90
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * Measure the memory usage by PHP so far.
97
-     *
98
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
-     * @param bool    $formatted
101
-     * @return void
102
-     */
103
-    public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
104
-    {
105
-        if (Benchmark::doNotRun()) {
106
-            return;
107
-        }
108
-        $memory_used = Benchmark::convert(memory_get_usage(true));
109
-        Benchmark::$memory_usage[$label] = $memory_used;
110
-        if ($output_now) {
111
-            echo $formatted
112
-                ? "<br>{$label} : {$memory_used}"
113
-                : "\n {$label} : {$memory_used}";
114
-        }
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * will display the benchmarking results at shutdown
121
-     *
122
-     * @param bool $formatted
123
-     * @return void
124
-     */
125
-    public static function displayResultsAtShutdown($formatted = true)
126
-    {
127
-        add_action(
128
-            'shutdown',
129
-            function () use ($formatted) {
130
-                Benchmark::displayResults(true, $formatted);
131
-            }
132
-        );
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     * will display the benchmarking results at shutdown
139
-     *
140
-     * @param string $filepath
141
-     * @param bool   $formatted
142
-     * @param bool   $append
143
-     * @return void
144
-     */
145
-    public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
146
-    {
147
-        add_action(
148
-            'shutdown',
149
-            function () use ($filepath, $formatted, $append) {
150
-                Benchmark::writeResultsToFile($filepath, $formatted, $append);
151
-            }
152
-        );
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * @param bool $formatted
159
-     * @return string
160
-     */
161
-    private static function generateResults($formatted = true)
162
-    {
163
-        if (Benchmark::doNotRun()) {
164
-            return '';
165
-        }
166
-        $output = '';
167
-        if (! empty(Benchmark::$times)) {
168
-            $total = 0;
169
-            $output .= $formatted
170
-                ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171
-                : '';
172
-            foreach (Benchmark::$times as $timer_name => $total_time) {
173
-                $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
-                $output .= $formatted ? '<br />'  : "\n";
175
-                $total += $total_time;
176
-            }
177
-            if($formatted) {
178
-                $output .= '<br />';
179
-                $output .= '<h4>TOTAL TIME</h4>';
180
-                $output .= Benchmark::formatTime('', $total, $formatted);
181
-                $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
182
-                $output .= '<br />';
183
-                $output .= '<h5>Performance scale (from best to worse)</h5>';
184
-                $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
185
-                $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
186
-                $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
187
-                $output .= '<span style="color:gold">Ruh Oh</span><br />';
188
-                $output .= '<span style="color:darkorange">Zoinks!</span><br />';
189
-                $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190
-            }
191
-        }
192
-        if (! empty(Benchmark::$memory_usage)) {
193
-            $output .= $formatted
194
-                ? '<h5>Memory</h5>'
195
-                : "\nMemory";
196
-            foreach (Benchmark::$memory_usage as $label => $memory_usage) {
197
-                $output .= $formatted
198
-                    ? '<br />'
199
-                    : "\n";
200
-                $output .= "{$memory_usage} : {$label}";
201
-            }
202
-        }
203
-        if (empty($output)) {
204
-            return '';
205
-        }
206
-        $output = $formatted
207
-            ? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
208
-              . (is_admin()
209
-                ? ' margin:2em 2em 2em 180px;'
210
-                : ' margin:2em;')
211
-              . ' padding:2em;">'
212
-              . '<h4>BENCHMARKING</h4>'
213
-              . $output
214
-              . '</div>'
215
-            : $output;
216
-        return $output;
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * @param bool $echo
223
-     * @param bool $formatted
224
-     * @return string
225
-     */
226
-    public static function displayResults($echo = true, $formatted = true)
227
-    {
228
-        $results = Benchmark::generateResults($formatted);
229
-        if ($echo) {
230
-            echo $results;
231
-            $results = '';
232
-        }
233
-        return $results;
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * @param string $filepath
240
-     * @param bool   $formatted
241
-     * @param bool   $append
242
-     */
243
-    public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
244
-    {
245
-        $filepath = ! empty($filepath) && is_readable(dirname($filepath))
246
-            ? $filepath
247
-            : '';
248
-        if( empty($filepath)) {
249
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
250
-        }
251
-        file_put_contents(
252
-            $filepath,
253
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
254
-            $append ? FILE_APPEND | LOCK_EX : LOCK_EX
255
-        );
256
-    }
257
-
258
-
259
-
260
-    /**
261
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
262
-     *
263
-     * @param int $size
264
-     * @return string
265
-     */
266
-    public static function convert($size)
267
-    {
268
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
269
-        return round(
270
-            $size / pow(1024, $i = floor(log($size, 1024))),
271
-            2
272
-        ) . ' ' . $unit[absint($i)];
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * @param string $timer_name
279
-     * @param float  $total_time
280
-     * @param bool   $formatted
281
-     * @return string
282
-     */
283
-    public static function formatTime($timer_name, $total_time, $formatted = true)
284
-    {
285
-        $total_time *= 1000;
286
-        switch ($total_time) {
287
-            case $total_time > 12500 :
288
-                $color = 'red';
289
-                $bold = 'bold';
290
-                break;
291
-            case $total_time > 2500 :
292
-                $color = 'darkorange';
293
-                $bold = 'bold';
294
-                break;
295
-            case $total_time > 500 :
296
-                $color = 'gold';
297
-                $bold = 'bold';
298
-                break;
299
-            case $total_time > 100 :
300
-                $color = 'limegreen';
301
-                $bold = 'normal';
302
-                break;
303
-            case $total_time > 20 :
304
-                $color = 'deepskyblue';
305
-                $bold = 'normal';
306
-                break;
307
-            default :
308
-                $color = 'mediumpurple';
309
-                $bold = 'normal';
310
-                break;
311
-        }
312
-        return $formatted
313
-            ? '<span style="min-width: 10px; margin:0 1em; color:'
314
-               . $color
315
-               . '; font-weight:'
316
-               . $bold
317
-               . '; font-size:1.2em;">'
318
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
319
-               . '</span> '
320
-               . $timer_name
321
-            :  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
322
-    }
20
+	/**
21
+	 * array containing the start time for the timers
22
+	 */
23
+	private static $start_times;
24
+
25
+	/**
26
+	 * array containing all the timer'd times, which can be outputted via show_times()
27
+	 */
28
+	private static $times = array();
29
+
30
+	/**
31
+	 * @var array
32
+	 */
33
+	protected static $memory_usage = array();
34
+
35
+
36
+
37
+	/**
38
+	 * whether to benchmark code or not
39
+	 */
40
+	public static function doNotRun()
41
+	{
42
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * resetTimes
49
+	 */
50
+	public static function resetTimes()
51
+	{
52
+		Benchmark::$times = array();
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
+	 *
60
+	 * @param null $timer_name
61
+	 */
62
+	public static function startTimer($timer_name = null)
63
+	{
64
+		if (Benchmark::doNotRun()) {
65
+			return;
66
+		}
67
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
+		Benchmark::$start_times[$timer_name] = microtime(true);
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
+	 *
76
+	 * @param string $timer_name
77
+	 */
78
+	public static function stopTimer($timer_name = '')
79
+	{
80
+		if (Benchmark::doNotRun()) {
81
+			return;
82
+		}
83
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
+		if (isset(Benchmark::$start_times[$timer_name])) {
85
+			$start_time = Benchmark::$start_times[$timer_name];
86
+			unset(Benchmark::$start_times[$timer_name]);
87
+		} else {
88
+			$start_time = array_pop(Benchmark::$start_times);
89
+		}
90
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * Measure the memory usage by PHP so far.
97
+	 *
98
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
+	 * @param bool    $formatted
101
+	 * @return void
102
+	 */
103
+	public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
104
+	{
105
+		if (Benchmark::doNotRun()) {
106
+			return;
107
+		}
108
+		$memory_used = Benchmark::convert(memory_get_usage(true));
109
+		Benchmark::$memory_usage[$label] = $memory_used;
110
+		if ($output_now) {
111
+			echo $formatted
112
+				? "<br>{$label} : {$memory_used}"
113
+				: "\n {$label} : {$memory_used}";
114
+		}
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * will display the benchmarking results at shutdown
121
+	 *
122
+	 * @param bool $formatted
123
+	 * @return void
124
+	 */
125
+	public static function displayResultsAtShutdown($formatted = true)
126
+	{
127
+		add_action(
128
+			'shutdown',
129
+			function () use ($formatted) {
130
+				Benchmark::displayResults(true, $formatted);
131
+			}
132
+		);
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 * will display the benchmarking results at shutdown
139
+	 *
140
+	 * @param string $filepath
141
+	 * @param bool   $formatted
142
+	 * @param bool   $append
143
+	 * @return void
144
+	 */
145
+	public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
146
+	{
147
+		add_action(
148
+			'shutdown',
149
+			function () use ($filepath, $formatted, $append) {
150
+				Benchmark::writeResultsToFile($filepath, $formatted, $append);
151
+			}
152
+		);
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * @param bool $formatted
159
+	 * @return string
160
+	 */
161
+	private static function generateResults($formatted = true)
162
+	{
163
+		if (Benchmark::doNotRun()) {
164
+			return '';
165
+		}
166
+		$output = '';
167
+		if (! empty(Benchmark::$times)) {
168
+			$total = 0;
169
+			$output .= $formatted
170
+				? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171
+				: '';
172
+			foreach (Benchmark::$times as $timer_name => $total_time) {
173
+				$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
+				$output .= $formatted ? '<br />'  : "\n";
175
+				$total += $total_time;
176
+			}
177
+			if($formatted) {
178
+				$output .= '<br />';
179
+				$output .= '<h4>TOTAL TIME</h4>';
180
+				$output .= Benchmark::formatTime('', $total, $formatted);
181
+				$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
182
+				$output .= '<br />';
183
+				$output .= '<h5>Performance scale (from best to worse)</h5>';
184
+				$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
185
+				$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
186
+				$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
187
+				$output .= '<span style="color:gold">Ruh Oh</span><br />';
188
+				$output .= '<span style="color:darkorange">Zoinks!</span><br />';
189
+				$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190
+			}
191
+		}
192
+		if (! empty(Benchmark::$memory_usage)) {
193
+			$output .= $formatted
194
+				? '<h5>Memory</h5>'
195
+				: "\nMemory";
196
+			foreach (Benchmark::$memory_usage as $label => $memory_usage) {
197
+				$output .= $formatted
198
+					? '<br />'
199
+					: "\n";
200
+				$output .= "{$memory_usage} : {$label}";
201
+			}
202
+		}
203
+		if (empty($output)) {
204
+			return '';
205
+		}
206
+		$output = $formatted
207
+			? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
208
+			  . (is_admin()
209
+				? ' margin:2em 2em 2em 180px;'
210
+				: ' margin:2em;')
211
+			  . ' padding:2em;">'
212
+			  . '<h4>BENCHMARKING</h4>'
213
+			  . $output
214
+			  . '</div>'
215
+			: $output;
216
+		return $output;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * @param bool $echo
223
+	 * @param bool $formatted
224
+	 * @return string
225
+	 */
226
+	public static function displayResults($echo = true, $formatted = true)
227
+	{
228
+		$results = Benchmark::generateResults($formatted);
229
+		if ($echo) {
230
+			echo $results;
231
+			$results = '';
232
+		}
233
+		return $results;
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * @param string $filepath
240
+	 * @param bool   $formatted
241
+	 * @param bool   $append
242
+	 */
243
+	public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
244
+	{
245
+		$filepath = ! empty($filepath) && is_readable(dirname($filepath))
246
+			? $filepath
247
+			: '';
248
+		if( empty($filepath)) {
249
+			$filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
250
+		}
251
+		file_put_contents(
252
+			$filepath,
253
+			"\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
254
+			$append ? FILE_APPEND | LOCK_EX : LOCK_EX
255
+		);
256
+	}
257
+
258
+
259
+
260
+	/**
261
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
262
+	 *
263
+	 * @param int $size
264
+	 * @return string
265
+	 */
266
+	public static function convert($size)
267
+	{
268
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
269
+		return round(
270
+			$size / pow(1024, $i = floor(log($size, 1024))),
271
+			2
272
+		) . ' ' . $unit[absint($i)];
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * @param string $timer_name
279
+	 * @param float  $total_time
280
+	 * @param bool   $formatted
281
+	 * @return string
282
+	 */
283
+	public static function formatTime($timer_name, $total_time, $formatted = true)
284
+	{
285
+		$total_time *= 1000;
286
+		switch ($total_time) {
287
+			case $total_time > 12500 :
288
+				$color = 'red';
289
+				$bold = 'bold';
290
+				break;
291
+			case $total_time > 2500 :
292
+				$color = 'darkorange';
293
+				$bold = 'bold';
294
+				break;
295
+			case $total_time > 500 :
296
+				$color = 'gold';
297
+				$bold = 'bold';
298
+				break;
299
+			case $total_time > 100 :
300
+				$color = 'limegreen';
301
+				$bold = 'normal';
302
+				break;
303
+			case $total_time > 20 :
304
+				$color = 'deepskyblue';
305
+				$bold = 'normal';
306
+				break;
307
+			default :
308
+				$color = 'mediumpurple';
309
+				$bold = 'normal';
310
+				break;
311
+		}
312
+		return $formatted
313
+			? '<span style="min-width: 10px; margin:0 1em; color:'
314
+			   . $color
315
+			   . '; font-weight:'
316
+			   . $bold
317
+			   . '; font-size:1.2em;">'
318
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
319
+			   . '</span> '
320
+			   . $timer_name
321
+			:  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
322
+	}
323 323
 
324 324
 
325 325
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
     {
127 127
         add_action(
128 128
             'shutdown',
129
-            function () use ($formatted) {
129
+            function() use ($formatted) {
130 130
                 Benchmark::displayResults(true, $formatted);
131 131
             }
132 132
         );
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
     {
147 147
         add_action(
148 148
             'shutdown',
149
-            function () use ($filepath, $formatted, $append) {
149
+            function() use ($filepath, $formatted, $append) {
150 150
                 Benchmark::writeResultsToFile($filepath, $formatted, $append);
151 151
             }
152 152
         );
@@ -164,17 +164,17 @@  discard block
 block discarded – undo
164 164
             return '';
165 165
         }
166 166
         $output = '';
167
-        if (! empty(Benchmark::$times)) {
167
+        if ( ! empty(Benchmark::$times)) {
168 168
             $total = 0;
169 169
             $output .= $formatted
170 170
                 ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171 171
                 : '';
172 172
             foreach (Benchmark::$times as $timer_name => $total_time) {
173 173
                 $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
-                $output .= $formatted ? '<br />'  : "\n";
174
+                $output .= $formatted ? '<br />' : "\n";
175 175
                 $total += $total_time;
176 176
             }
177
-            if($formatted) {
177
+            if ($formatted) {
178 178
                 $output .= '<br />';
179 179
                 $output .= '<h4>TOTAL TIME</h4>';
180 180
                 $output .= Benchmark::formatTime('', $total, $formatted);
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
                 $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190 190
             }
191 191
         }
192
-        if (! empty(Benchmark::$memory_usage)) {
192
+        if ( ! empty(Benchmark::$memory_usage)) {
193 193
             $output .= $formatted
194 194
                 ? '<h5>Memory</h5>'
195 195
                 : "\nMemory";
@@ -245,12 +245,12 @@  discard block
 block discarded – undo
245 245
         $filepath = ! empty($filepath) && is_readable(dirname($filepath))
246 246
             ? $filepath
247 247
             : '';
248
-        if( empty($filepath)) {
249
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
248
+        if (empty($filepath)) {
249
+            $filepath = EVENT_ESPRESSO_UPLOAD_DIR.'logs/benchmarking-'.date('Y-m-d').'.html';
250 250
         }
251 251
         file_put_contents(
252 252
             $filepath,
253
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
253
+            "\n".date('Y-m-d H:i:s').Benchmark::generateResults($formatted),
254 254
             $append ? FILE_APPEND | LOCK_EX : LOCK_EX
255 255
         );
256 256
     }
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
         return round(
270 270
             $size / pow(1024, $i = floor(log($size, 1024))),
271 271
             2
272
-        ) . ' ' . $unit[absint($i)];
272
+        ).' '.$unit[absint($i)];
273 273
     }
274 274
 
275 275
 
Please login to merge, or discard this patch.