Completed
Branch BUG-10738-inconsistency-in-ses... (cda363)
by
unknown
13:38 queued 12s
created
core/db_models/fields/EE_Post_Content_Field.php 2 patches
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -8,133 +8,133 @@
 block discarded – undo
8 8
 class EE_Post_Content_Field extends EE_Text_Field_Base
9 9
 {
10 10
 
11
-    /**
12
-     * @param string $table_column
13
-     * @param string $nicename
14
-     * @param bool   $nullable
15
-     * @param null   $default_value
16
-     */
17
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
-    {
19
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
20
-        $this->setSchemaType('object');
21
-    }
11
+	/**
12
+	 * @param string $table_column
13
+	 * @param string $nicename
14
+	 * @param bool   $nullable
15
+	 * @param null   $default_value
16
+	 */
17
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
+	{
19
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
20
+		$this->setSchemaType('object');
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * removes all tags which a WP Post wouldn't allow in its content normally
26
-     *
27
-     * @param string $value
28
-     * @return string
29
-     */
30
-    function prepare_for_set($value)
31
-    {
32
-        if (! current_user_can('unfiltered_html')) {
33
-            $value = wp_kses("$value", wp_kses_allowed_html('post'));
34
-        }
35
-        return parent::prepare_for_set($value);
36
-    }
24
+	/**
25
+	 * removes all tags which a WP Post wouldn't allow in its content normally
26
+	 *
27
+	 * @param string $value
28
+	 * @return string
29
+	 */
30
+	function prepare_for_set($value)
31
+	{
32
+		if (! current_user_can('unfiltered_html')) {
33
+			$value = wp_kses("$value", wp_kses_allowed_html('post'));
34
+		}
35
+		return parent::prepare_for_set($value);
36
+	}
37 37
 
38
-    function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
-    {
40
-        return $value_found_in_db_for_model_object;
41
-    }
38
+	function prepare_for_set_from_db($value_found_in_db_for_model_object)
39
+	{
40
+		return $value_found_in_db_for_model_object;
41
+	}
42 42
 
43 43
 
44 44
 
45
-    /**
46
-     * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
-     * @param string $value_on_field_to_be_outputted
48
-     * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
-     * @return string
50
-     * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
-     */
52
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
-    {
54
-        switch($schema){
55
-            case 'form_input':
56
-                return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
-            case 'the_content':
45
+	/**
46
+	 * Runs the content through `the_content`, or if prepares the content for placing in a form input
47
+	 * @param string $value_on_field_to_be_outputted
48
+	 * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
49
+	 * @return string
50
+	 * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
51
+	 */
52
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53
+	{
54
+		switch($schema){
55
+			case 'form_input':
56
+				return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57
+			case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
61
-                        throw new EE_Error(
62
-                            sprintf(
63
-                                esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
-                                'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
-                                '$schema',
66
-                                'the_content',
67
-                                'the_content_wp_core_only'
68
-                            )
69
-                        );
70
-                    } else {
71
-                        return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
-                    }
73
-                }
74
-                return apply_filters(
75
-                    'the_content',
76
-                    parent::prepare_for_pretty_echoing(
77
-                        $value_on_field_to_be_outputted,
78
-                        $schema
79
-                    )
80
-                );
81
-            case 'the_content_wp_core_only':
82
-            default:
83
-                self::_setup_the_content_wp_core_only_filters();
84
-                $return_value = apply_filters(
85
-                    'the_content_wp_core_only',
86
-                    parent::prepare_for_pretty_echoing(
87
-                        $value_on_field_to_be_outputted,
88
-                        $schema
89
-                    )
90
-                );
91
-                //ya know what? adding these filters is super fast. Let's just
92
-                //avoid needing to maintain global state and set this up as-needed
93
-                remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
-                return $return_value;
96
-        }
97
-    }
59
+				if(doing_filter( 'the_content')){
60
+					if( defined('WP_DEBUG') && WP_DEBUG){
61
+						throw new EE_Error(
62
+							sprintf(
63
+								esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
64
+								'EE_Post_Content_Field::prepare_for_pretty_echoing',
65
+								'$schema',
66
+								'the_content',
67
+								'the_content_wp_core_only'
68
+							)
69
+						);
70
+					} else {
71
+						return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
72
+					}
73
+				}
74
+				return apply_filters(
75
+					'the_content',
76
+					parent::prepare_for_pretty_echoing(
77
+						$value_on_field_to_be_outputted,
78
+						$schema
79
+					)
80
+				);
81
+			case 'the_content_wp_core_only':
82
+			default:
83
+				self::_setup_the_content_wp_core_only_filters();
84
+				$return_value = apply_filters(
85
+					'the_content_wp_core_only',
86
+					parent::prepare_for_pretty_echoing(
87
+						$value_on_field_to_be_outputted,
88
+						$schema
89
+					)
90
+				);
91
+				//ya know what? adding these filters is super fast. Let's just
92
+				//avoid needing to maintain global state and set this up as-needed
93
+				remove_all_filters('the_content_wp_core_only');
94
+				do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95
+				return $return_value;
96
+		}
97
+	}
98 98
 
99 99
 
100 100
 
101
-    /**
102
-     * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
-     */
104
-    protected static function _setup_the_content_wp_core_only_filters()
105
-    {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
-        add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
-        add_filter('the_content_wp_core_only', 'wpautop', 10);
110
-        add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
-        add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
113
-            add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
-        }
115
-        add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
-        add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
-    }
101
+	/**
102
+	 * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
103
+	 */
104
+	protected static function _setup_the_content_wp_core_only_filters()
105
+	{
106
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
108
+		add_filter('the_content_wp_core_only', 'wptexturize', 10);
109
+		add_filter('the_content_wp_core_only', 'wpautop', 10);
110
+		add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111
+		add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
+		if(function_exists('wp_make_content_images_responsive')) {
113
+			add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114
+		}
115
+		add_filter('the_content_wp_core_only', 'do_shortcode', 11);
116
+		add_filter('the_content_wp_core_only', 'convert_smilies', 20);
117
+	}
118 118
 
119 119
 
120 120
 
121
-    public function getSchemaProperties()
122
-    {
123
-        return array(
124
-            'raw' => array(
125
-                'description' =>  sprintf(
126
-                    __('%s - the content as it exists in the database.', 'event_espresso'),
127
-                    $this->get_nicename()
128
-                ),
129
-                'type' => 'string'
130
-            ),
131
-            'rendered' => array(
132
-                'description' =>  sprintf(
133
-                    __('%s - the content rendered for display.', 'event_espresso'),
134
-                    $this->get_nicename()
135
-                ),
136
-                'type' => 'string'
137
-            )
138
-        );
139
-    }
121
+	public function getSchemaProperties()
122
+	{
123
+		return array(
124
+			'raw' => array(
125
+				'description' =>  sprintf(
126
+					__('%s - the content as it exists in the database.', 'event_espresso'),
127
+					$this->get_nicename()
128
+				),
129
+				'type' => 'string'
130
+			),
131
+			'rendered' => array(
132
+				'description' =>  sprintf(
133
+					__('%s - the content rendered for display.', 'event_espresso'),
134
+					$this->get_nicename()
135
+				),
136
+				'type' => 'string'
137
+			)
138
+		);
139
+	}
140 140
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
      */
30 30
     function prepare_for_set($value)
31 31
     {
32
-        if (! current_user_can('unfiltered_html')) {
32
+        if ( ! current_user_can('unfiltered_html')) {
33 33
             $value = wp_kses("$value", wp_kses_allowed_html('post'));
34 34
         }
35 35
         return parent::prepare_for_set($value);
@@ -51,13 +51,13 @@  discard block
 block discarded – undo
51 51
      */
52 52
     public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
53 53
     {
54
-        switch($schema){
54
+        switch ($schema) {
55 55
             case 'form_input':
56 56
                 return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
57 57
             case 'the_content':
58 58
 
59
-                if(doing_filter( 'the_content')){
60
-                    if( defined('WP_DEBUG') && WP_DEBUG){
59
+                if (doing_filter('the_content')) {
60
+                    if (defined('WP_DEBUG') && WP_DEBUG) {
61 61
                         throw new EE_Error(
62 62
                             sprintf(
63 63
                                 esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
                 //ya know what? adding these filters is super fast. Let's just
92 92
                 //avoid needing to maintain global state and set this up as-needed
93 93
                 remove_all_filters('the_content_wp_core_only');
94
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
94
+                do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
95 95
                 return $return_value;
96 96
         }
97 97
     }
@@ -103,13 +103,13 @@  discard block
 block discarded – undo
103 103
      */
104 104
     protected static function _setup_the_content_wp_core_only_filters()
105 105
     {
106
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
106
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'run_shortcode'), 8);
107
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'autoembed'), 8);
108 108
         add_filter('the_content_wp_core_only', 'wptexturize', 10);
109 109
         add_filter('the_content_wp_core_only', 'wpautop', 10);
110 110
         add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
111 111
         add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
112
-        if(function_exists('wp_make_content_images_responsive')) {
112
+        if (function_exists('wp_make_content_images_responsive')) {
113 113
             add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
114 114
         }
115 115
         add_filter('the_content_wp_core_only', 'do_shortcode', 11);
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -36,9 +36,9 @@  discard block
 block discarded – undo
36 36
 	 */
37 37
 	protected $_feature_image = array();
38 38
 
39
-    /**
40
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
41
-     */
39
+	/**
40
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
41
+	 */
42 42
 	protected $_wp_post;
43 43
 
44 44
 
@@ -46,75 +46,75 @@  discard block
 block discarded – undo
46 46
 
47 47
 
48 48
 
49
-    /**
50
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
-     * @return WP_Post
53
-     */
54
-    public function wp_post(){
55
-        global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
57
-            if ($this->ID()) {
58
-                $this->_wp_post = get_post($this->ID());
59
-            } else {
60
-                $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
-                        $column = $field_obj->get_table_column();
64
-
65
-                        if($field_obj instanceof EE_Datetime_Field){
66
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
68
-                            $value_on_model_obj = $field_obj->get_default_value();
69
-                        } else {
70
-                            $value_on_model_obj = $this->get_raw($field_name);
71
-                        }
72
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
-                    }
74
-                }
75
-                $this->_wp_post = new WP_Post($simulated_db_result);
76
-            }
77
-            //and let's make retrieving the EE CPT object easy too
78
-            $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
80
-                $this->_wp_post->{$classname} = $this;
81
-            }
82
-        }
83
-        return $this->_wp_post;
84
-    }
85
-
86
-    /**
87
-     * When fetching a new value for a post field that uses the global $post for rendering,
88
-     * set the global $post temporarily to be this model object; and afterwards restore it
89
-     * @param string $fieldname
90
-     * @param bool $pretty
91
-     * @param string $extra_cache_ref
92
-     * @return mixed
93
-     */
94
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
-    {
96
-        global $post;
97
-
98
-        if ( $pretty
99
-            && (
100
-                ! (
101
-                       $post instanceof WP_Post
102
-                       && $post->ID
103
-                   )
104
-                || (int)$post->ID !== $this->ID()
105
-             )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
-            $old_post = $post;
108
-            $post = $this->wp_post();
109
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
-            $post = $old_post;
111
-        } else {
112
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
-        }
114
-        return $return_value;
115
-    }
116
-
117
-    /**
49
+	/**
50
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
51
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52
+	 * @return WP_Post
53
+	 */
54
+	public function wp_post(){
55
+		global $wpdb;
56
+		if (! $this->_wp_post instanceof WP_Post) {
57
+			if ($this->ID()) {
58
+				$this->_wp_post = get_post($this->ID());
59
+			} else {
60
+				$simulated_db_result = new stdClass();
61
+				foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
+					if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
63
+						$column = $field_obj->get_table_column();
64
+
65
+						if($field_obj instanceof EE_Datetime_Field){
66
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
67
+						} elseif( $field_obj->is_db_only_field()){
68
+							$value_on_model_obj = $field_obj->get_default_value();
69
+						} else {
70
+							$value_on_model_obj = $this->get_raw($field_name);
71
+						}
72
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
73
+					}
74
+				}
75
+				$this->_wp_post = new WP_Post($simulated_db_result);
76
+			}
77
+			//and let's make retrieving the EE CPT object easy too
78
+			$classname = get_class($this);
79
+			if (! isset($this->_wp_post->{$classname})) {
80
+				$this->_wp_post->{$classname} = $this;
81
+			}
82
+		}
83
+		return $this->_wp_post;
84
+	}
85
+
86
+	/**
87
+	 * When fetching a new value for a post field that uses the global $post for rendering,
88
+	 * set the global $post temporarily to be this model object; and afterwards restore it
89
+	 * @param string $fieldname
90
+	 * @param bool $pretty
91
+	 * @param string $extra_cache_ref
92
+	 * @return mixed
93
+	 */
94
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
95
+	{
96
+		global $post;
97
+
98
+		if ( $pretty
99
+			&& (
100
+				! (
101
+					   $post instanceof WP_Post
102
+					   && $post->ID
103
+				   )
104
+				|| (int)$post->ID !== $this->ID()
105
+			 )
106
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
107
+			$old_post = $post;
108
+			$post = $this->wp_post();
109
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
110
+			$post = $old_post;
111
+		} else {
112
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
113
+		}
114
+		return $return_value;
115
+	}
116
+
117
+	/**
118 118
 	 * Adds to the specified event category. If it category doesn't exist, creates it.
119 119
 	 * @param string $category_name
120 120
 	 * @param string $category_description    optional
@@ -399,14 +399,14 @@  discard block
 block discarded – undo
399 399
 
400 400
 
401 401
 
402
-    /**
403
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
-     * @return array
405
-     */
406
-    public function __sleep()
407
-    {
408
-        $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
-        return $properties_to_serialize;
411
-    }
402
+	/**
403
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
404
+	 * @return array
405
+	 */
406
+	public function __sleep()
407
+	{
408
+		$properties_to_serialize = parent::__sleep();
409
+		$properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
410
+		return $properties_to_serialize;
411
+	}
412 412
 }
Please login to merge, or discard this patch.
Spacing   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -51,20 +51,20 @@  discard block
 block discarded – undo
51 51
      * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
52 52
      * @return WP_Post
53 53
      */
54
-    public function wp_post(){
54
+    public function wp_post() {
55 55
         global $wpdb;
56
-        if (! $this->_wp_post instanceof WP_Post) {
56
+        if ( ! $this->_wp_post instanceof WP_Post) {
57 57
             if ($this->ID()) {
58 58
                 $this->_wp_post = get_post($this->ID());
59 59
             } else {
60 60
                 $simulated_db_result = new stdClass();
61
-                foreach($this->get_model()->field_settings(true) as $field_name => $field_obj){
62
-                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts){
61
+                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
62
+                    if ($this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name() === $wpdb->posts) {
63 63
                         $column = $field_obj->get_table_column();
64 64
 
65
-                        if($field_obj instanceof EE_Datetime_Field){
65
+                        if ($field_obj instanceof EE_Datetime_Field) {
66 66
                             $value_on_model_obj = $this->get_DateTime_object($field_name);
67
-                        } elseif( $field_obj->is_db_only_field()){
67
+                        } elseif ($field_obj->is_db_only_field()) {
68 68
                             $value_on_model_obj = $field_obj->get_default_value();
69 69
                         } else {
70 70
                             $value_on_model_obj = $this->get_raw($field_name);
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
             }
77 77
             //and let's make retrieving the EE CPT object easy too
78 78
             $classname = get_class($this);
79
-            if (! isset($this->_wp_post->{$classname})) {
79
+            if ( ! isset($this->_wp_post->{$classname})) {
80 80
                 $this->_wp_post->{$classname} = $this;
81 81
             }
82 82
         }
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
     {
96 96
         global $post;
97 97
 
98
-        if ( $pretty
98
+        if ($pretty
99 99
             && (
100 100
                 ! (
101 101
                        $post instanceof WP_Post
102 102
                        && $post->ID
103 103
                    )
104
-                || (int)$post->ID !== $this->ID()
104
+                || (int) $post->ID !== $this->ID()
105 105
              )
106
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field ) {
106
+            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field) {
107 107
             $old_post = $post;
108 108
             $post = $this->wp_post();
109 109
             $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
 	 * @param int    $parent_term_taxonomy_id optional
122 122
 	 * @return EE_Term_Taxonomy
123 123
 	 */
124
-	function add_event_category( $category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL ) {
125
-		return $this->get_model()->add_event_category( $this, $category_name, $category_description, $parent_term_taxonomy_id );
124
+	function add_event_category($category_name, $category_description = NULL, $parent_term_taxonomy_id = NULL) {
125
+		return $this->get_model()->add_event_category($this, $category_name, $category_description, $parent_term_taxonomy_id);
126 126
 	}
127 127
 
128 128
 
@@ -132,8 +132,8 @@  discard block
 block discarded – undo
132 132
 	 * @param string $category_name
133 133
 	 * @return bool
134 134
 	 */
135
-	function remove_event_category( $category_name ) {
136
-		return $this->get_model()->remove_event_category( $this, $category_name );
135
+	function remove_event_category($category_name) {
136
+		return $this->get_model()->remove_event_category($this, $category_name);
137 137
 	}
138 138
 
139 139
 
@@ -144,14 +144,14 @@  discard block
 block discarded – undo
144 144
 	 * @param EE_Term_Taxonomy $term_taxonomy
145 145
 	 * @return EE_Base_Class the relation was removed from
146 146
 	 */
147
-	function remove_relation_to_term_taxonomy( $term_taxonomy ) {
148
-		if ( !$term_taxonomy ) {
149
-			EE_Error::add_error( sprintf( __( "No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso" ), get_class( $this ), $this->ID() ), __FILE__, __FUNCTION__, __LINE__ );
147
+	function remove_relation_to_term_taxonomy($term_taxonomy) {
148
+		if ( ! $term_taxonomy) {
149
+			EE_Error::add_error(sprintf(__("No Term_Taxonomy provided which to remove from model object of type %s and id %d", "event_espresso"), get_class($this), $this->ID()), __FILE__, __FUNCTION__, __LINE__);
150 150
 			return NULL;
151 151
 		}
152
-		$term_taxonomy->set_count( $term_taxonomy->count() - 1 );
152
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
153 153
 		$term_taxonomy->save();
154
-		return $this->_remove_relation_to( $term_taxonomy, 'Term_Taxonomy' );
154
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
155 155
 	}
156 156
 
157 157
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	 * @return int
176 176
 	 */
177 177
 	public function parent() {
178
-		return $this->get( 'parent' );
178
+		return $this->get('parent');
179 179
 	}
180 180
 
181 181
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	 * @return string
186 186
 	 */
187 187
 	public function status() {
188
-		return $this->get( 'status' );
188
+		return $this->get('status');
189 189
 	}
190 190
 
191 191
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 	/**
194 194
 	 * @param string $status
195 195
 	 */
196
-	public function set_status( $status ) {
197
-		$this->set( 'status', $status );
196
+	public function set_status($status) {
197
+		$this->set('status', $status);
198 198
 	}
199 199
 
200 200
 
@@ -208,12 +208,12 @@  discard block
 block discarded – undo
208 208
 	 * @param string|array $attr Optional. Query string or array of attributes.
209 209
 	 * @return string HTML image element
210 210
 	 */
211
-	protected function _get_feature_image( $size, $attr ) {
211
+	protected function _get_feature_image($size, $attr) {
212 212
 		//first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
213
-		$attr_key = is_array( $attr ) ? implode( '_', $attr ) : $attr;
214
-		$cache_key = is_array( $size ) ? implode( '_', $size ) . $attr_key : $size . $attr_key;
215
-		$this->_feature_image[ $cache_key ] = isset( $this->_feature_image[ $cache_key ] ) ? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image( $this->ID(), $size, $attr );
216
-		return $this->_feature_image[ $cache_key ];
213
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
214
+		$cache_key = is_array($size) ? implode('_', $size).$attr_key : $size.$attr_key;
215
+		$this->_feature_image[$cache_key] = isset($this->_feature_image[$cache_key]) ? $this->_feature_image[$cache_key] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
216
+		return $this->_feature_image[$cache_key];
217 217
 	}
218 218
 
219 219
 
@@ -224,8 +224,8 @@  discard block
 block discarded – undo
224 224
 	 * @param string|array $attr
225 225
 	 * @return string of html
226 226
 	 */
227
-	public function feature_image( $size = 'thumbnail', $attr = '' ) {
228
-		return $this->_get_feature_image( $size, $attr );
227
+	public function feature_image($size = 'thumbnail', $attr = '') {
228
+		return $this->_get_feature_image($size, $attr);
229 229
 	}
230 230
 
231 231
 
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
 	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array representing width and height in pixels eg. array(32,32).
236 236
 	 * @return string|boolean          the url of the image or false if not found
237 237
 	 */
238
-	public function feature_image_url( $size = 'thumbnail' ) {
239
-		$attachment = wp_get_attachment_image_src( get_post_thumbnail_id( $this->ID() ), $size );
240
-		return !empty( $attachment ) ? $attachment[ 0 ] : FALSE;
238
+	public function feature_image_url($size = 'thumbnail') {
239
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
240
+		return ! empty($attachment) ? $attachment[0] : FALSE;
241 241
 	}
242 242
 
243 243
 
@@ -259,36 +259,36 @@  discard block
 block discarded – undo
259 259
 	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names sent);
260 260
 	 * @return void
261 261
 	 */
262
-	public function restore_revision( $revision_id, $related_obj_names = array(), $where_query = array() ) {
262
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array()) {
263 263
 		//get revision object
264
-		$revision_obj = $this->get_model()->get_one_by_ID( $revision_id );
265
-		if ( $revision_obj instanceof EE_CPT_Base ) {
264
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
265
+		if ($revision_obj instanceof EE_CPT_Base) {
266 266
 			//no related_obj_name so we assume we're saving a revision on this object.
267
-			if ( empty( $related_obj_names ) ) {
267
+			if (empty($related_obj_names)) {
268 268
 				$fields = $this->get_model()->get_meta_table_fields();
269
-				foreach ( $fields as $field ) {
270
-					$this->set( $field, $revision_obj->get( $field ) );
269
+				foreach ($fields as $field) {
270
+					$this->set($field, $revision_obj->get($field));
271 271
 				}
272 272
 				$this->save();
273 273
 			}
274
-			$related_obj_names = (array)$related_obj_names;
275
-			foreach ( $related_obj_names as $related_name ) {
274
+			$related_obj_names = (array) $related_obj_names;
275
+			foreach ($related_obj_names as $related_name) {
276 276
 				//related_obj_name so we're saving a revision on an object related to this object
277 277
 				//do we have $where_query params for this related object?  If we do then we include that.
278
-				$cols_n_values = isset( $where_query[ $related_name ] ) ? $where_query[ $related_name ] : array();
279
-				$where_params = !empty( $cols_n_values ) ? array( $cols_n_values ) : array();
280
-				$related_objs = $this->get_many_related( $related_name, $where_params );
281
-				$revision_related_objs = $revision_obj->get_many_related( $related_name, $where_params );
278
+				$cols_n_values = isset($where_query[$related_name]) ? $where_query[$related_name] : array();
279
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
280
+				$related_objs = $this->get_many_related($related_name, $where_params);
281
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
282 282
 				//load helper
283 283
 				//remove related objs from this object that are not in revision
284 284
 				//array_diff *should* work cause I think objects are indexed by ID?
285
-				$related_to_remove = EEH_Array::object_array_diff( $related_objs, $revision_related_objs );
286
-				foreach ( $related_to_remove as $rr ) {
287
-					$this->_remove_relation_to( $rr, $related_name, $cols_n_values );
285
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
286
+				foreach ($related_to_remove as $rr) {
287
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
288 288
 				}
289 289
 				//add all related objs attached to revision to this object
290
-				foreach ( $revision_related_objs as $r_obj ) {
291
-					$this->_add_relation_to( $r_obj, $related_name, $cols_n_values );
290
+				foreach ($revision_related_objs as $r_obj) {
291
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
292 292
 				}
293 293
 			}
294 294
 		}
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
 	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the specified key.</li>
305 305
 	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an array</li></ul>
306 306
 	 */
307
-	public function get_post_meta( $meta_key = NULL, $single = FALSE ) {
308
-		return get_post_meta( $this->ID(), $meta_key, $single );
307
+	public function get_post_meta($meta_key = NULL, $single = FALSE) {
308
+		return get_post_meta($this->ID(), $meta_key, $single);
309 309
 	}
310 310
 
311 311
 
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
 	 * @param mixed  $prev_value
318 318
 	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. NOTE: If the meta_value passed to this function is the same as the value that is already in the database, this function returns false.
319 319
 	 */
320
-	public function update_post_meta( $meta_key, $meta_value, $prev_value = NULL ) {
321
-		if ( ! $this->ID() ) {
320
+	public function update_post_meta($meta_key, $meta_value, $prev_value = NULL) {
321
+		if ( ! $this->ID()) {
322 322
 			$this->save();
323 323
 		}
324
-		return update_post_meta( $this->ID(), $meta_key, $meta_value, $prev_value );
324
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
325 325
 	}
326 326
 
327 327
 
@@ -333,11 +333,11 @@  discard block
 block discarded – undo
333 333
 	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
334 334
 	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given key already exists, in which case false is returned.
335 335
 	 */
336
-	public function add_post_meta( $meta_key, $meta_value, $unique = FALSE ) {
337
-		if ( $this->ID() ) {
336
+	public function add_post_meta($meta_key, $meta_value, $unique = FALSE) {
337
+		if ($this->ID()) {
338 338
 			$this->save();
339 339
 		}
340
-		return add_post_meta( $this->ID(), $meta_key, $meta_value, $unique );
340
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
341 341
 	}
342 342
 
343 343
 
@@ -349,13 +349,13 @@  discard block
 block discarded – undo
349 349
 	 * @param mixed $meta_value
350 350
 	 * @return boolean False for failure. True for success.
351 351
 	 */
352
-	public function delete_post_meta( $meta_key, $meta_value = '' ) {
353
-		if ( ! $this->ID() ) {
352
+	public function delete_post_meta($meta_key, $meta_value = '') {
353
+		if ( ! $this->ID()) {
354 354
 			//there are obviously no postmetas for this if it's not saved
355 355
 			//so let's just report this as a success
356 356
 			return true;
357 357
 		}
358
-		return delete_post_meta( $this->ID(), $meta_key, $meta_value );
358
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
359 359
 	}
360 360
 
361 361
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 * @return string
366 366
 	 */
367 367
 	public function get_permalink() {
368
-		return get_permalink( $this->ID() );
368
+		return get_permalink($this->ID());
369 369
 	}
370 370
 
371 371
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * @param array $query_params
376 376
 	 * @return EE_Term_Taxonomy
377 377
 	 */
378
-	public function term_taxonomies( $query_params = array() ) {
379
-		return $this->get_many_related( 'Term_Taxonomy', $query_params );
378
+	public function term_taxonomies($query_params = array()) {
379
+		return $this->get_many_related('Term_Taxonomy', $query_params);
380 380
 	}
381 381
 
382 382
 
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function __sleep()
407 407
     {
408 408
         $properties_to_serialize = parent::__sleep();
409
-        $properties_to_serialize = array_diff( $properties_to_serialize, array('_wp_post'));
409
+        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
410 410
         return $properties_to_serialize;
411 411
     }
412 412
 }
Please login to merge, or discard this patch.
core/services/shortcodes/EspressoShortcode.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
             }
85 85
         }
86 86
         return $this->shortcodeContent(
87
-            $this->sanitizeAttributes((array)$attributes)
87
+            $this->sanitizeAttributes((array) $attributes)
88 88
         );
89 89
     }
90 90
 
@@ -112,8 +112,8 @@  discard block
 block discarded – undo
112 112
             // serialized attributes
113 113
             wp_json_encode($attributes),
114 114
             // Closure for generating content if cache is expired
115
-            function () use ($shortcode, $attributes) {
116
-                if($shortcode->initialized() === false){
115
+            function() use ($shortcode, $attributes) {
116
+                if ($shortcode->initialized() === false) {
117 117
                     $shortcode->initializeShortcode();
118 118
                 }
119 119
                 return $shortcode->processShortcode($attributes);
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
      * Returns whether or not this shortcode has been initialized
248 248
      * @return boolean
249 249
      */
250
-    public function initialized(){
250
+    public function initialized() {
251 251
         return $this->initialized;
252 252
     }
253 253
 
Please login to merge, or discard this patch.
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -23,230 +23,230 @@
 block discarded – undo
23 23
 abstract class EspressoShortcode implements ShortcodeInterface
24 24
 {
25 25
 
26
-    /**
27
-     * transient prefix
28
-     *
29
-     * @type string
30
-     */
31
-    const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
32
-
33
-    /**
34
-     * @var PostRelatedCacheManager $cache_manager
35
-     */
36
-    private $cache_manager;
37
-
38
-    /**
39
-     * true if ShortcodeInterface::initializeShortcode() has been called
40
-     * if false, then that will get called before processing
41
-     *
42
-     * @var boolean $initialized
43
-     */
44
-    private $initialized = false;
45
-
46
-
47
-
48
-    /**
49
-     * EspressoShortcode constructor
50
-     *
51
-     * @param PostRelatedCacheManager $cache_manager
52
-     */
53
-    public function __construct(PostRelatedCacheManager $cache_manager)
54
-    {
55
-        $this->cache_manager = $cache_manager;
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     * @return void
62
-     */
63
-    public function shortcodeHasBeenInitialized()
64
-    {
65
-        $this->initialized = true;
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * enqueues scripts then processes the shortcode
72
-     *
73
-     * @param array $attributes
74
-     * @return string
75
-     * @throws EE_Error
76
-     */
77
-    final public function processShortcodeCallback($attributes = array())
78
-    {
79
-        if ($this instanceof EnqueueAssetsInterface) {
80
-            if (is_admin()) {
81
-                $this->enqueueAdminScripts();
82
-            } else {
83
-                $this->enqueueScripts();
84
-            }
85
-        }
86
-        return $this->shortcodeContent(
87
-            $this->sanitizeAttributes((array)$attributes)
88
-        );
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * If shortcode caching is enabled for the shortcode,
95
-     * and cached results exist, then that will be returned
96
-     * else new content will be generated.
97
-     * If caching is enabled, then the new content will be cached for later.
98
-     *
99
-     * @param array $attributes
100
-     * @return mixed|string
101
-     * @throws EE_Error
102
-     */
103
-    private function shortcodeContent(array $attributes)
104
-    {
105
-        $shortcode = $this;
106
-        $post_ID = $this->currentPostID();
107
-        // something like "SC_EVENTS-123"
108
-        $cache_ID = $this->shortcodeCacheID($post_ID);
109
-        $this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
110
-        return $this->cache_manager->get(
111
-            $cache_ID,
112
-            // serialized attributes
113
-            wp_json_encode($attributes),
114
-            // Closure for generating content if cache is expired
115
-            function () use ($shortcode, $attributes) {
116
-                if($shortcode->initialized() === false){
117
-                    $shortcode->initializeShortcode();
118
-                }
119
-                return $shortcode->processShortcode($attributes);
120
-            },
121
-            // filterable cache expiration set by each shortcode
122
-            apply_filters(
123
-                'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
124
-                $this->cacheExpiration(),
125
-                $this->getTag(),
126
-                $this
127
-            )
128
-        );
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     * @return int
135
-     * @throws EE_Error
136
-     */
137
-    private function currentPostID()
138
-    {
139
-        // try to get EE_Event any way we can
140
-        $event = EEH_Event_View::get_event();
141
-        // then get some kind of ID
142
-        if ($event instanceof EE_Event) {
143
-            return $event->ID();
144
-        }
145
-        global $post;
146
-        if ($post instanceof WP_Post) {
147
-            return $post->ID;
148
-        }
149
-        return 0;
150
-    }
151
-
152
-
153
-
154
-    /**
155
-     * @param int $post_ID
156
-     * @return string
157
-     * @throws EE_Error
158
-     */
159
-    private function shortcodeCacheID($post_ID)
160
-    {
161
-        $tag = str_replace('ESPRESSO_', '', $this->getTag());
162
-        return "SC_{$tag}-{$post_ID}";
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * array for defining custom attribute sanitization callbacks,
169
-     * where keys match keys in your attributes array,
170
-     * and values represent the sanitization function you wish to be applied to that attribute.
171
-     * So for example, if you had an integer attribute named "event_id"
172
-     * that you wanted to be sanitized using absint(),
173
-     * then you would return the following:
174
-     *      array('event_id' => 'absint')
175
-     * Entering 'skip_sanitization' for the callback value
176
-     * means that no sanitization will be applied
177
-     * on the assumption that the attribute
178
-     * will be sanitized at some point... right?
179
-     * You wouldn't pass around unsanitized attributes would you?
180
-     * That would be very Tom Foolery of you!!!
181
-     *
182
-     * @return array
183
-     */
184
-    protected function customAttributeSanitizationMap()
185
-    {
186
-        return array();
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * Performs basic sanitization on shortcode attributes
193
-     * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
194
-     * most attributes will by default be sanitized using the sanitize_text_field() function.
195
-     * This can be overridden using the customAttributeSanitizationMap() method (see above),
196
-     * all other attributes would be sanitized using the defaults in the switch statement below
197
-     *
198
-     * @param array $attributes
199
-     * @return array
200
-     */
201
-    private function sanitizeAttributes(array $attributes)
202
-    {
203
-        $custom_sanitization = $this->customAttributeSanitizationMap();
204
-        foreach ($attributes as $key => $value) {
205
-            // is a custom sanitization callback specified ?
206
-            if (isset($custom_sanitization[$key])) {
207
-                $callback = $custom_sanitization[$key];
208
-                if ($callback === 'skip_sanitization') {
209
-                    $attributes[$key] = $value;
210
-                    continue;
211
-                }
212
-                if (function_exists($callback)) {
213
-                    $attributes[$key] = $callback($value);
214
-                    continue;
215
-                }
216
-            }
217
-            switch (true) {
218
-                case $value === null :
219
-                case is_int($value) :
220
-                case is_float($value) :
221
-                    // typical booleans
222
-                case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
223
-                    $attributes[$key] = $value;
224
-                    break;
225
-                case is_string($value) :
226
-                    $attributes[$key] = sanitize_text_field($value);
227
-                    break;
228
-                case is_array($value) :
229
-                    $attributes[$key] = $this->sanitizeAttributes($value);
230
-                    break;
231
-                default :
232
-                    // only remaining data types are Object and Resource
233
-                    // which are not allowed as shortcode attributes
234
-                    $attributes[$key] = null;
235
-                    break;
236
-            }
237
-        }
238
-        return $attributes;
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Returns whether or not this shortcode has been initialized
245
-     * @return boolean
246
-     */
247
-    public function initialized(){
248
-        return $this->initialized;
249
-    }
26
+	/**
27
+	 * transient prefix
28
+	 *
29
+	 * @type string
30
+	 */
31
+	const CACHE_TRANSIENT_PREFIX = 'ee_sc_';
32
+
33
+	/**
34
+	 * @var PostRelatedCacheManager $cache_manager
35
+	 */
36
+	private $cache_manager;
37
+
38
+	/**
39
+	 * true if ShortcodeInterface::initializeShortcode() has been called
40
+	 * if false, then that will get called before processing
41
+	 *
42
+	 * @var boolean $initialized
43
+	 */
44
+	private $initialized = false;
45
+
46
+
47
+
48
+	/**
49
+	 * EspressoShortcode constructor
50
+	 *
51
+	 * @param PostRelatedCacheManager $cache_manager
52
+	 */
53
+	public function __construct(PostRelatedCacheManager $cache_manager)
54
+	{
55
+		$this->cache_manager = $cache_manager;
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 * @return void
62
+	 */
63
+	public function shortcodeHasBeenInitialized()
64
+	{
65
+		$this->initialized = true;
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * enqueues scripts then processes the shortcode
72
+	 *
73
+	 * @param array $attributes
74
+	 * @return string
75
+	 * @throws EE_Error
76
+	 */
77
+	final public function processShortcodeCallback($attributes = array())
78
+	{
79
+		if ($this instanceof EnqueueAssetsInterface) {
80
+			if (is_admin()) {
81
+				$this->enqueueAdminScripts();
82
+			} else {
83
+				$this->enqueueScripts();
84
+			}
85
+		}
86
+		return $this->shortcodeContent(
87
+			$this->sanitizeAttributes((array)$attributes)
88
+		);
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * If shortcode caching is enabled for the shortcode,
95
+	 * and cached results exist, then that will be returned
96
+	 * else new content will be generated.
97
+	 * If caching is enabled, then the new content will be cached for later.
98
+	 *
99
+	 * @param array $attributes
100
+	 * @return mixed|string
101
+	 * @throws EE_Error
102
+	 */
103
+	private function shortcodeContent(array $attributes)
104
+	{
105
+		$shortcode = $this;
106
+		$post_ID = $this->currentPostID();
107
+		// something like "SC_EVENTS-123"
108
+		$cache_ID = $this->shortcodeCacheID($post_ID);
109
+		$this->cache_manager->clearPostRelatedCacheOnUpdate($post_ID, $cache_ID);
110
+		return $this->cache_manager->get(
111
+			$cache_ID,
112
+			// serialized attributes
113
+			wp_json_encode($attributes),
114
+			// Closure for generating content if cache is expired
115
+			function () use ($shortcode, $attributes) {
116
+				if($shortcode->initialized() === false){
117
+					$shortcode->initializeShortcode();
118
+				}
119
+				return $shortcode->processShortcode($attributes);
120
+			},
121
+			// filterable cache expiration set by each shortcode
122
+			apply_filters(
123
+				'FHEE__EventEspresso_core_services_shortcodes_EspressoShortcode__shortcodeContent__cache_expiration',
124
+				$this->cacheExpiration(),
125
+				$this->getTag(),
126
+				$this
127
+			)
128
+		);
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 * @return int
135
+	 * @throws EE_Error
136
+	 */
137
+	private function currentPostID()
138
+	{
139
+		// try to get EE_Event any way we can
140
+		$event = EEH_Event_View::get_event();
141
+		// then get some kind of ID
142
+		if ($event instanceof EE_Event) {
143
+			return $event->ID();
144
+		}
145
+		global $post;
146
+		if ($post instanceof WP_Post) {
147
+			return $post->ID;
148
+		}
149
+		return 0;
150
+	}
151
+
152
+
153
+
154
+	/**
155
+	 * @param int $post_ID
156
+	 * @return string
157
+	 * @throws EE_Error
158
+	 */
159
+	private function shortcodeCacheID($post_ID)
160
+	{
161
+		$tag = str_replace('ESPRESSO_', '', $this->getTag());
162
+		return "SC_{$tag}-{$post_ID}";
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * array for defining custom attribute sanitization callbacks,
169
+	 * where keys match keys in your attributes array,
170
+	 * and values represent the sanitization function you wish to be applied to that attribute.
171
+	 * So for example, if you had an integer attribute named "event_id"
172
+	 * that you wanted to be sanitized using absint(),
173
+	 * then you would return the following:
174
+	 *      array('event_id' => 'absint')
175
+	 * Entering 'skip_sanitization' for the callback value
176
+	 * means that no sanitization will be applied
177
+	 * on the assumption that the attribute
178
+	 * will be sanitized at some point... right?
179
+	 * You wouldn't pass around unsanitized attributes would you?
180
+	 * That would be very Tom Foolery of you!!!
181
+	 *
182
+	 * @return array
183
+	 */
184
+	protected function customAttributeSanitizationMap()
185
+	{
186
+		return array();
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * Performs basic sanitization on shortcode attributes
193
+	 * Since incoming attributes from the shortcode usage in the WP editor will all be strings,
194
+	 * most attributes will by default be sanitized using the sanitize_text_field() function.
195
+	 * This can be overridden using the customAttributeSanitizationMap() method (see above),
196
+	 * all other attributes would be sanitized using the defaults in the switch statement below
197
+	 *
198
+	 * @param array $attributes
199
+	 * @return array
200
+	 */
201
+	private function sanitizeAttributes(array $attributes)
202
+	{
203
+		$custom_sanitization = $this->customAttributeSanitizationMap();
204
+		foreach ($attributes as $key => $value) {
205
+			// is a custom sanitization callback specified ?
206
+			if (isset($custom_sanitization[$key])) {
207
+				$callback = $custom_sanitization[$key];
208
+				if ($callback === 'skip_sanitization') {
209
+					$attributes[$key] = $value;
210
+					continue;
211
+				}
212
+				if (function_exists($callback)) {
213
+					$attributes[$key] = $callback($value);
214
+					continue;
215
+				}
216
+			}
217
+			switch (true) {
218
+				case $value === null :
219
+				case is_int($value) :
220
+				case is_float($value) :
221
+					// typical booleans
222
+				case in_array($value, array(true, 'true', '1', 'on', 'yes', false, 'false', '0', 'off', 'no'), true) :
223
+					$attributes[$key] = $value;
224
+					break;
225
+				case is_string($value) :
226
+					$attributes[$key] = sanitize_text_field($value);
227
+					break;
228
+				case is_array($value) :
229
+					$attributes[$key] = $this->sanitizeAttributes($value);
230
+					break;
231
+				default :
232
+					// only remaining data types are Object and Resource
233
+					// which are not allowed as shortcode attributes
234
+					$attributes[$key] = null;
235
+					break;
236
+			}
237
+		}
238
+		return $attributes;
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Returns whether or not this shortcode has been initialized
245
+	 * @return boolean
246
+	 */
247
+	public function initialized(){
248
+		return $this->initialized;
249
+	}
250 250
 
251 251
 
252 252
 
Please login to merge, or discard this patch.
core/services/shortcodes/ShortcodeInterface.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -8,52 +8,52 @@
 block discarded – undo
8 8
 interface ShortcodeInterface
9 9
 {
10 10
 
11
-    /**
12
-     * the actual shortcode tag that gets registered with WordPress
13
-     *
14
-     * @return string
15
-     */
16
-    public function getTag();
17
-
18
-    /**
19
-     * the length of time in seconds to cache the results of the processShortcode() method
20
-     * 0 means the processShortcode() results will NOT be cached at all
21
-     *
22
-     * @return int
23
-     */
24
-    public function cacheExpiration();
25
-
26
-    /**
27
-     * a place for adding any initialization code that needs to run prior to wp_header().
28
-     * this may be required for shortcodes that utilize a corresponding module,
29
-     * and need to enqueue assets for that module
30
-     *
31
-     * !!! IMPORTANT !!!
32
-     * After performing any logic within this method required for initialization
33
-     *         $this->shortcodeHasBeenInitialized();
34
-     * should be called to ensure that the shortcode is setup correctly.
35
-     *
36
-     * @return void
37
-     */
38
-    public function initializeShortcode();
39
-
40
-    /**
41
-     * callback that runs when the shortcode is encountered in post content.
42
-     * IMPORTANT !!!
43
-     * remember that shortcode content should be RETURNED and NOT echoed out
44
-     *
45
-     * @param array $attributes
46
-     * @return string
47
-     */
48
-    public function processShortcode($attributes = array());
49
-
50
-
51
-
52
-    /**
53
-     * Returns whether or not this shortcode class has already been initialized
54
-     * @return boolean
55
-     */
56
-    public function initialized();
11
+	/**
12
+	 * the actual shortcode tag that gets registered with WordPress
13
+	 *
14
+	 * @return string
15
+	 */
16
+	public function getTag();
17
+
18
+	/**
19
+	 * the length of time in seconds to cache the results of the processShortcode() method
20
+	 * 0 means the processShortcode() results will NOT be cached at all
21
+	 *
22
+	 * @return int
23
+	 */
24
+	public function cacheExpiration();
25
+
26
+	/**
27
+	 * a place for adding any initialization code that needs to run prior to wp_header().
28
+	 * this may be required for shortcodes that utilize a corresponding module,
29
+	 * and need to enqueue assets for that module
30
+	 *
31
+	 * !!! IMPORTANT !!!
32
+	 * After performing any logic within this method required for initialization
33
+	 *         $this->shortcodeHasBeenInitialized();
34
+	 * should be called to ensure that the shortcode is setup correctly.
35
+	 *
36
+	 * @return void
37
+	 */
38
+	public function initializeShortcode();
39
+
40
+	/**
41
+	 * callback that runs when the shortcode is encountered in post content.
42
+	 * IMPORTANT !!!
43
+	 * remember that shortcode content should be RETURNED and NOT echoed out
44
+	 *
45
+	 * @param array $attributes
46
+	 * @return string
47
+	 */
48
+	public function processShortcode($attributes = array());
49
+
50
+
51
+
52
+	/**
53
+	 * Returns whether or not this shortcode class has already been initialized
54
+	 * @return boolean
55
+	 */
56
+	public function initialized();
57 57
 
58 58
 }
59 59
 // End of file ShortcodeInterface.php
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@
 block discarded – undo
164 164
 
165 165
 
166 166
     /**
167
-     * @param $ticket
167
+     * @param \EE_Base_Class $ticket
168 168
      * @throws DomainException
169 169
      * @throws EE_Error
170 170
      * @throws UnexpectedEntityException
Please login to merge, or discard this patch.
Indentation   +614 added lines, -614 removed lines patch added patch discarded remove patch
@@ -31,620 +31,620 @@
 block discarded – undo
31 31
 class EventSpacesCalculator
32 32
 {
33 33
 
34
-    /**
35
-     * @var EE_Event $event
36
-     */
37
-    private $event;
38
-
39
-    /**
40
-     * @var array $datetime_query_params
41
-     */
42
-    private $datetime_query_params;
43
-
44
-    /**
45
-     * @var EE_Ticket[] $active_tickets
46
-     */
47
-    private $active_tickets = array();
48
-
49
-    /**
50
-     * @var EE_Datetime[] $datetimes
51
-     */
52
-    private $datetimes = array();
53
-
54
-    /**
55
-     * Array of Ticket IDs grouped by Datetime
56
-     *
57
-     * @var array $datetimes
58
-     */
59
-    private $datetime_tickets = array();
60
-
61
-    /**
62
-     * Max spaces for each Datetime (reg limit - previous sold)
63
-     *
64
-     * @var array $datetime_spaces
65
-     */
66
-    private $datetime_spaces = array();
67
-
68
-    /**
69
-     * Array of Datetime IDs grouped by Ticket
70
-     *
71
-     * @var array $ticket_datetimes
72
-     */
73
-    private $ticket_datetimes = array();
74
-
75
-    /**
76
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
77
-     *
78
-     * @var array $ticket_quantities
79
-     */
80
-    private $ticket_quantities = array();
81
-
82
-    /**
83
-     * total quantity of sold and reserved for each ticket
84
-     *
85
-     * @var array $tickets_sold
86
-     */
87
-    private $tickets_sold = array();
88
-
89
-    /**
90
-     * total spaces available across all datetimes
91
-     *
92
-     * @var array $total_spaces
93
-     */
94
-    private $total_spaces = array();
95
-
96
-    /**
97
-     * @var boolean $debug
98
-     */
99
-    private $debug = false;
100
-
101
-
102
-
103
-    /**
104
-     * EventSpacesCalculator constructor.
105
-     *
106
-     * @param EE_Event $event
107
-     * @param array    $datetime_query_params
108
-     * @throws EE_Error
109
-     */
110
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
111
-    {
112
-        $this->event                 = $event;
113
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * @return EE_Ticket[]
120
-     * @throws EE_Error
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     * @throws InvalidArgumentException
124
-     */
125
-    public function getActiveTickets()
126
-    {
127
-        if (empty($this->active_tickets)) {
128
-            $this->active_tickets = $this->event->tickets(
129
-                array(
130
-                    array(
131
-                        'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
132
-                        'TKT_deleted'  => false,
133
-                    ),
134
-                    'order_by' => array('TKT_qty' => 'ASC'),
135
-                )
136
-            );
137
-        }
138
-        return $this->active_tickets;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * @param EE_Ticket[] $active_tickets
145
-     * @throws EE_Error
146
-     * @throws DomainException
147
-     * @throws UnexpectedEntityException
148
-     */
149
-    public function setActiveTickets(array $active_tickets = array())
150
-    {
151
-        if ( ! empty($active_tickets)) {
152
-            foreach ($active_tickets as $active_ticket) {
153
-                $this->validateTicket($active_ticket);
154
-            }
155
-            // sort incoming array by ticket quantity (asc)
156
-            usort(
157
-                $active_tickets,
158
-                function (EE_Ticket $a, EE_Ticket $b) {
159
-                    if ($a->qty() === $b->qty()) {
160
-                        return 0;
161
-                    }
162
-                    return ($a->qty() < $b->qty())
163
-                        ? -1
164
-                        : 1;
165
-                }
166
-            );
167
-        }
168
-        $this->active_tickets = $active_tickets;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * @param $ticket
175
-     * @throws DomainException
176
-     * @throws EE_Error
177
-     * @throws UnexpectedEntityException
178
-     */
179
-    private function validateTicket($ticket)
180
-    {
181
-        if ( ! $ticket instanceof EE_Ticket) {
182
-            throw new DomainException(
183
-                esc_html__(
184
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
185
-                    'event_espresso'
186
-                )
187
-            );
188
-        }
189
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
190
-            throw new DomainException(
191
-                sprintf(
192
-                    esc_html__(
193
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
194
-                        'event_espresso'
195
-                    ),
196
-                    $ticket->get_event_ID(),
197
-                    $this->event->ID()
198
-                )
199
-            );
200
-        }
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * @return EE_Datetime[]
207
-     */
208
-    public function getDatetimes()
209
-    {
210
-        return $this->datetimes;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * @param EE_Datetime $datetime
217
-     * @throws EE_Error
218
-     * @throws DomainException
219
-     */
220
-    public function setDatetime(EE_Datetime $datetime)
221
-    {
222
-        if ($datetime->event()->ID() !== $this->event->ID()) {
223
-            throw new DomainException(
224
-                sprintf(
225
-                    esc_html__(
226
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
227
-                        'event_espresso'
228
-                    ),
229
-                    $datetime->event()->ID(),
230
-                    $this->event->ID()
231
-                )
232
-            );
233
-        }
234
-        $this->datetimes[ $datetime->ID() ] = $datetime;
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * calculate spaces remaining based on "saleable" tickets
241
-     *
242
-     * @return float|int
243
-     * @throws EE_Error
244
-     * @throws DomainException
245
-     * @throws UnexpectedEntityException
246
-     * @throws InvalidDataTypeException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidArgumentException
249
-     */
250
-    public function spacesRemaining()
251
-    {
252
-        $this->initialize();
253
-        return $this->calculate();
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * calculates total available spaces for an event with no regard for sold tickets
260
-     *
261
-     * @return int|float
262
-     * @throws EE_Error
263
-     * @throws DomainException
264
-     * @throws UnexpectedEntityException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws InvalidArgumentException
268
-     */
269
-    public function totalSpacesAvailable()
270
-    {
271
-        $this->initialize();
272
-        return $this->calculate(false);
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * Loops through the active tickets for the event
279
-     * and builds a series of data arrays that will be used for calculating
280
-     * the total maximum available spaces, as well as the spaces remaining.
281
-     * Because ticket quantities affect datetime spaces and vice versa,
282
-     * we need to be constantly updating these data arrays as things change,
283
-     * which is the entire reason for their existence.
284
-     *
285
-     * @throws EE_Error
286
-     * @throws DomainException
287
-     * @throws UnexpectedEntityException
288
-     * @throws InvalidDataTypeException
289
-     * @throws InvalidInterfaceException
290
-     * @throws InvalidArgumentException
291
-     */
292
-    private function initialize()
293
-    {
294
-        if ($this->debug) {
295
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
296
-        }
297
-        $this->datetime_tickets  = array();
298
-        $this->datetime_spaces   = array();
299
-        $this->ticket_datetimes  = array();
300
-        $this->ticket_quantities = array();
301
-        $this->tickets_sold      = array();
302
-        $this->total_spaces      = array();
303
-        $active_tickets          = $this->getActiveTickets();
304
-        if ( ! empty($active_tickets)) {
305
-            foreach ($active_tickets as $ticket) {
306
-                $this->validateTicket($ticket);
307
-                // we need to index our data arrays using strings for the purpose of sorting,
308
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
309
-                $ticket_identifier = "T{$ticket->ID()}";
310
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket
311
-                $max_tickets = $ticket->qty();
312
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
313
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
314
-                foreach ($ticket_datetimes as $datetime) {
315
-                    // save all datetimes
316
-                    $this->setDatetime($datetime);
317
-                    $datetime_identifier = "D{$datetime->ID()}";
318
-                    $reg_limit           = $datetime->reg_limit();
319
-                    // ticket quantity can not exceed datetime reg limit
320
-                    $max_tickets = min($max_tickets, $reg_limit);
321
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
322
-                    // we are going to move all of our data into the following arrays:
323
-                    // datetime spaces initially represents the reg limit for each datetime,
324
-                    // but this will get adjusted as tickets are accounted for
325
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
326
-                    // just an array of ticket IDs grouped by datetime
327
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
328
-                    // and an array of datetime IDs grouped by ticket
329
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
330
-                }
331
-                // total quantity of sold and reserved for each ticket
332
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
333
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
335
-            }
336
-        }
337
-        // sort datetime spaces by reg limit, but maintain our string indexes
338
-        asort($this->datetime_spaces, SORT_NUMERIC);
339
-        // datetime tickets need to be sorted in the SAME order as the above array...
340
-        // so we'll just use array_merge() to take the structure of datetime_spaces
341
-        // but overwrite all of the data with that from datetime_tickets
342
-        $this->datetime_tickets = array_merge(
343
-            $this->datetime_spaces,
344
-            $this->datetime_tickets
345
-        );
346
-        if ($this->debug) {
347
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
348
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
349
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
350
-        }
351
-    }
352
-
353
-
354
-
355
-    /**
356
-     * performs calculations on initialized data
357
-     *
358
-     * @param bool $consider_sold
359
-     * @return int|float
360
-     */
361
-    private function calculate($consider_sold = true)
362
-    {
363
-        if ($this->debug) {
364
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
365
-        }
366
-        if ($consider_sold) {
367
-            // subtract amounts sold from all ticket quantities and datetime spaces
368
-            $this->adjustTicketQuantitiesDueToSales();
369
-        }
370
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
371
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
372
-        }
373
-        // total spaces available is just the sum of the spaces available for each datetime
374
-        $spaces_remaining = array_sum($this->total_spaces);
375
-        if ($this->debug) {
376
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
377
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
378
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
379
-        }
380
-        return $spaces_remaining;
381
-    }
382
-
383
-
384
-    /**
385
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
386
-     */
387
-    private function adjustTicketQuantitiesDueToSales()
388
-    {
389
-        if ($this->debug) {
390
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
-        }
392
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
-            if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
395
-                if ($this->debug) {
396
-                    \EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397
-                }
398
-            }
399
-            if (
400
-                isset($this->ticket_datetimes[ $ticket_identifier ])
401
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
402
-            ){
403
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
406
-                        if ($this->debug) {
407
-                            \EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408
-                                'subtracting', __FILE__, __LINE__);
409
-                        }
410
-                    }
411
-                }
412
-            }
413
-        }
414
-    }
415
-
416
-
417
-
418
-    /**
419
-     * @param string $datetime_identifier
420
-     * @param array  $tickets
421
-     */
422
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423
-    {
424
-        // make sure a reg limit is set for the datetime
425
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
-            ? $this->datetime_spaces[ $datetime_identifier ]
427
-            : 0;
428
-        // and bail if it is not
429
-        if ( ! $reg_limit) {
430
-            if ($this->debug) {
431
-                \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
432
-            }
433
-            return;
434
-        }
435
-        if ($this->debug) {
436
-            \EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
437
-            \EEH_Debug_Tools::printr("{$reg_limit}", 'REG LIMIT', __FILE__, __LINE__);
438
-        }
439
-        // number of allocated spaces always starts at zero
440
-        $spaces_allocated                           = 0;
441
-        $this->total_spaces[ $datetime_identifier ] = 0;
442
-        foreach ($tickets as $ticket_identifier) {
443
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
444
-                $datetime_identifier,
445
-                $reg_limit,
446
-                $ticket_identifier,
447
-                $spaces_allocated
448
-            );
449
-        }
450
-        // spaces can't be negative
451
-        $spaces_allocated = max($spaces_allocated, 0);
452
-        if ($spaces_allocated) {
453
-            // track any non-zero values
454
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
455
-            if ($this->debug) {
456
-                \EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457
-            }
458
-        } else {
459
-            if ($this->debug) {
460
-                \EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
461
-            }
462
-        }
463
-        if ($this->debug) {
464
-            \EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
465
-                __LINE__);
466
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
468
-        }
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * @param string $datetime_identifier
475
-     * @param int    $reg_limit
476
-     * @param string $ticket_identifier
477
-     * @param int    $spaces_allocated
478
-     * @return int
479
-     */
480
-    private function calculateAvailableSpacesForTicket(
481
-        $datetime_identifier,
482
-        $reg_limit,
483
-        $ticket_identifier,
484
-        $spaces_allocated
485
-    ) {
486
-        // make sure ticket quantity is set
487
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
-            ? $this->ticket_quantities[ $ticket_identifier ]
489
-            : 0;
490
-        if ($this->debug) {
491
-            \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
492
-            \EEH_Debug_Tools::printr("{$ticket_quantity}", "ticket $ticket_identifier quantity: ",
493
-                __FILE__, __LINE__, 2);
494
-        }
495
-        if ($ticket_quantity) {
496
-            if ($this->debug) {
497
-                \EEH_Debug_Tools::printr(
498
-                    ($spaces_allocated <= $reg_limit)
499
-                        ? 'true'
500
-                        : 'false',
501
-                    ' . spaces_allocated <= reg_limit = ',
502
-                    __FILE__, __LINE__
503
-                );
504
-            }
505
-            // if the datetime is NOT at full capacity yet
506
-            if ($spaces_allocated <= $reg_limit) {
507
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
508
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
509
-                //  or the maximum ticket quantity
510
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511
-                // adjust the available quantity in our tracking array
512
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
513
-                // and increment spaces allocated for this datetime
514
-                $spaces_allocated += $ticket_quantity;
515
-                $at_capacity = $spaces_allocated >= $reg_limit;
516
-                if ($this->debug) {
517
-                    \EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
-                        __FILE__, __LINE__,   3);
519
-                    if ($at_capacity) {
520
-                        \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521
-                    }
522
-                }
523
-                // now adjust all other datetimes that allow access to this ticket
524
-                $this->adjustDatetimes(
525
-                    $datetime_identifier,
526
-                    $ticket_identifier,
527
-                    $ticket_quantity,
528
-                    $at_capacity
529
-                );
530
-            }
531
-        }
532
-        return $spaces_allocated;
533
-    }
534
-
535
-
536
-
537
-    /**
538
-     * subtracts ticket amounts from all datetime reg limits
539
-     * that allow access to the ticket specified,
540
-     * because that ticket could be used
541
-     * to attend any of the datetimes it has access to
542
-     *
543
-     * @param string $datetime_identifier
544
-     * @param string $ticket_identifier
545
-     * @param bool   $at_capacity
546
-     * @param int    $ticket_quantity
547
-     */
548
-    private function adjustDatetimes(
549
-        $datetime_identifier,
550
-        $ticket_identifier,
551
-        $ticket_quantity,
552
-        $at_capacity
553
-    ) {
554
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
555
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
556
-                continue;
557
-            }
558
-            $adjusted = $this->adjustDatetimeSpaces(
559
-                $datetime_ID,
560
-                $ticket_identifier,
561
-                $ticket_quantity
562
-            );
563
-            // skip to next ticket if nothing changed
564
-            if (! ($adjusted || $at_capacity)) {
565
-                continue;
566
-            }
567
-            // then all of it's tickets are now unavailable
568
-            foreach ($datetime_tickets as $datetime_ticket) {
569
-                if (
570
-                    ($ticket_identifier === $datetime_ticket || $at_capacity)
571
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
572
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
573
-                ) {
574
-                    if ($this->debug) {
575
-                        \EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
576
-                            __LINE__);
577
-                    }
578
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
579
-                    // otherwise just subtract the ticket quantity
580
-                    $new_quantity = $at_capacity
581
-                        ? 0
582
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
583
-                    // don't let ticket quantity go below zero
584
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
585
-                    if ($this->debug) {
586
-                        \EEH_Debug_Tools::printr(
587
-                            $at_capacity
588
-                                ? "0 because Datetime {$datetime_identifier} is at capacity"
589
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
590
-                            " . . . . {$datetime_ticket} quantity set to ",
591
-                            __FILE__, __LINE__
592
-                        );
593
-                    }
594
-                }
595
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
596
-                if ($datetime_ticket === $ticket_identifier) {
597
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
599
-                    ) {
600
-                        if ($this->debug) {
601
-                            \EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602
-                                __LINE__);
603
-                        }
604
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
605
-                            // don't adjust the current datetime twice
606
-                            if ($datetime !== $datetime_identifier) {
607
-                                $this->adjustDatetimeSpaces(
608
-                                    $datetime,
609
-                                    $datetime_ticket,
610
-                                    $ticket_quantity
611
-                                );
612
-                            }
613
-                        }
614
-                    }
615
-                }
616
-            }
617
-        }
618
-    }
619
-
620
-    private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
621
-    {
622
-        // does datetime have spaces available?
623
-        // and does the supplied ticket have access to this datetime ?
624
-        if (
625
-            $this->datetime_spaces[ $datetime_identifier ] > 0
626
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
628
-            ) {
629
-            if ($this->debug) {
630
-                \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
-                \EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632
-            }
633
-            // then decrement the available spaces for the datetime
634
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
635
-            // but don't let quantities go below zero
636
-            $this->datetime_spaces[ $datetime_identifier ] = max(
637
-                $this->datetime_spaces[ $datetime_identifier ],
638
-                0
639
-            );
640
-            if ($this->debug) {
641
-                \EEH_Debug_Tools::printr("{$ticket_quantity}",
642
-                    " . . . {$datetime_identifier} capacity reduced by", __FILE__, __LINE__);
643
-            }
644
-            return true;
645
-        }
646
-        return false;
647
-    }
34
+	/**
35
+	 * @var EE_Event $event
36
+	 */
37
+	private $event;
38
+
39
+	/**
40
+	 * @var array $datetime_query_params
41
+	 */
42
+	private $datetime_query_params;
43
+
44
+	/**
45
+	 * @var EE_Ticket[] $active_tickets
46
+	 */
47
+	private $active_tickets = array();
48
+
49
+	/**
50
+	 * @var EE_Datetime[] $datetimes
51
+	 */
52
+	private $datetimes = array();
53
+
54
+	/**
55
+	 * Array of Ticket IDs grouped by Datetime
56
+	 *
57
+	 * @var array $datetimes
58
+	 */
59
+	private $datetime_tickets = array();
60
+
61
+	/**
62
+	 * Max spaces for each Datetime (reg limit - previous sold)
63
+	 *
64
+	 * @var array $datetime_spaces
65
+	 */
66
+	private $datetime_spaces = array();
67
+
68
+	/**
69
+	 * Array of Datetime IDs grouped by Ticket
70
+	 *
71
+	 * @var array $ticket_datetimes
72
+	 */
73
+	private $ticket_datetimes = array();
74
+
75
+	/**
76
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
77
+	 *
78
+	 * @var array $ticket_quantities
79
+	 */
80
+	private $ticket_quantities = array();
81
+
82
+	/**
83
+	 * total quantity of sold and reserved for each ticket
84
+	 *
85
+	 * @var array $tickets_sold
86
+	 */
87
+	private $tickets_sold = array();
88
+
89
+	/**
90
+	 * total spaces available across all datetimes
91
+	 *
92
+	 * @var array $total_spaces
93
+	 */
94
+	private $total_spaces = array();
95
+
96
+	/**
97
+	 * @var boolean $debug
98
+	 */
99
+	private $debug = false;
100
+
101
+
102
+
103
+	/**
104
+	 * EventSpacesCalculator constructor.
105
+	 *
106
+	 * @param EE_Event $event
107
+	 * @param array    $datetime_query_params
108
+	 * @throws EE_Error
109
+	 */
110
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
111
+	{
112
+		$this->event                 = $event;
113
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * @return EE_Ticket[]
120
+	 * @throws EE_Error
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 * @throws InvalidArgumentException
124
+	 */
125
+	public function getActiveTickets()
126
+	{
127
+		if (empty($this->active_tickets)) {
128
+			$this->active_tickets = $this->event->tickets(
129
+				array(
130
+					array(
131
+						'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
132
+						'TKT_deleted'  => false,
133
+					),
134
+					'order_by' => array('TKT_qty' => 'ASC'),
135
+				)
136
+			);
137
+		}
138
+		return $this->active_tickets;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * @param EE_Ticket[] $active_tickets
145
+	 * @throws EE_Error
146
+	 * @throws DomainException
147
+	 * @throws UnexpectedEntityException
148
+	 */
149
+	public function setActiveTickets(array $active_tickets = array())
150
+	{
151
+		if ( ! empty($active_tickets)) {
152
+			foreach ($active_tickets as $active_ticket) {
153
+				$this->validateTicket($active_ticket);
154
+			}
155
+			// sort incoming array by ticket quantity (asc)
156
+			usort(
157
+				$active_tickets,
158
+				function (EE_Ticket $a, EE_Ticket $b) {
159
+					if ($a->qty() === $b->qty()) {
160
+						return 0;
161
+					}
162
+					return ($a->qty() < $b->qty())
163
+						? -1
164
+						: 1;
165
+				}
166
+			);
167
+		}
168
+		$this->active_tickets = $active_tickets;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * @param $ticket
175
+	 * @throws DomainException
176
+	 * @throws EE_Error
177
+	 * @throws UnexpectedEntityException
178
+	 */
179
+	private function validateTicket($ticket)
180
+	{
181
+		if ( ! $ticket instanceof EE_Ticket) {
182
+			throw new DomainException(
183
+				esc_html__(
184
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
185
+					'event_espresso'
186
+				)
187
+			);
188
+		}
189
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
190
+			throw new DomainException(
191
+				sprintf(
192
+					esc_html__(
193
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
194
+						'event_espresso'
195
+					),
196
+					$ticket->get_event_ID(),
197
+					$this->event->ID()
198
+				)
199
+			);
200
+		}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * @return EE_Datetime[]
207
+	 */
208
+	public function getDatetimes()
209
+	{
210
+		return $this->datetimes;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * @param EE_Datetime $datetime
217
+	 * @throws EE_Error
218
+	 * @throws DomainException
219
+	 */
220
+	public function setDatetime(EE_Datetime $datetime)
221
+	{
222
+		if ($datetime->event()->ID() !== $this->event->ID()) {
223
+			throw new DomainException(
224
+				sprintf(
225
+					esc_html__(
226
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
227
+						'event_espresso'
228
+					),
229
+					$datetime->event()->ID(),
230
+					$this->event->ID()
231
+				)
232
+			);
233
+		}
234
+		$this->datetimes[ $datetime->ID() ] = $datetime;
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * calculate spaces remaining based on "saleable" tickets
241
+	 *
242
+	 * @return float|int
243
+	 * @throws EE_Error
244
+	 * @throws DomainException
245
+	 * @throws UnexpectedEntityException
246
+	 * @throws InvalidDataTypeException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidArgumentException
249
+	 */
250
+	public function spacesRemaining()
251
+	{
252
+		$this->initialize();
253
+		return $this->calculate();
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * calculates total available spaces for an event with no regard for sold tickets
260
+	 *
261
+	 * @return int|float
262
+	 * @throws EE_Error
263
+	 * @throws DomainException
264
+	 * @throws UnexpectedEntityException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws InvalidArgumentException
268
+	 */
269
+	public function totalSpacesAvailable()
270
+	{
271
+		$this->initialize();
272
+		return $this->calculate(false);
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * Loops through the active tickets for the event
279
+	 * and builds a series of data arrays that will be used for calculating
280
+	 * the total maximum available spaces, as well as the spaces remaining.
281
+	 * Because ticket quantities affect datetime spaces and vice versa,
282
+	 * we need to be constantly updating these data arrays as things change,
283
+	 * which is the entire reason for their existence.
284
+	 *
285
+	 * @throws EE_Error
286
+	 * @throws DomainException
287
+	 * @throws UnexpectedEntityException
288
+	 * @throws InvalidDataTypeException
289
+	 * @throws InvalidInterfaceException
290
+	 * @throws InvalidArgumentException
291
+	 */
292
+	private function initialize()
293
+	{
294
+		if ($this->debug) {
295
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
296
+		}
297
+		$this->datetime_tickets  = array();
298
+		$this->datetime_spaces   = array();
299
+		$this->ticket_datetimes  = array();
300
+		$this->ticket_quantities = array();
301
+		$this->tickets_sold      = array();
302
+		$this->total_spaces      = array();
303
+		$active_tickets          = $this->getActiveTickets();
304
+		if ( ! empty($active_tickets)) {
305
+			foreach ($active_tickets as $ticket) {
306
+				$this->validateTicket($ticket);
307
+				// we need to index our data arrays using strings for the purpose of sorting,
308
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
309
+				$ticket_identifier = "T{$ticket->ID()}";
310
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket
311
+				$max_tickets = $ticket->qty();
312
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
313
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
314
+				foreach ($ticket_datetimes as $datetime) {
315
+					// save all datetimes
316
+					$this->setDatetime($datetime);
317
+					$datetime_identifier = "D{$datetime->ID()}";
318
+					$reg_limit           = $datetime->reg_limit();
319
+					// ticket quantity can not exceed datetime reg limit
320
+					$max_tickets = min($max_tickets, $reg_limit);
321
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
322
+					// we are going to move all of our data into the following arrays:
323
+					// datetime spaces initially represents the reg limit for each datetime,
324
+					// but this will get adjusted as tickets are accounted for
325
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
326
+					// just an array of ticket IDs grouped by datetime
327
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
328
+					// and an array of datetime IDs grouped by ticket
329
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
330
+				}
331
+				// total quantity of sold and reserved for each ticket
332
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
333
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
335
+			}
336
+		}
337
+		// sort datetime spaces by reg limit, but maintain our string indexes
338
+		asort($this->datetime_spaces, SORT_NUMERIC);
339
+		// datetime tickets need to be sorted in the SAME order as the above array...
340
+		// so we'll just use array_merge() to take the structure of datetime_spaces
341
+		// but overwrite all of the data with that from datetime_tickets
342
+		$this->datetime_tickets = array_merge(
343
+			$this->datetime_spaces,
344
+			$this->datetime_tickets
345
+		);
346
+		if ($this->debug) {
347
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
348
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
349
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
350
+		}
351
+	}
352
+
353
+
354
+
355
+	/**
356
+	 * performs calculations on initialized data
357
+	 *
358
+	 * @param bool $consider_sold
359
+	 * @return int|float
360
+	 */
361
+	private function calculate($consider_sold = true)
362
+	{
363
+		if ($this->debug) {
364
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
365
+		}
366
+		if ($consider_sold) {
367
+			// subtract amounts sold from all ticket quantities and datetime spaces
368
+			$this->adjustTicketQuantitiesDueToSales();
369
+		}
370
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
371
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
372
+		}
373
+		// total spaces available is just the sum of the spaces available for each datetime
374
+		$spaces_remaining = array_sum($this->total_spaces);
375
+		if ($this->debug) {
376
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
377
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
378
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
379
+		}
380
+		return $spaces_remaining;
381
+	}
382
+
383
+
384
+	/**
385
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
386
+	 */
387
+	private function adjustTicketQuantitiesDueToSales()
388
+	{
389
+		if ($this->debug) {
390
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391
+		}
392
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
+			if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
395
+				if ($this->debug) {
396
+					\EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397
+				}
398
+			}
399
+			if (
400
+				isset($this->ticket_datetimes[ $ticket_identifier ])
401
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
402
+			){
403
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
406
+						if ($this->debug) {
407
+							\EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408
+								'subtracting', __FILE__, __LINE__);
409
+						}
410
+					}
411
+				}
412
+			}
413
+		}
414
+	}
415
+
416
+
417
+
418
+	/**
419
+	 * @param string $datetime_identifier
420
+	 * @param array  $tickets
421
+	 */
422
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423
+	{
424
+		// make sure a reg limit is set for the datetime
425
+		$reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
+			? $this->datetime_spaces[ $datetime_identifier ]
427
+			: 0;
428
+		// and bail if it is not
429
+		if ( ! $reg_limit) {
430
+			if ($this->debug) {
431
+				\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
432
+			}
433
+			return;
434
+		}
435
+		if ($this->debug) {
436
+			\EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
437
+			\EEH_Debug_Tools::printr("{$reg_limit}", 'REG LIMIT', __FILE__, __LINE__);
438
+		}
439
+		// number of allocated spaces always starts at zero
440
+		$spaces_allocated                           = 0;
441
+		$this->total_spaces[ $datetime_identifier ] = 0;
442
+		foreach ($tickets as $ticket_identifier) {
443
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
444
+				$datetime_identifier,
445
+				$reg_limit,
446
+				$ticket_identifier,
447
+				$spaces_allocated
448
+			);
449
+		}
450
+		// spaces can't be negative
451
+		$spaces_allocated = max($spaces_allocated, 0);
452
+		if ($spaces_allocated) {
453
+			// track any non-zero values
454
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
455
+			if ($this->debug) {
456
+				\EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457
+			}
458
+		} else {
459
+			if ($this->debug) {
460
+				\EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
461
+			}
462
+		}
463
+		if ($this->debug) {
464
+			\EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
465
+				__LINE__);
466
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
468
+		}
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * @param string $datetime_identifier
475
+	 * @param int    $reg_limit
476
+	 * @param string $ticket_identifier
477
+	 * @param int    $spaces_allocated
478
+	 * @return int
479
+	 */
480
+	private function calculateAvailableSpacesForTicket(
481
+		$datetime_identifier,
482
+		$reg_limit,
483
+		$ticket_identifier,
484
+		$spaces_allocated
485
+	) {
486
+		// make sure ticket quantity is set
487
+		$ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
+			? $this->ticket_quantities[ $ticket_identifier ]
489
+			: 0;
490
+		if ($this->debug) {
491
+			\EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
492
+			\EEH_Debug_Tools::printr("{$ticket_quantity}", "ticket $ticket_identifier quantity: ",
493
+				__FILE__, __LINE__, 2);
494
+		}
495
+		if ($ticket_quantity) {
496
+			if ($this->debug) {
497
+				\EEH_Debug_Tools::printr(
498
+					($spaces_allocated <= $reg_limit)
499
+						? 'true'
500
+						: 'false',
501
+					' . spaces_allocated <= reg_limit = ',
502
+					__FILE__, __LINE__
503
+				);
504
+			}
505
+			// if the datetime is NOT at full capacity yet
506
+			if ($spaces_allocated <= $reg_limit) {
507
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
508
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
509
+				//  or the maximum ticket quantity
510
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511
+				// adjust the available quantity in our tracking array
512
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
513
+				// and increment spaces allocated for this datetime
514
+				$spaces_allocated += $ticket_quantity;
515
+				$at_capacity = $spaces_allocated >= $reg_limit;
516
+				if ($this->debug) {
517
+					\EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
+						__FILE__, __LINE__,   3);
519
+					if ($at_capacity) {
520
+						\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521
+					}
522
+				}
523
+				// now adjust all other datetimes that allow access to this ticket
524
+				$this->adjustDatetimes(
525
+					$datetime_identifier,
526
+					$ticket_identifier,
527
+					$ticket_quantity,
528
+					$at_capacity
529
+				);
530
+			}
531
+		}
532
+		return $spaces_allocated;
533
+	}
534
+
535
+
536
+
537
+	/**
538
+	 * subtracts ticket amounts from all datetime reg limits
539
+	 * that allow access to the ticket specified,
540
+	 * because that ticket could be used
541
+	 * to attend any of the datetimes it has access to
542
+	 *
543
+	 * @param string $datetime_identifier
544
+	 * @param string $ticket_identifier
545
+	 * @param bool   $at_capacity
546
+	 * @param int    $ticket_quantity
547
+	 */
548
+	private function adjustDatetimes(
549
+		$datetime_identifier,
550
+		$ticket_identifier,
551
+		$ticket_quantity,
552
+		$at_capacity
553
+	) {
554
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
555
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
556
+				continue;
557
+			}
558
+			$adjusted = $this->adjustDatetimeSpaces(
559
+				$datetime_ID,
560
+				$ticket_identifier,
561
+				$ticket_quantity
562
+			);
563
+			// skip to next ticket if nothing changed
564
+			if (! ($adjusted || $at_capacity)) {
565
+				continue;
566
+			}
567
+			// then all of it's tickets are now unavailable
568
+			foreach ($datetime_tickets as $datetime_ticket) {
569
+				if (
570
+					($ticket_identifier === $datetime_ticket || $at_capacity)
571
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
572
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
573
+				) {
574
+					if ($this->debug) {
575
+						\EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
576
+							__LINE__);
577
+					}
578
+					// if this datetime is at full capacity, set any tracked available quantities to zero
579
+					// otherwise just subtract the ticket quantity
580
+					$new_quantity = $at_capacity
581
+						? 0
582
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
583
+					// don't let ticket quantity go below zero
584
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
585
+					if ($this->debug) {
586
+						\EEH_Debug_Tools::printr(
587
+							$at_capacity
588
+								? "0 because Datetime {$datetime_identifier} is at capacity"
589
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
590
+							" . . . . {$datetime_ticket} quantity set to ",
591
+							__FILE__, __LINE__
592
+						);
593
+					}
594
+				}
595
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
596
+				if ($datetime_ticket === $ticket_identifier) {
597
+					if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
599
+					) {
600
+						if ($this->debug) {
601
+							\EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602
+								__LINE__);
603
+						}
604
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
605
+							// don't adjust the current datetime twice
606
+							if ($datetime !== $datetime_identifier) {
607
+								$this->adjustDatetimeSpaces(
608
+									$datetime,
609
+									$datetime_ticket,
610
+									$ticket_quantity
611
+								);
612
+							}
613
+						}
614
+					}
615
+				}
616
+			}
617
+		}
618
+	}
619
+
620
+	private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
621
+	{
622
+		// does datetime have spaces available?
623
+		// and does the supplied ticket have access to this datetime ?
624
+		if (
625
+			$this->datetime_spaces[ $datetime_identifier ] > 0
626
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
628
+			) {
629
+			if ($this->debug) {
630
+				\EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
+				\EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632
+			}
633
+			// then decrement the available spaces for the datetime
634
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
635
+			// but don't let quantities go below zero
636
+			$this->datetime_spaces[ $datetime_identifier ] = max(
637
+				$this->datetime_spaces[ $datetime_identifier ],
638
+				0
639
+			);
640
+			if ($this->debug) {
641
+				\EEH_Debug_Tools::printr("{$ticket_quantity}",
642
+					" . . . {$datetime_identifier} capacity reduced by", __FILE__, __LINE__);
643
+			}
644
+			return true;
645
+		}
646
+		return false;
647
+	}
648 648
 
649 649
 }
650 650
 // Location: EventSpacesCalculator.php
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
             // sort incoming array by ticket quantity (asc)
156 156
             usort(
157 157
                 $active_tickets,
158
-                function (EE_Ticket $a, EE_Ticket $b) {
158
+                function(EE_Ticket $a, EE_Ticket $b) {
159 159
                     if ($a->qty() === $b->qty()) {
160 160
                         return 0;
161 161
                     }
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
                 )
232 232
             );
233 233
         }
234
-        $this->datetimes[ $datetime->ID() ] = $datetime;
234
+        $this->datetimes[$datetime->ID()] = $datetime;
235 235
     }
236 236
 
237 237
 
@@ -322,16 +322,16 @@  discard block
 block discarded – undo
322 322
                     // we are going to move all of our data into the following arrays:
323 323
                     // datetime spaces initially represents the reg limit for each datetime,
324 324
                     // but this will get adjusted as tickets are accounted for
325
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
325
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
326 326
                     // just an array of ticket IDs grouped by datetime
327
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
327
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
328 328
                     // and an array of datetime IDs grouped by ticket
329
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
329
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
330 330
                 }
331 331
                 // total quantity of sold and reserved for each ticket
332
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
332
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
333 333
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
334
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
334
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
335 335
             }
336 336
         }
337 337
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -390,19 +390,19 @@  discard block
 block discarded – undo
390 390
             \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
391 391
         }
392 392
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
393
-            if (isset($this->ticket_quantities[ $ticket_identifier ])){
394
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
393
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
394
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
395 395
                 if ($this->debug) {
396 396
                     \EEH_Debug_Tools::printr("{$tickets_sold} sales for ticket {$ticket_identifier} ", 'subtracting', __FILE__, __LINE__);
397 397
                 }
398 398
             }
399 399
             if (
400
-                isset($this->ticket_datetimes[ $ticket_identifier ])
401
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
402
-            ){
403
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
404
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
405
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
400
+                isset($this->ticket_datetimes[$ticket_identifier])
401
+                && is_array($this->ticket_datetimes[$ticket_identifier])
402
+            ) {
403
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
404
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
405
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
406 406
                         if ($this->debug) {
407 407
                             \EEH_Debug_Tools::printr("{$tickets_sold} sales for datetime {$ticket_datetime} ",
408 408
                                 'subtracting', __FILE__, __LINE__);
@@ -422,8 +422,8 @@  discard block
 block discarded – undo
422 422
     private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
423 423
     {
424 424
         // make sure a reg limit is set for the datetime
425
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
426
-            ? $this->datetime_spaces[ $datetime_identifier ]
425
+        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
426
+            ? $this->datetime_spaces[$datetime_identifier]
427 427
             : 0;
428 428
         // and bail if it is not
429 429
         if ( ! $reg_limit) {
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
         }
439 439
         // number of allocated spaces always starts at zero
440 440
         $spaces_allocated                           = 0;
441
-        $this->total_spaces[ $datetime_identifier ] = 0;
441
+        $this->total_spaces[$datetime_identifier] = 0;
442 442
         foreach ($tickets as $ticket_identifier) {
443 443
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
444 444
                 $datetime_identifier,
@@ -451,9 +451,9 @@  discard block
 block discarded – undo
451 451
         $spaces_allocated = max($spaces_allocated, 0);
452 452
         if ($spaces_allocated) {
453 453
             // track any non-zero values
454
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
454
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
455 455
             if ($this->debug) {
456
-                \EEH_Debug_Tools::printr((string)$spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
456
+                \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
457 457
             }
458 458
         } else {
459 459
             if ($this->debug) {
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
             }
462 462
         }
463 463
         if ($this->debug) {
464
-            \EEH_Debug_Tools::printr($this->total_spaces[ $datetime_identifier ], '$total_spaces', __FILE__,
464
+            \EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$total_spaces', __FILE__,
465 465
                 __LINE__);
466 466
             \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
467 467
             \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
@@ -484,8 +484,8 @@  discard block
 block discarded – undo
484 484
         $spaces_allocated
485 485
     ) {
486 486
         // make sure ticket quantity is set
487
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
488
-            ? $this->ticket_quantities[ $ticket_identifier ]
487
+        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
488
+            ? $this->ticket_quantities[$ticket_identifier]
489 489
             : 0;
490 490
         if ($this->debug) {
491 491
             \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
@@ -509,13 +509,13 @@  discard block
 block discarded – undo
509 509
                 //  or the maximum ticket quantity
510 510
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
511 511
                 // adjust the available quantity in our tracking array
512
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
512
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
513 513
                 // and increment spaces allocated for this datetime
514 514
                 $spaces_allocated += $ticket_quantity;
515 515
                 $at_capacity = $spaces_allocated >= $reg_limit;
516 516
                 if ($this->debug) {
517 517
                     \EEH_Debug_Tools::printr("{$ticket_quantity} {$ticket_identifier} tickets", ' > > allocate ',
518
-                        __FILE__, __LINE__,   3);
518
+                        __FILE__, __LINE__, 3);
519 519
                     if ($at_capacity) {
520 520
                         \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
521 521
                     }
@@ -561,15 +561,15 @@  discard block
 block discarded – undo
561 561
                 $ticket_quantity
562 562
             );
563 563
             // skip to next ticket if nothing changed
564
-            if (! ($adjusted || $at_capacity)) {
564
+            if ( ! ($adjusted || $at_capacity)) {
565 565
                 continue;
566 566
             }
567 567
             // then all of it's tickets are now unavailable
568 568
             foreach ($datetime_tickets as $datetime_ticket) {
569 569
                 if (
570 570
                     ($ticket_identifier === $datetime_ticket || $at_capacity)
571
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
572
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
571
+                    && isset($this->ticket_quantities[$datetime_ticket])
572
+                    && $this->ticket_quantities[$datetime_ticket] > 0
573 573
                 ) {
574 574
                     if ($this->debug) {
575 575
                         \EEH_Debug_Tools::printr($datetime_ticket, ' . . . adjust ticket quantities for', __FILE__,
@@ -579,14 +579,14 @@  discard block
 block discarded – undo
579 579
                     // otherwise just subtract the ticket quantity
580 580
                     $new_quantity = $at_capacity
581 581
                         ? 0
582
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
582
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
583 583
                     // don't let ticket quantity go below zero
584
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
584
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
585 585
                     if ($this->debug) {
586 586
                         \EEH_Debug_Tools::printr(
587 587
                             $at_capacity
588 588
                                 ? "0 because Datetime {$datetime_identifier} is at capacity"
589
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
589
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
590 590
                             " . . . . {$datetime_ticket} quantity set to ",
591 591
                             __FILE__, __LINE__
592 592
                         );
@@ -594,14 +594,14 @@  discard block
 block discarded – undo
594 594
                 }
595 595
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
596 596
                 if ($datetime_ticket === $ticket_identifier) {
597
-                    if (isset($this->ticket_datetimes[ $datetime_ticket ])
598
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
597
+                    if (isset($this->ticket_datetimes[$datetime_ticket])
598
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
599 599
                     ) {
600 600
                         if ($this->debug) {
601 601
                             \EEH_Debug_Tools::printr($datetime_ticket, ' . . adjust other Datetimes for', __FILE__,
602 602
                                 __LINE__);
603 603
                         }
604
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
604
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
605 605
                             // don't adjust the current datetime twice
606 606
                             if ($datetime !== $datetime_identifier) {
607 607
                                 $this->adjustDatetimeSpaces(
@@ -622,19 +622,19 @@  discard block
 block discarded – undo
622 622
         // does datetime have spaces available?
623 623
         // and does the supplied ticket have access to this datetime ?
624 624
         if (
625
-            $this->datetime_spaces[ $datetime_identifier ] > 0
626
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
627
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
625
+            $this->datetime_spaces[$datetime_identifier] > 0
626
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
627
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
628 628
             ) {
629 629
             if ($this->debug) {
630 630
                 \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
631
-                \EEH_Debug_Tools::printr("{$this->datetime_spaces[ $datetime_identifier ]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
631
+                \EEH_Debug_Tools::printr("{$this->datetime_spaces[$datetime_identifier]}", " . . current  {$datetime_identifier} spaces available", __FILE__, __LINE__);
632 632
             }
633 633
             // then decrement the available spaces for the datetime
634
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
634
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
635 635
             // but don't let quantities go below zero
636
-            $this->datetime_spaces[ $datetime_identifier ] = max(
637
-                $this->datetime_spaces[ $datetime_identifier ],
636
+            $this->datetime_spaces[$datetime_identifier] = max(
637
+                $this->datetime_spaces[$datetime_identifier],
638 638
                 0
639 639
             );
640 640
             if ($this->debug) {
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 2 patches
Indentation   +1285 added lines, -1285 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6 6
 if (!defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -18,1289 +18,1289 @@  discard block
 block discarded – undo
18 18
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
19 19
 {
20 20
 
21
-    /**
22
-     * cached value for the the logical active status for the event
23
-     *
24
-     * @see get_active_status()
25
-     * @var string
26
-     */
27
-    protected $_active_status = '';
28
-
29
-    /**
30
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
-     *
32
-     * @var EE_Datetime
33
-     */
34
-    protected $_Primary_Datetime;
35
-
36
-    /**
37
-     * @var EventSpacesCalculator $available_spaces_calculator
38
-     */
39
-    protected $available_spaces_calculator;
40
-
41
-
42
-    /**
43
-     * @param array $props_n_values incoming values
44
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
-     *                                        used.)
46
-     * @param array $date_formats incoming date_formats in an array where the first value is the
47
-     *                                        date_format and the second value is the time format
48
-     * @return EE_Event
49
-     * @throws EE_Error
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values incoming values from the database
60
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Event
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return EventSpacesCalculator
74
-     * @throws \EE_Error
75
-     */
76
-    public function getAvailableSpacesCalculator()
77
-    {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
-     *
89
-     * @param string $field_name
90
-     * @param mixed $field_value
91
-     * @param bool $use_default
92
-     * @throws EE_Error
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status' :
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default :
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @access public
113
-     * @param string $new_status
114
-     * @param bool $use_default
115
-     * @return void
116
-     * @throws EE_Error
117
-     */
118
-    public function set_status($new_status = null, $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $new_status) {
128
-            // TO sold_out
129
-            if ($new_status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
-                // OR FROM  sold_out
134
-            } else if ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
-            }
138
-            // update status
139
-            parent::set('status', $new_status, $use_default);
140
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
141
-            return;
142
-        }
143
-        // even though the old value matches the new value, it's still good to
144
-        // allow the parent set method to have a say
145
-        parent::set('status', $new_status, $use_default);
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets all the datetimes for this event
151
-     *
152
-     * @param array $query_params like EEM_Base::get_all
153
-     * @return EE_Base_Class[]|EE_Datetime[]
154
-     * @throws EE_Error
155
-     */
156
-    public function datetimes($query_params = array())
157
-    {
158
-        return $this->get_many_related('Datetime', $query_params);
159
-    }
160
-
161
-
162
-    /**
163
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
-     *
165
-     * @return EE_Base_Class[]|EE_Datetime[]
166
-     * @throws EE_Error
167
-     */
168
-    public function datetimes_in_chronological_order()
169
-    {
170
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
-    }
172
-
173
-
174
-    /**
175
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
-     * after running our query, so that this timezone isn't set for EVERY query
178
-     * on EEM_Datetime for the rest of the request, no?
179
-     *
180
-     * @param boolean $show_expired whether or not to include expired events
181
-     * @param boolean $show_deleted whether or not to include deleted events
182
-     * @param null $limit
183
-     * @return EE_Datetime[]
184
-     * @throws EE_Error
185
-     */
186
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
-    {
188
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
-            $this->ID(),
190
-            $show_expired,
191
-            $show_deleted,
192
-            $limit
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * Returns one related datetime. Mostly only used by some legacy code.
199
-     *
200
-     * @return EE_Base_Class|EE_Datetime
201
-     * @throws EE_Error
202
-     */
203
-    public function first_datetime()
204
-    {
205
-        return $this->get_first_related('Datetime');
206
-    }
207
-
208
-
209
-    /**
210
-     * Returns the 'primary' datetime for the event
211
-     *
212
-     * @param bool $try_to_exclude_expired
213
-     * @param bool $try_to_exclude_deleted
214
-     * @return EE_Datetime
215
-     * @throws EE_Error
216
-     */
217
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
-    {
219
-        if (!empty ($this->_Primary_Datetime)) {
220
-            return $this->_Primary_Datetime;
221
-        }
222
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
-            $this->ID(),
224
-            $try_to_exclude_expired,
225
-            $try_to_exclude_deleted
226
-        );
227
-        return $this->_Primary_Datetime;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets all the tickets available for purchase of this event
233
-     *
234
-     * @param array $query_params like EEM_Base::get_all
235
-     * @return EE_Base_Class[]|EE_Ticket[]
236
-     * @throws EE_Error
237
-     */
238
-    public function tickets($query_params = array())
239
-    {
240
-        //first get all datetimes
241
-        $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
243
-            return array();
244
-        }
245
-        $datetime_ids = array();
246
-        foreach ($datetimes as $datetime) {
247
-            $datetime_ids[] = $datetime->ID();
248
-        }
249
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
-        //if incoming $query_params has where conditions let's merge but not override existing.
251
-        if (is_array($query_params) && isset($query_params[0])) {
252
-            $where_params = array_merge($query_params[0], $where_params);
253
-            unset($query_params[0]);
254
-        }
255
-        //now add $where_params to $query_params
256
-        $query_params[0] = $where_params;
257
-        return EEM_Ticket::instance()->get_all($query_params);
258
-    }
259
-
260
-
261
-    /**
262
-     * get all unexpired untrashed tickets
263
-     *
264
-     * @return EE_Ticket[]
265
-     * @throws EE_Error
266
-     */
267
-    public function active_tickets()
268
-    {
269
-        return $this->tickets(array(
270
-            array(
271
-                'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
-                'TKT_deleted' => false,
273
-            ),
274
-        ));
275
-    }
276
-
277
-
278
-    /**
279
-     * @return bool
280
-     * @throws EE_Error
281
-     */
282
-    public function additional_limit()
283
-    {
284
-        return $this->get('EVT_additional_limit');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return bool
290
-     * @throws EE_Error
291
-     */
292
-    public function allow_overflow()
293
-    {
294
-        return $this->get('EVT_allow_overflow');
295
-    }
296
-
297
-
298
-    /**
299
-     * @return bool
300
-     * @throws EE_Error
301
-     */
302
-    public function created()
303
-    {
304
-        return $this->get('EVT_created');
305
-    }
306
-
307
-
308
-    /**
309
-     * @return bool
310
-     * @throws EE_Error
311
-     */
312
-    public function description()
313
-    {
314
-        return $this->get('EVT_desc');
315
-    }
316
-
317
-
318
-    /**
319
-     * Runs do_shortcode and wpautop on the description
320
-     *
321
-     * @return string of html
322
-     * @throws EE_Error
323
-     */
324
-    public function description_filtered()
325
-    {
326
-        return $this->get_pretty('EVT_desc');
327
-    }
328
-
329
-
330
-    /**
331
-     * @return bool
332
-     * @throws EE_Error
333
-     */
334
-    public function display_description()
335
-    {
336
-        return $this->get('EVT_display_desc');
337
-    }
338
-
339
-
340
-    /**
341
-     * @return bool
342
-     * @throws EE_Error
343
-     */
344
-    public function display_ticket_selector()
345
-    {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
347
-    }
348
-
349
-
350
-    /**
351
-     * @return bool
352
-     * @throws EE_Error
353
-     */
354
-    public function external_url()
355
-    {
356
-        return $this->get('EVT_external_URL');
357
-    }
358
-
359
-
360
-    /**
361
-     * @return bool
362
-     * @throws EE_Error
363
-     */
364
-    public function member_only()
365
-    {
366
-        return $this->get('EVT_member_only');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return bool
372
-     * @throws EE_Error
373
-     */
374
-    public function phone()
375
-    {
376
-        return $this->get('EVT_phone');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     */
384
-    public function modified()
385
-    {
386
-        return $this->get('EVT_modified');
387
-    }
388
-
389
-
390
-    /**
391
-     * @return bool
392
-     * @throws EE_Error
393
-     */
394
-    public function name()
395
-    {
396
-        return $this->get('EVT_name');
397
-    }
398
-
399
-
400
-    /**
401
-     * @return bool
402
-     * @throws EE_Error
403
-     */
404
-    public function order()
405
-    {
406
-        return $this->get('EVT_order');
407
-    }
408
-
409
-
410
-    /**
411
-     * @return bool|string
412
-     * @throws EE_Error
413
-     */
414
-    public function default_registration_status()
415
-    {
416
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
418
-            ? $event_default_registration_status
419
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
420
-    }
421
-
422
-
423
-    /**
424
-     * @param int $num_words
425
-     * @param null $more
426
-     * @param bool $not_full_desc
427
-     * @return bool|string
428
-     * @throws EE_Error
429
-     */
430
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
-    {
432
-        $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
434
-            return $short_desc;
435
-        }
436
-        $full_desc = $this->get('EVT_desc');
437
-        return wp_trim_words($full_desc, $num_words, $more);
438
-    }
439
-
440
-
441
-    /**
442
-     * @return bool
443
-     * @throws EE_Error
444
-     */
445
-    public function slug()
446
-    {
447
-        return $this->get('EVT_slug');
448
-    }
449
-
450
-
451
-    /**
452
-     * @return bool
453
-     * @throws EE_Error
454
-     */
455
-    public function timezone_string()
456
-    {
457
-        return $this->get('EVT_timezone_string');
458
-    }
459
-
460
-
461
-    /**
462
-     * @return bool
463
-     * @throws EE_Error
464
-     */
465
-    public function visible_on()
466
-    {
467
-        return $this->get('EVT_visible_on');
468
-    }
469
-
470
-
471
-    /**
472
-     * @return int
473
-     * @throws EE_Error
474
-     */
475
-    public function wp_user()
476
-    {
477
-        return $this->get('EVT_wp_user');
478
-    }
479
-
480
-
481
-    /**
482
-     * @return bool
483
-     * @throws EE_Error
484
-     */
485
-    public function donations()
486
-    {
487
-        return $this->get('EVT_donations');
488
-    }
489
-
490
-
491
-    /**
492
-     * @param $limit
493
-     * @throws EE_Error
494
-     */
495
-    public function set_additional_limit($limit)
496
-    {
497
-        $this->set('EVT_additional_limit', $limit);
498
-    }
499
-
500
-
501
-    /**
502
-     * @param $created
503
-     * @throws EE_Error
504
-     */
505
-    public function set_created($created)
506
-    {
507
-        $this->set('EVT_created', $created);
508
-    }
509
-
510
-
511
-    /**
512
-     * @param $desc
513
-     * @throws EE_Error
514
-     */
515
-    public function set_description($desc)
516
-    {
517
-        $this->set('EVT_desc', $desc);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param $display_desc
523
-     * @throws EE_Error
524
-     */
525
-    public function set_display_description($display_desc)
526
-    {
527
-        $this->set('EVT_display_desc', $display_desc);
528
-    }
529
-
530
-
531
-    /**
532
-     * @param $display_ticket_selector
533
-     * @throws EE_Error
534
-     */
535
-    public function set_display_ticket_selector($display_ticket_selector)
536
-    {
537
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
-    }
539
-
540
-
541
-    /**
542
-     * @param $external_url
543
-     * @throws EE_Error
544
-     */
545
-    public function set_external_url($external_url)
546
-    {
547
-        $this->set('EVT_external_URL', $external_url);
548
-    }
549
-
550
-
551
-    /**
552
-     * @param $member_only
553
-     * @throws EE_Error
554
-     */
555
-    public function set_member_only($member_only)
556
-    {
557
-        $this->set('EVT_member_only', $member_only);
558
-    }
559
-
560
-
561
-    /**
562
-     * @param $event_phone
563
-     * @throws EE_Error
564
-     */
565
-    public function set_event_phone($event_phone)
566
-    {
567
-        $this->set('EVT_phone', $event_phone);
568
-    }
569
-
570
-
571
-    /**
572
-     * @param $modified
573
-     * @throws EE_Error
574
-     */
575
-    public function set_modified($modified)
576
-    {
577
-        $this->set('EVT_modified', $modified);
578
-    }
579
-
580
-
581
-    /**
582
-     * @param $name
583
-     * @throws EE_Error
584
-     */
585
-    public function set_name($name)
586
-    {
587
-        $this->set('EVT_name', $name);
588
-    }
589
-
590
-
591
-    /**
592
-     * @param $order
593
-     * @throws EE_Error
594
-     */
595
-    public function set_order($order)
596
-    {
597
-        $this->set('EVT_order', $order);
598
-    }
599
-
600
-
601
-    /**
602
-     * @param $short_desc
603
-     * @throws EE_Error
604
-     */
605
-    public function set_short_description($short_desc)
606
-    {
607
-        $this->set('EVT_short_desc', $short_desc);
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $slug
613
-     * @throws EE_Error
614
-     */
615
-    public function set_slug($slug)
616
-    {
617
-        $this->set('EVT_slug', $slug);
618
-    }
619
-
620
-
621
-    /**
622
-     * @param $timezone_string
623
-     * @throws EE_Error
624
-     */
625
-    public function set_timezone_string($timezone_string)
626
-    {
627
-        $this->set('EVT_timezone_string', $timezone_string);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $visible_on
633
-     * @throws EE_Error
634
-     */
635
-    public function set_visible_on($visible_on)
636
-    {
637
-        $this->set('EVT_visible_on', $visible_on);
638
-    }
639
-
640
-
641
-    /**
642
-     * @param $wp_user
643
-     * @throws EE_Error
644
-     */
645
-    public function set_wp_user($wp_user)
646
-    {
647
-        $this->set('EVT_wp_user', $wp_user);
648
-    }
649
-
650
-
651
-    /**
652
-     * @param $default_registration_status
653
-     * @throws EE_Error
654
-     */
655
-    public function set_default_registration_status($default_registration_status)
656
-    {
657
-        $this->set('EVT_default_registration_status', $default_registration_status);
658
-    }
659
-
660
-
661
-    /**
662
-     * @param $donations
663
-     * @throws EE_Error
664
-     */
665
-    public function set_donations($donations)
666
-    {
667
-        $this->set('EVT_donations', $donations);
668
-    }
669
-
670
-
671
-    /**
672
-     * Adds a venue to this event
673
-     *
674
-     * @param EE_Venue /int $venue_id_or_obj
675
-     * @return EE_Base_Class|EE_Venue
676
-     * @throws EE_Error
677
-     */
678
-    public function add_venue($venue_id_or_obj)
679
-    {
680
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
-    }
682
-
683
-
684
-    /**
685
-     * Removes a venue from the event
686
-     *
687
-     * @param EE_Venue /int $venue_id_or_obj
688
-     * @return EE_Base_Class|EE_Venue
689
-     * @throws EE_Error
690
-     */
691
-    public function remove_venue($venue_id_or_obj)
692
-    {
693
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
-    }
695
-
696
-
697
-    /**
698
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
699
-     *
700
-     * @param array $query_params like EEM_Base::get_all's $query_params
701
-     * @return EE_Base_Class[]|EE_Venue[]
702
-     * @throws EE_Error
703
-     */
704
-    public function venues($query_params = array())
705
-    {
706
-        return $this->get_many_related('Venue', $query_params);
707
-    }
708
-
709
-
710
-    /**
711
-     * check if event id is present and if event is published
712
-     *
713
-     * @access public
714
-     * @return boolean true yes, false no
715
-     * @throws EE_Error
716
-     */
717
-    private function _has_ID_and_is_published()
718
-    {
719
-        // first check if event id is present and not NULL,
720
-        // then check if this event is published (or any of the equivalent "published" statuses)
721
-        return
722
-            $this->ID() && $this->ID() !== null
723
-            && (
724
-                $this->status() === 'publish'
725
-                || $this->status() === EEM_Event::sold_out
726
-                || $this->status() === EEM_Event::postponed
727
-                || $this->status() === EEM_Event::cancelled
728
-            );
729
-    }
730
-
731
-
732
-    /**
733
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
-     *
735
-     * @access public
736
-     * @return boolean true yes, false no
737
-     * @throws EE_Error
738
-     */
739
-    public function is_upcoming()
740
-    {
741
-        // check if event id is present and if this event is published
742
-        if ($this->is_inactive()) {
743
-            return false;
744
-        }
745
-        // set initial value
746
-        $upcoming = false;
747
-        //next let's get all datetimes and loop through them
748
-        $datetimes = $this->datetimes_in_chronological_order();
749
-        foreach ($datetimes as $datetime) {
750
-            if ($datetime instanceof EE_Datetime) {
751
-                //if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
-                if ($datetime->is_expired()) {
753
-                    continue;
754
-                }
755
-                //if this dtt is active then we return false.
756
-                if ($datetime->is_active()) {
757
-                    return false;
758
-                }
759
-                //otherwise let's check upcoming status
760
-                $upcoming = $datetime->is_upcoming();
761
-            }
762
-        }
763
-        return $upcoming;
764
-    }
765
-
766
-
767
-    /**
768
-     * @return bool
769
-     * @throws EE_Error
770
-     */
771
-    public function is_active()
772
-    {
773
-        // check if event id is present and if this event is published
774
-        if ($this->is_inactive()) {
775
-            return false;
776
-        }
777
-        // set initial value
778
-        $active = false;
779
-        //next let's get all datetimes and loop through them
780
-        $datetimes = $this->datetimes_in_chronological_order();
781
-        foreach ($datetimes as $datetime) {
782
-            if ($datetime instanceof EE_Datetime) {
783
-                //if this dtt is expired then we continue cause one of the other datetimes might be active.
784
-                if ($datetime->is_expired()) {
785
-                    continue;
786
-                }
787
-                //if this dtt is upcoming then we return false.
788
-                if ($datetime->is_upcoming()) {
789
-                    return false;
790
-                }
791
-                //otherwise let's check active status
792
-                $active = $datetime->is_active();
793
-            }
794
-        }
795
-        return $active;
796
-    }
797
-
798
-
799
-    /**
800
-     * @return bool
801
-     * @throws EE_Error
802
-     */
803
-    public function is_expired()
804
-    {
805
-        // check if event id is present and if this event is published
806
-        if ($this->is_inactive()) {
807
-            return false;
808
-        }
809
-        // set initial value
810
-        $expired = false;
811
-        //first let's get all datetimes and loop through them
812
-        $datetimes = $this->datetimes_in_chronological_order();
813
-        foreach ($datetimes as $datetime) {
814
-            if ($datetime instanceof EE_Datetime) {
815
-                //if this dtt is upcoming or active then we return false.
816
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
817
-                    return false;
818
-                }
819
-                //otherwise let's check active status
820
-                $expired = $datetime->is_expired();
821
-            }
822
-        }
823
-        return $expired;
824
-    }
825
-
826
-
827
-    /**
828
-     * @return bool
829
-     * @throws EE_Error
830
-     */
831
-    public function is_inactive()
832
-    {
833
-        // check if event id is present and if this event is published
834
-        if ($this->_has_ID_and_is_published()) {
835
-            return false;
836
-        }
837
-        return true;
838
-    }
839
-
840
-
841
-    /**
842
-     * calculate spaces remaining based on "saleable" tickets
843
-     *
844
-     * @param array $tickets
845
-     * @param bool $filtered
846
-     * @return int|float
847
-     * @throws EE_Error
848
-     * @throws DomainException
849
-     * @throws UnexpectedEntityException
850
-     */
851
-    public function spaces_remaining($tickets = array(), $filtered = true)
852
-    {
853
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
-        return $filtered
856
-            ? apply_filters(
857
-                'FHEE_EE_Event__spaces_remaining',
858
-                $spaces_remaining,
859
-                $this,
860
-                $tickets
861
-            )
862
-            : $spaces_remaining;
863
-    }
864
-
865
-
866
-    /**
867
-     *    perform_sold_out_status_check
868
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
-     *    if NOT, then the event status will get toggled to 'sold_out'
870
-     *
871
-     * @return bool    return the ACTUAL sold out state.
872
-     * @throws EE_Error
873
-     * @throws DomainException
874
-     * @throws UnexpectedEntityException
875
-     */
876
-    public function perform_sold_out_status_check()
877
-    {
878
-        // get all unexpired untrashed tickets
879
-        $tickets = $this->active_tickets();
880
-        // if all the tickets are just expired, then don't update the event status to sold out
881
-        if (empty($tickets)) {
882
-            return true;
883
-        }
884
-        $spaces_remaining = $this->spaces_remaining($tickets);
885
-        if ($spaces_remaining < 1) {
886
-            $this->set_status(EEM_Event::sold_out);
887
-            $this->save();
888
-            $sold_out = true;
889
-        } else {
890
-            $sold_out = false;
891
-            // was event previously marked as sold out ?
892
-            if ($this->status() === EEM_Event::sold_out) {
893
-                // revert status to previous value, if it was set
894
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
-                if ($previous_event_status) {
896
-                    $this->set_status($previous_event_status);
897
-                    $this->save();
898
-                }
899
-            }
900
-        }
901
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
-        return $sold_out;
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * This returns the total remaining spaces for sale on this event.
909
-     *
910
-     * @uses EE_Event::total_available_spaces()
911
-     * @return float|int
912
-     * @throws EE_Error
913
-     * @throws DomainException
914
-     * @throws UnexpectedEntityException
915
-     */
916
-    public function spaces_remaining_for_sale()
917
-    {
918
-        return $this->total_available_spaces(true);
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * This returns the total spaces available for an event
925
-     * while considering all the qtys on the tickets and the reg limits
926
-     * on the datetimes attached to this event.
927
-     *
928
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
-     *                              If this is false, then we return the most tickets that could ever be sold
930
-     *                              for this event with the datetime and tickets setup on the event under optimal
931
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
933
-     *                              may appear to equal remaining tickets.  However, the more tickets are
934
-     *                              sold out, the more accurate the "live" total is.
935
-     * @return float|int
936
-     * @throws EE_Error
937
-     * @throws DomainException
938
-     * @throws UnexpectedEntityException
939
-     */
940
-    public function total_available_spaces($consider_sold = false)
941
-    {
942
-        $spaces_available = $consider_sold
943
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
-        return apply_filters(
946
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
947
-            $spaces_available,
948
-            $this,
949
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
950
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
951
-        );
952
-    }
953
-
954
-
955
-    /**
956
-     * Checks if the event is set to sold out
957
-     *
958
-     * @param  bool $actual whether or not to perform calculations to not only figure the
959
-     *                      actual status but also to flip the status if necessary to sold
960
-     *                      out If false, we just check the existing status of the event
961
-     * @return boolean
962
-     * @throws EE_Error
963
-     */
964
-    public function is_sold_out($actual = false)
965
-    {
966
-        if (!$actual) {
967
-            return $this->status() === EEM_Event::sold_out;
968
-        }
969
-        return $this->perform_sold_out_status_check();
970
-    }
971
-
972
-
973
-    /**
974
-     * Checks if the event is marked as postponed
975
-     *
976
-     * @return boolean
977
-     */
978
-    public function is_postponed()
979
-    {
980
-        return $this->status() === EEM_Event::postponed;
981
-    }
982
-
983
-
984
-    /**
985
-     * Checks if the event is marked as cancelled
986
-     *
987
-     * @return boolean
988
-     */
989
-    public function is_cancelled()
990
-    {
991
-        return $this->status() === EEM_Event::cancelled;
992
-    }
993
-
994
-
995
-    /**
996
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
-     * the event is considered expired.
1001
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
-     * set on the EVENT when it is not published and thus is done
1003
-     *
1004
-     * @param bool $reset
1005
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
-     * @throws EE_Error
1007
-     */
1008
-    public function get_active_status($reset = false)
1009
-    {
1010
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1012
-            return $this->_active_status;
1013
-        }
1014
-        //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1016
-            return false;
1017
-        }
1018
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
-        //if event is published:
1020
-        if ($this->status() === 'publish') {
1021
-            //active?
1022
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
-                $this->_active_status = EE_Datetime::active;
1024
-            } else {
1025
-                //upcoming?
1026
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
-                    $this->_active_status = EE_Datetime::upcoming;
1028
-                } else {
1029
-                    //expired?
1030
-                    if (
1031
-                        EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
-                    ) {
1033
-                        $this->_active_status = EE_Datetime::expired;
1034
-                    } else {
1035
-                        //it would be odd if things make it this far because it basically means there are no datetime's
1036
-                        //attached to the event.  So in this case it will just be considered inactive.
1037
-                        $this->_active_status = EE_Datetime::inactive;
1038
-                    }
1039
-                }
1040
-            }
1041
-        } else {
1042
-            //the event is not published, so let's just set it's active status according to its' post status
1043
-            switch ($this->status()) {
1044
-                case EEM_Event::sold_out :
1045
-                    $this->_active_status = EE_Datetime::sold_out;
1046
-                    break;
1047
-                case EEM_Event::cancelled :
1048
-                    $this->_active_status = EE_Datetime::cancelled;
1049
-                    break;
1050
-                case EEM_Event::postponed :
1051
-                    $this->_active_status = EE_Datetime::postponed;
1052
-                    break;
1053
-                default :
1054
-                    $this->_active_status = EE_Datetime::inactive;
1055
-            }
1056
-        }
1057
-        return $this->_active_status;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     *    pretty_active_status
1063
-     *
1064
-     * @access public
1065
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
-     * @return mixed void|string
1067
-     * @throws EE_Error
1068
-     */
1069
-    public function pretty_active_status($echo = true)
1070
-    {
1071
-        $active_status = $this->get_active_status();
1072
-        $status = '<span class="ee-status event-active-status-'
1073
-            . $active_status
1074
-            . '">'
1075
-            . EEH_Template::pretty_status($active_status, false, 'sentence')
1076
-            . '</span>';
1077
-        if ($echo) {
1078
-            echo $status;
1079
-            return '';
1080
-        }
1081
-        return $status;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * @return bool|int
1087
-     * @throws EE_Error
1088
-     */
1089
-    public function get_number_of_tickets_sold()
1090
-    {
1091
-        $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1093
-            return 0;
1094
-        }
1095
-        $datetimes = $this->datetimes();
1096
-        foreach ($datetimes as $datetime) {
1097
-            if ($datetime instanceof EE_Datetime) {
1098
-                $tkt_sold += $datetime->sold();
1099
-            }
1100
-        }
1101
-        return $tkt_sold;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * This just returns a count of all the registrations for this event
1107
-     *
1108
-     * @access  public
1109
-     * @return int
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function get_count_of_all_registrations()
1113
-    {
1114
-        return EEM_Event::instance()->count_related($this, 'Registration');
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * This returns the ticket with the earliest start time that is
1120
-     * available for this event (across all datetimes attached to the event)
1121
-     *
1122
-     * @return EE_Base_Class|EE_Ticket|null
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_ticket_with_earliest_start_time()
1126
-    {
1127
-        $where['Datetime.EVT_ID'] = $this->ID();
1128
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * This returns the ticket with the latest end time that is available
1135
-     * for this event (across all datetimes attached to the event)
1136
-     *
1137
-     * @return EE_Base_Class|EE_Ticket|null
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function get_ticket_with_latest_end_time()
1141
-    {
1142
-        $where['Datetime.EVT_ID'] = $this->ID();
1143
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This returns whether there are any tickets on sale for this event.
1150
-     *
1151
-     * @return bool true = YES tickets on sale.
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function tickets_on_sale()
1155
-    {
1156
-        $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
-        $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
-            return false;
1160
-        }
1161
-        //check on sale for these two tickets.
1162
-        if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
-            return true;
1164
-        }
1165
-        return false;
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1171
-     * to check for an external URL first
1172
-     *
1173
-     * @return string
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_permalink()
1177
-    {
1178
-        if ($this->external_url()) {
1179
-            return $this->external_url();
1180
-        }
1181
-        return parent::get_permalink();
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     * Gets the first term for 'espresso_event_categories' we can find
1187
-     *
1188
-     * @param array $query_params like EEM_Base::get_all
1189
-     * @return EE_Base_Class|EE_Term|null
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function first_event_category($query_params = array())
1193
-    {
1194
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
-        return EEM_Term::instance()->get_one($query_params);
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Gets all terms for 'espresso_event_categories' we can find
1202
-     *
1203
-     * @param array $query_params
1204
-     * @return EE_Base_Class[]|EE_Term[]
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function get_all_event_categories($query_params = array())
1208
-    {
1209
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
-        return EEM_Term::instance()->get_all($query_params);
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Gets all the question groups, ordering them by QSG_order ascending
1217
-     *
1218
-     * @param array $query_params @see EEM_Base::get_all
1219
-     * @return EE_Base_Class[]|EE_Question_Group[]
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function question_groups($query_params = array())
1223
-    {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
-        return $this->get_many_related('Question_Group', $query_params);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Implementation for EEI_Has_Icon interface method.
1231
-     *
1232
-     * @see EEI_Visual_Representation for comments
1233
-     * @return string
1234
-     */
1235
-    public function get_icon()
1236
-    {
1237
-        return '<span class="dashicons dashicons-flag"></span>';
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * Implementation for EEI_Admin_Links interface method.
1243
-     *
1244
-     * @see EEI_Admin_Links for comments
1245
-     * @return string
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function get_admin_details_link()
1249
-    {
1250
-        return $this->get_admin_edit_link();
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * Implementation for EEI_Admin_Links interface method.
1256
-     *
1257
-     * @see EEI_Admin_Links for comments
1258
-     * @return string
1259
-     * @throws EE_Error
1260
-     */
1261
-    public function get_admin_edit_link()
1262
-    {
1263
-        return EEH_URL::add_query_args_and_nonce(array(
1264
-            'page' => 'espresso_events',
1265
-            'action' => 'edit',
1266
-            'post' => $this->ID(),
1267
-        ),
1268
-            admin_url('admin.php')
1269
-        );
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Implementation for EEI_Admin_Links interface method.
1275
-     *
1276
-     * @see EEI_Admin_Links for comments
1277
-     * @return string
1278
-     */
1279
-    public function get_admin_settings_link()
1280
-    {
1281
-        return EEH_URL::add_query_args_and_nonce(array(
1282
-            'page' => 'espresso_events',
1283
-            'action' => 'default_event_settings',
1284
-        ),
1285
-            admin_url('admin.php')
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * Implementation for EEI_Admin_Links interface method.
1292
-     *
1293
-     * @see EEI_Admin_Links for comments
1294
-     * @return string
1295
-     */
1296
-    public function get_admin_overview_link()
1297
-    {
1298
-        return EEH_URL::add_query_args_and_nonce(array(
1299
-            'page' => 'espresso_events',
1300
-            'action' => 'default',
1301
-        ),
1302
-            admin_url('admin.php')
1303
-        );
1304
-    }
21
+	/**
22
+	 * cached value for the the logical active status for the event
23
+	 *
24
+	 * @see get_active_status()
25
+	 * @var string
26
+	 */
27
+	protected $_active_status = '';
28
+
29
+	/**
30
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
+	 *
32
+	 * @var EE_Datetime
33
+	 */
34
+	protected $_Primary_Datetime;
35
+
36
+	/**
37
+	 * @var EventSpacesCalculator $available_spaces_calculator
38
+	 */
39
+	protected $available_spaces_calculator;
40
+
41
+
42
+	/**
43
+	 * @param array $props_n_values incoming values
44
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
+	 *                                        used.)
46
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
47
+	 *                                        date_format and the second value is the time format
48
+	 * @return EE_Event
49
+	 * @throws EE_Error
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values incoming values from the database
60
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Event
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return EventSpacesCalculator
74
+	 * @throws \EE_Error
75
+	 */
76
+	public function getAvailableSpacesCalculator()
77
+	{
78
+		if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
+	 *
89
+	 * @param string $field_name
90
+	 * @param mixed $field_value
91
+	 * @param bool $use_default
92
+	 * @throws EE_Error
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status' :
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default :
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @access public
113
+	 * @param string $new_status
114
+	 * @param bool $use_default
115
+	 * @return void
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_status($new_status = null, $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($new_status) && !$use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $new_status) {
128
+			// TO sold_out
129
+			if ($new_status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
+				// OR FROM  sold_out
134
+			} else if ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
+			}
138
+			// update status
139
+			parent::set('status', $new_status, $use_default);
140
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
141
+			return;
142
+		}
143
+		// even though the old value matches the new value, it's still good to
144
+		// allow the parent set method to have a say
145
+		parent::set('status', $new_status, $use_default);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets all the datetimes for this event
151
+	 *
152
+	 * @param array $query_params like EEM_Base::get_all
153
+	 * @return EE_Base_Class[]|EE_Datetime[]
154
+	 * @throws EE_Error
155
+	 */
156
+	public function datetimes($query_params = array())
157
+	{
158
+		return $this->get_many_related('Datetime', $query_params);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
+	 *
165
+	 * @return EE_Base_Class[]|EE_Datetime[]
166
+	 * @throws EE_Error
167
+	 */
168
+	public function datetimes_in_chronological_order()
169
+	{
170
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
+	}
172
+
173
+
174
+	/**
175
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
+	 * after running our query, so that this timezone isn't set for EVERY query
178
+	 * on EEM_Datetime for the rest of the request, no?
179
+	 *
180
+	 * @param boolean $show_expired whether or not to include expired events
181
+	 * @param boolean $show_deleted whether or not to include deleted events
182
+	 * @param null $limit
183
+	 * @return EE_Datetime[]
184
+	 * @throws EE_Error
185
+	 */
186
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
+	{
188
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
+			$this->ID(),
190
+			$show_expired,
191
+			$show_deleted,
192
+			$limit
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Returns one related datetime. Mostly only used by some legacy code.
199
+	 *
200
+	 * @return EE_Base_Class|EE_Datetime
201
+	 * @throws EE_Error
202
+	 */
203
+	public function first_datetime()
204
+	{
205
+		return $this->get_first_related('Datetime');
206
+	}
207
+
208
+
209
+	/**
210
+	 * Returns the 'primary' datetime for the event
211
+	 *
212
+	 * @param bool $try_to_exclude_expired
213
+	 * @param bool $try_to_exclude_deleted
214
+	 * @return EE_Datetime
215
+	 * @throws EE_Error
216
+	 */
217
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
+	{
219
+		if (!empty ($this->_Primary_Datetime)) {
220
+			return $this->_Primary_Datetime;
221
+		}
222
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
+			$this->ID(),
224
+			$try_to_exclude_expired,
225
+			$try_to_exclude_deleted
226
+		);
227
+		return $this->_Primary_Datetime;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets all the tickets available for purchase of this event
233
+	 *
234
+	 * @param array $query_params like EEM_Base::get_all
235
+	 * @return EE_Base_Class[]|EE_Ticket[]
236
+	 * @throws EE_Error
237
+	 */
238
+	public function tickets($query_params = array())
239
+	{
240
+		//first get all datetimes
241
+		$datetimes = $this->datetimes_ordered();
242
+		if (!$datetimes) {
243
+			return array();
244
+		}
245
+		$datetime_ids = array();
246
+		foreach ($datetimes as $datetime) {
247
+			$datetime_ids[] = $datetime->ID();
248
+		}
249
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
+		//if incoming $query_params has where conditions let's merge but not override existing.
251
+		if (is_array($query_params) && isset($query_params[0])) {
252
+			$where_params = array_merge($query_params[0], $where_params);
253
+			unset($query_params[0]);
254
+		}
255
+		//now add $where_params to $query_params
256
+		$query_params[0] = $where_params;
257
+		return EEM_Ticket::instance()->get_all($query_params);
258
+	}
259
+
260
+
261
+	/**
262
+	 * get all unexpired untrashed tickets
263
+	 *
264
+	 * @return EE_Ticket[]
265
+	 * @throws EE_Error
266
+	 */
267
+	public function active_tickets()
268
+	{
269
+		return $this->tickets(array(
270
+			array(
271
+				'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
+				'TKT_deleted' => false,
273
+			),
274
+		));
275
+	}
276
+
277
+
278
+	/**
279
+	 * @return bool
280
+	 * @throws EE_Error
281
+	 */
282
+	public function additional_limit()
283
+	{
284
+		return $this->get('EVT_additional_limit');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return bool
290
+	 * @throws EE_Error
291
+	 */
292
+	public function allow_overflow()
293
+	{
294
+		return $this->get('EVT_allow_overflow');
295
+	}
296
+
297
+
298
+	/**
299
+	 * @return bool
300
+	 * @throws EE_Error
301
+	 */
302
+	public function created()
303
+	{
304
+		return $this->get('EVT_created');
305
+	}
306
+
307
+
308
+	/**
309
+	 * @return bool
310
+	 * @throws EE_Error
311
+	 */
312
+	public function description()
313
+	{
314
+		return $this->get('EVT_desc');
315
+	}
316
+
317
+
318
+	/**
319
+	 * Runs do_shortcode and wpautop on the description
320
+	 *
321
+	 * @return string of html
322
+	 * @throws EE_Error
323
+	 */
324
+	public function description_filtered()
325
+	{
326
+		return $this->get_pretty('EVT_desc');
327
+	}
328
+
329
+
330
+	/**
331
+	 * @return bool
332
+	 * @throws EE_Error
333
+	 */
334
+	public function display_description()
335
+	{
336
+		return $this->get('EVT_display_desc');
337
+	}
338
+
339
+
340
+	/**
341
+	 * @return bool
342
+	 * @throws EE_Error
343
+	 */
344
+	public function display_ticket_selector()
345
+	{
346
+		return (bool)$this->get('EVT_display_ticket_selector');
347
+	}
348
+
349
+
350
+	/**
351
+	 * @return bool
352
+	 * @throws EE_Error
353
+	 */
354
+	public function external_url()
355
+	{
356
+		return $this->get('EVT_external_URL');
357
+	}
358
+
359
+
360
+	/**
361
+	 * @return bool
362
+	 * @throws EE_Error
363
+	 */
364
+	public function member_only()
365
+	{
366
+		return $this->get('EVT_member_only');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return bool
372
+	 * @throws EE_Error
373
+	 */
374
+	public function phone()
375
+	{
376
+		return $this->get('EVT_phone');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 */
384
+	public function modified()
385
+	{
386
+		return $this->get('EVT_modified');
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return bool
392
+	 * @throws EE_Error
393
+	 */
394
+	public function name()
395
+	{
396
+		return $this->get('EVT_name');
397
+	}
398
+
399
+
400
+	/**
401
+	 * @return bool
402
+	 * @throws EE_Error
403
+	 */
404
+	public function order()
405
+	{
406
+		return $this->get('EVT_order');
407
+	}
408
+
409
+
410
+	/**
411
+	 * @return bool|string
412
+	 * @throws EE_Error
413
+	 */
414
+	public function default_registration_status()
415
+	{
416
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
417
+		return !empty($event_default_registration_status)
418
+			? $event_default_registration_status
419
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
420
+	}
421
+
422
+
423
+	/**
424
+	 * @param int $num_words
425
+	 * @param null $more
426
+	 * @param bool $not_full_desc
427
+	 * @return bool|string
428
+	 * @throws EE_Error
429
+	 */
430
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
+	{
432
+		$short_desc = $this->get('EVT_short_desc');
433
+		if (!empty($short_desc) || $not_full_desc) {
434
+			return $short_desc;
435
+		}
436
+		$full_desc = $this->get('EVT_desc');
437
+		return wp_trim_words($full_desc, $num_words, $more);
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return bool
443
+	 * @throws EE_Error
444
+	 */
445
+	public function slug()
446
+	{
447
+		return $this->get('EVT_slug');
448
+	}
449
+
450
+
451
+	/**
452
+	 * @return bool
453
+	 * @throws EE_Error
454
+	 */
455
+	public function timezone_string()
456
+	{
457
+		return $this->get('EVT_timezone_string');
458
+	}
459
+
460
+
461
+	/**
462
+	 * @return bool
463
+	 * @throws EE_Error
464
+	 */
465
+	public function visible_on()
466
+	{
467
+		return $this->get('EVT_visible_on');
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return int
473
+	 * @throws EE_Error
474
+	 */
475
+	public function wp_user()
476
+	{
477
+		return $this->get('EVT_wp_user');
478
+	}
479
+
480
+
481
+	/**
482
+	 * @return bool
483
+	 * @throws EE_Error
484
+	 */
485
+	public function donations()
486
+	{
487
+		return $this->get('EVT_donations');
488
+	}
489
+
490
+
491
+	/**
492
+	 * @param $limit
493
+	 * @throws EE_Error
494
+	 */
495
+	public function set_additional_limit($limit)
496
+	{
497
+		$this->set('EVT_additional_limit', $limit);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @param $created
503
+	 * @throws EE_Error
504
+	 */
505
+	public function set_created($created)
506
+	{
507
+		$this->set('EVT_created', $created);
508
+	}
509
+
510
+
511
+	/**
512
+	 * @param $desc
513
+	 * @throws EE_Error
514
+	 */
515
+	public function set_description($desc)
516
+	{
517
+		$this->set('EVT_desc', $desc);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param $display_desc
523
+	 * @throws EE_Error
524
+	 */
525
+	public function set_display_description($display_desc)
526
+	{
527
+		$this->set('EVT_display_desc', $display_desc);
528
+	}
529
+
530
+
531
+	/**
532
+	 * @param $display_ticket_selector
533
+	 * @throws EE_Error
534
+	 */
535
+	public function set_display_ticket_selector($display_ticket_selector)
536
+	{
537
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
+	}
539
+
540
+
541
+	/**
542
+	 * @param $external_url
543
+	 * @throws EE_Error
544
+	 */
545
+	public function set_external_url($external_url)
546
+	{
547
+		$this->set('EVT_external_URL', $external_url);
548
+	}
549
+
550
+
551
+	/**
552
+	 * @param $member_only
553
+	 * @throws EE_Error
554
+	 */
555
+	public function set_member_only($member_only)
556
+	{
557
+		$this->set('EVT_member_only', $member_only);
558
+	}
559
+
560
+
561
+	/**
562
+	 * @param $event_phone
563
+	 * @throws EE_Error
564
+	 */
565
+	public function set_event_phone($event_phone)
566
+	{
567
+		$this->set('EVT_phone', $event_phone);
568
+	}
569
+
570
+
571
+	/**
572
+	 * @param $modified
573
+	 * @throws EE_Error
574
+	 */
575
+	public function set_modified($modified)
576
+	{
577
+		$this->set('EVT_modified', $modified);
578
+	}
579
+
580
+
581
+	/**
582
+	 * @param $name
583
+	 * @throws EE_Error
584
+	 */
585
+	public function set_name($name)
586
+	{
587
+		$this->set('EVT_name', $name);
588
+	}
589
+
590
+
591
+	/**
592
+	 * @param $order
593
+	 * @throws EE_Error
594
+	 */
595
+	public function set_order($order)
596
+	{
597
+		$this->set('EVT_order', $order);
598
+	}
599
+
600
+
601
+	/**
602
+	 * @param $short_desc
603
+	 * @throws EE_Error
604
+	 */
605
+	public function set_short_description($short_desc)
606
+	{
607
+		$this->set('EVT_short_desc', $short_desc);
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $slug
613
+	 * @throws EE_Error
614
+	 */
615
+	public function set_slug($slug)
616
+	{
617
+		$this->set('EVT_slug', $slug);
618
+	}
619
+
620
+
621
+	/**
622
+	 * @param $timezone_string
623
+	 * @throws EE_Error
624
+	 */
625
+	public function set_timezone_string($timezone_string)
626
+	{
627
+		$this->set('EVT_timezone_string', $timezone_string);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $visible_on
633
+	 * @throws EE_Error
634
+	 */
635
+	public function set_visible_on($visible_on)
636
+	{
637
+		$this->set('EVT_visible_on', $visible_on);
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param $wp_user
643
+	 * @throws EE_Error
644
+	 */
645
+	public function set_wp_user($wp_user)
646
+	{
647
+		$this->set('EVT_wp_user', $wp_user);
648
+	}
649
+
650
+
651
+	/**
652
+	 * @param $default_registration_status
653
+	 * @throws EE_Error
654
+	 */
655
+	public function set_default_registration_status($default_registration_status)
656
+	{
657
+		$this->set('EVT_default_registration_status', $default_registration_status);
658
+	}
659
+
660
+
661
+	/**
662
+	 * @param $donations
663
+	 * @throws EE_Error
664
+	 */
665
+	public function set_donations($donations)
666
+	{
667
+		$this->set('EVT_donations', $donations);
668
+	}
669
+
670
+
671
+	/**
672
+	 * Adds a venue to this event
673
+	 *
674
+	 * @param EE_Venue /int $venue_id_or_obj
675
+	 * @return EE_Base_Class|EE_Venue
676
+	 * @throws EE_Error
677
+	 */
678
+	public function add_venue($venue_id_or_obj)
679
+	{
680
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
+	}
682
+
683
+
684
+	/**
685
+	 * Removes a venue from the event
686
+	 *
687
+	 * @param EE_Venue /int $venue_id_or_obj
688
+	 * @return EE_Base_Class|EE_Venue
689
+	 * @throws EE_Error
690
+	 */
691
+	public function remove_venue($venue_id_or_obj)
692
+	{
693
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
+	}
695
+
696
+
697
+	/**
698
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
699
+	 *
700
+	 * @param array $query_params like EEM_Base::get_all's $query_params
701
+	 * @return EE_Base_Class[]|EE_Venue[]
702
+	 * @throws EE_Error
703
+	 */
704
+	public function venues($query_params = array())
705
+	{
706
+		return $this->get_many_related('Venue', $query_params);
707
+	}
708
+
709
+
710
+	/**
711
+	 * check if event id is present and if event is published
712
+	 *
713
+	 * @access public
714
+	 * @return boolean true yes, false no
715
+	 * @throws EE_Error
716
+	 */
717
+	private function _has_ID_and_is_published()
718
+	{
719
+		// first check if event id is present and not NULL,
720
+		// then check if this event is published (or any of the equivalent "published" statuses)
721
+		return
722
+			$this->ID() && $this->ID() !== null
723
+			&& (
724
+				$this->status() === 'publish'
725
+				|| $this->status() === EEM_Event::sold_out
726
+				|| $this->status() === EEM_Event::postponed
727
+				|| $this->status() === EEM_Event::cancelled
728
+			);
729
+	}
730
+
731
+
732
+	/**
733
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
+	 *
735
+	 * @access public
736
+	 * @return boolean true yes, false no
737
+	 * @throws EE_Error
738
+	 */
739
+	public function is_upcoming()
740
+	{
741
+		// check if event id is present and if this event is published
742
+		if ($this->is_inactive()) {
743
+			return false;
744
+		}
745
+		// set initial value
746
+		$upcoming = false;
747
+		//next let's get all datetimes and loop through them
748
+		$datetimes = $this->datetimes_in_chronological_order();
749
+		foreach ($datetimes as $datetime) {
750
+			if ($datetime instanceof EE_Datetime) {
751
+				//if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
+				if ($datetime->is_expired()) {
753
+					continue;
754
+				}
755
+				//if this dtt is active then we return false.
756
+				if ($datetime->is_active()) {
757
+					return false;
758
+				}
759
+				//otherwise let's check upcoming status
760
+				$upcoming = $datetime->is_upcoming();
761
+			}
762
+		}
763
+		return $upcoming;
764
+	}
765
+
766
+
767
+	/**
768
+	 * @return bool
769
+	 * @throws EE_Error
770
+	 */
771
+	public function is_active()
772
+	{
773
+		// check if event id is present and if this event is published
774
+		if ($this->is_inactive()) {
775
+			return false;
776
+		}
777
+		// set initial value
778
+		$active = false;
779
+		//next let's get all datetimes and loop through them
780
+		$datetimes = $this->datetimes_in_chronological_order();
781
+		foreach ($datetimes as $datetime) {
782
+			if ($datetime instanceof EE_Datetime) {
783
+				//if this dtt is expired then we continue cause one of the other datetimes might be active.
784
+				if ($datetime->is_expired()) {
785
+					continue;
786
+				}
787
+				//if this dtt is upcoming then we return false.
788
+				if ($datetime->is_upcoming()) {
789
+					return false;
790
+				}
791
+				//otherwise let's check active status
792
+				$active = $datetime->is_active();
793
+			}
794
+		}
795
+		return $active;
796
+	}
797
+
798
+
799
+	/**
800
+	 * @return bool
801
+	 * @throws EE_Error
802
+	 */
803
+	public function is_expired()
804
+	{
805
+		// check if event id is present and if this event is published
806
+		if ($this->is_inactive()) {
807
+			return false;
808
+		}
809
+		// set initial value
810
+		$expired = false;
811
+		//first let's get all datetimes and loop through them
812
+		$datetimes = $this->datetimes_in_chronological_order();
813
+		foreach ($datetimes as $datetime) {
814
+			if ($datetime instanceof EE_Datetime) {
815
+				//if this dtt is upcoming or active then we return false.
816
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
817
+					return false;
818
+				}
819
+				//otherwise let's check active status
820
+				$expired = $datetime->is_expired();
821
+			}
822
+		}
823
+		return $expired;
824
+	}
825
+
826
+
827
+	/**
828
+	 * @return bool
829
+	 * @throws EE_Error
830
+	 */
831
+	public function is_inactive()
832
+	{
833
+		// check if event id is present and if this event is published
834
+		if ($this->_has_ID_and_is_published()) {
835
+			return false;
836
+		}
837
+		return true;
838
+	}
839
+
840
+
841
+	/**
842
+	 * calculate spaces remaining based on "saleable" tickets
843
+	 *
844
+	 * @param array $tickets
845
+	 * @param bool $filtered
846
+	 * @return int|float
847
+	 * @throws EE_Error
848
+	 * @throws DomainException
849
+	 * @throws UnexpectedEntityException
850
+	 */
851
+	public function spaces_remaining($tickets = array(), $filtered = true)
852
+	{
853
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
+		return $filtered
856
+			? apply_filters(
857
+				'FHEE_EE_Event__spaces_remaining',
858
+				$spaces_remaining,
859
+				$this,
860
+				$tickets
861
+			)
862
+			: $spaces_remaining;
863
+	}
864
+
865
+
866
+	/**
867
+	 *    perform_sold_out_status_check
868
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
+	 *    if NOT, then the event status will get toggled to 'sold_out'
870
+	 *
871
+	 * @return bool    return the ACTUAL sold out state.
872
+	 * @throws EE_Error
873
+	 * @throws DomainException
874
+	 * @throws UnexpectedEntityException
875
+	 */
876
+	public function perform_sold_out_status_check()
877
+	{
878
+		// get all unexpired untrashed tickets
879
+		$tickets = $this->active_tickets();
880
+		// if all the tickets are just expired, then don't update the event status to sold out
881
+		if (empty($tickets)) {
882
+			return true;
883
+		}
884
+		$spaces_remaining = $this->spaces_remaining($tickets);
885
+		if ($spaces_remaining < 1) {
886
+			$this->set_status(EEM_Event::sold_out);
887
+			$this->save();
888
+			$sold_out = true;
889
+		} else {
890
+			$sold_out = false;
891
+			// was event previously marked as sold out ?
892
+			if ($this->status() === EEM_Event::sold_out) {
893
+				// revert status to previous value, if it was set
894
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
+				if ($previous_event_status) {
896
+					$this->set_status($previous_event_status);
897
+					$this->save();
898
+				}
899
+			}
900
+		}
901
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
+		return $sold_out;
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * This returns the total remaining spaces for sale on this event.
909
+	 *
910
+	 * @uses EE_Event::total_available_spaces()
911
+	 * @return float|int
912
+	 * @throws EE_Error
913
+	 * @throws DomainException
914
+	 * @throws UnexpectedEntityException
915
+	 */
916
+	public function spaces_remaining_for_sale()
917
+	{
918
+		return $this->total_available_spaces(true);
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * This returns the total spaces available for an event
925
+	 * while considering all the qtys on the tickets and the reg limits
926
+	 * on the datetimes attached to this event.
927
+	 *
928
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
+	 *                              If this is false, then we return the most tickets that could ever be sold
930
+	 *                              for this event with the datetime and tickets setup on the event under optimal
931
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
933
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
934
+	 *                              sold out, the more accurate the "live" total is.
935
+	 * @return float|int
936
+	 * @throws EE_Error
937
+	 * @throws DomainException
938
+	 * @throws UnexpectedEntityException
939
+	 */
940
+	public function total_available_spaces($consider_sold = false)
941
+	{
942
+		$spaces_available = $consider_sold
943
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
+		return apply_filters(
946
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
947
+			$spaces_available,
948
+			$this,
949
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
950
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
951
+		);
952
+	}
953
+
954
+
955
+	/**
956
+	 * Checks if the event is set to sold out
957
+	 *
958
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
959
+	 *                      actual status but also to flip the status if necessary to sold
960
+	 *                      out If false, we just check the existing status of the event
961
+	 * @return boolean
962
+	 * @throws EE_Error
963
+	 */
964
+	public function is_sold_out($actual = false)
965
+	{
966
+		if (!$actual) {
967
+			return $this->status() === EEM_Event::sold_out;
968
+		}
969
+		return $this->perform_sold_out_status_check();
970
+	}
971
+
972
+
973
+	/**
974
+	 * Checks if the event is marked as postponed
975
+	 *
976
+	 * @return boolean
977
+	 */
978
+	public function is_postponed()
979
+	{
980
+		return $this->status() === EEM_Event::postponed;
981
+	}
982
+
983
+
984
+	/**
985
+	 * Checks if the event is marked as cancelled
986
+	 *
987
+	 * @return boolean
988
+	 */
989
+	public function is_cancelled()
990
+	{
991
+		return $this->status() === EEM_Event::cancelled;
992
+	}
993
+
994
+
995
+	/**
996
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
+	 * the event is considered expired.
1001
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
+	 * set on the EVENT when it is not published and thus is done
1003
+	 *
1004
+	 * @param bool $reset
1005
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
+	 * @throws EE_Error
1007
+	 */
1008
+	public function get_active_status($reset = false)
1009
+	{
1010
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1011
+		if (!empty($this->_active_status) && !$reset) {
1012
+			return $this->_active_status;
1013
+		}
1014
+		//first check if event id is present on this object
1015
+		if (!$this->ID()) {
1016
+			return false;
1017
+		}
1018
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
+		//if event is published:
1020
+		if ($this->status() === 'publish') {
1021
+			//active?
1022
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
+				$this->_active_status = EE_Datetime::active;
1024
+			} else {
1025
+				//upcoming?
1026
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
+					$this->_active_status = EE_Datetime::upcoming;
1028
+				} else {
1029
+					//expired?
1030
+					if (
1031
+						EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
+					) {
1033
+						$this->_active_status = EE_Datetime::expired;
1034
+					} else {
1035
+						//it would be odd if things make it this far because it basically means there are no datetime's
1036
+						//attached to the event.  So in this case it will just be considered inactive.
1037
+						$this->_active_status = EE_Datetime::inactive;
1038
+					}
1039
+				}
1040
+			}
1041
+		} else {
1042
+			//the event is not published, so let's just set it's active status according to its' post status
1043
+			switch ($this->status()) {
1044
+				case EEM_Event::sold_out :
1045
+					$this->_active_status = EE_Datetime::sold_out;
1046
+					break;
1047
+				case EEM_Event::cancelled :
1048
+					$this->_active_status = EE_Datetime::cancelled;
1049
+					break;
1050
+				case EEM_Event::postponed :
1051
+					$this->_active_status = EE_Datetime::postponed;
1052
+					break;
1053
+				default :
1054
+					$this->_active_status = EE_Datetime::inactive;
1055
+			}
1056
+		}
1057
+		return $this->_active_status;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 *    pretty_active_status
1063
+	 *
1064
+	 * @access public
1065
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
+	 * @return mixed void|string
1067
+	 * @throws EE_Error
1068
+	 */
1069
+	public function pretty_active_status($echo = true)
1070
+	{
1071
+		$active_status = $this->get_active_status();
1072
+		$status = '<span class="ee-status event-active-status-'
1073
+			. $active_status
1074
+			. '">'
1075
+			. EEH_Template::pretty_status($active_status, false, 'sentence')
1076
+			. '</span>';
1077
+		if ($echo) {
1078
+			echo $status;
1079
+			return '';
1080
+		}
1081
+		return $status;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * @return bool|int
1087
+	 * @throws EE_Error
1088
+	 */
1089
+	public function get_number_of_tickets_sold()
1090
+	{
1091
+		$tkt_sold = 0;
1092
+		if (!$this->ID()) {
1093
+			return 0;
1094
+		}
1095
+		$datetimes = $this->datetimes();
1096
+		foreach ($datetimes as $datetime) {
1097
+			if ($datetime instanceof EE_Datetime) {
1098
+				$tkt_sold += $datetime->sold();
1099
+			}
1100
+		}
1101
+		return $tkt_sold;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * This just returns a count of all the registrations for this event
1107
+	 *
1108
+	 * @access  public
1109
+	 * @return int
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function get_count_of_all_registrations()
1113
+	{
1114
+		return EEM_Event::instance()->count_related($this, 'Registration');
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * This returns the ticket with the earliest start time that is
1120
+	 * available for this event (across all datetimes attached to the event)
1121
+	 *
1122
+	 * @return EE_Base_Class|EE_Ticket|null
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_ticket_with_earliest_start_time()
1126
+	{
1127
+		$where['Datetime.EVT_ID'] = $this->ID();
1128
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * This returns the ticket with the latest end time that is available
1135
+	 * for this event (across all datetimes attached to the event)
1136
+	 *
1137
+	 * @return EE_Base_Class|EE_Ticket|null
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function get_ticket_with_latest_end_time()
1141
+	{
1142
+		$where['Datetime.EVT_ID'] = $this->ID();
1143
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This returns whether there are any tickets on sale for this event.
1150
+	 *
1151
+	 * @return bool true = YES tickets on sale.
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function tickets_on_sale()
1155
+	{
1156
+		$earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
+		$latest_ticket = $this->get_ticket_with_latest_end_time();
1158
+		if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
+			return false;
1160
+		}
1161
+		//check on sale for these two tickets.
1162
+		if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
+			return true;
1164
+		}
1165
+		return false;
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1171
+	 * to check for an external URL first
1172
+	 *
1173
+	 * @return string
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_permalink()
1177
+	{
1178
+		if ($this->external_url()) {
1179
+			return $this->external_url();
1180
+		}
1181
+		return parent::get_permalink();
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 * Gets the first term for 'espresso_event_categories' we can find
1187
+	 *
1188
+	 * @param array $query_params like EEM_Base::get_all
1189
+	 * @return EE_Base_Class|EE_Term|null
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function first_event_category($query_params = array())
1193
+	{
1194
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
+		return EEM_Term::instance()->get_one($query_params);
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Gets all terms for 'espresso_event_categories' we can find
1202
+	 *
1203
+	 * @param array $query_params
1204
+	 * @return EE_Base_Class[]|EE_Term[]
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function get_all_event_categories($query_params = array())
1208
+	{
1209
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
+		return EEM_Term::instance()->get_all($query_params);
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Gets all the question groups, ordering them by QSG_order ascending
1217
+	 *
1218
+	 * @param array $query_params @see EEM_Base::get_all
1219
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function question_groups($query_params = array())
1223
+	{
1224
+		$query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
+		return $this->get_many_related('Question_Group', $query_params);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Implementation for EEI_Has_Icon interface method.
1231
+	 *
1232
+	 * @see EEI_Visual_Representation for comments
1233
+	 * @return string
1234
+	 */
1235
+	public function get_icon()
1236
+	{
1237
+		return '<span class="dashicons dashicons-flag"></span>';
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * Implementation for EEI_Admin_Links interface method.
1243
+	 *
1244
+	 * @see EEI_Admin_Links for comments
1245
+	 * @return string
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function get_admin_details_link()
1249
+	{
1250
+		return $this->get_admin_edit_link();
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * Implementation for EEI_Admin_Links interface method.
1256
+	 *
1257
+	 * @see EEI_Admin_Links for comments
1258
+	 * @return string
1259
+	 * @throws EE_Error
1260
+	 */
1261
+	public function get_admin_edit_link()
1262
+	{
1263
+		return EEH_URL::add_query_args_and_nonce(array(
1264
+			'page' => 'espresso_events',
1265
+			'action' => 'edit',
1266
+			'post' => $this->ID(),
1267
+		),
1268
+			admin_url('admin.php')
1269
+		);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Implementation for EEI_Admin_Links interface method.
1275
+	 *
1276
+	 * @see EEI_Admin_Links for comments
1277
+	 * @return string
1278
+	 */
1279
+	public function get_admin_settings_link()
1280
+	{
1281
+		return EEH_URL::add_query_args_and_nonce(array(
1282
+			'page' => 'espresso_events',
1283
+			'action' => 'default_event_settings',
1284
+		),
1285
+			admin_url('admin.php')
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * Implementation for EEI_Admin_Links interface method.
1292
+	 *
1293
+	 * @see EEI_Admin_Links for comments
1294
+	 * @return string
1295
+	 */
1296
+	public function get_admin_overview_link()
1297
+	{
1298
+		return EEH_URL::add_query_args_and_nonce(array(
1299
+			'page' => 'espresso_events',
1300
+			'action' => 'default',
1301
+		),
1302
+			admin_url('admin.php')
1303
+		);
1304
+	}
1305 1305
 
1306 1306
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\domain\services\event\EventSpacesCalculator;
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6
-if (!defined('EVENT_ESPRESSO_VERSION')) {
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7 7
     exit('No direct script access allowed');
8 8
 }
9 9
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function getAvailableSpacesCalculator()
77 77
     {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
78
+        if ( ! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79 79
             $this->available_spaces_calculator = new EventSpacesCalculator($this);
80 80
         }
81 81
         return $this->available_spaces_calculator;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function set_status($new_status = null, $use_default = false)
119 119
     {
120 120
         // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
121
+        if (empty($new_status) && ! $use_default) {
122 122
             return;
123 123
         }
124 124
         // get current Event status
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218 218
     {
219
-        if (!empty ($this->_Primary_Datetime)) {
219
+        if ( ! empty ($this->_Primary_Datetime)) {
220 220
             return $this->_Primary_Datetime;
221 221
         }
222 222
         $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
     {
240 240
         //first get all datetimes
241 241
         $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
242
+        if ( ! $datetimes) {
243 243
             return array();
244 244
         }
245 245
         $datetime_ids = array();
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function display_ticket_selector()
345 345
     {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
346
+        return (bool) $this->get('EVT_display_ticket_selector');
347 347
     }
348 348
 
349 349
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
     public function default_registration_status()
415 415
     {
416 416
         $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
417
+        return ! empty($event_default_registration_status)
418 418
             ? $event_default_registration_status
419 419
             : EE_Registry::instance()->CFG->registration->default_STS_ID;
420 420
     }
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431 431
     {
432 432
         $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
433
+        if ( ! empty($short_desc) || $not_full_desc) {
434 434
             return $short_desc;
435 435
         }
436 436
         $full_desc = $this->get('EVT_desc');
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
      */
964 964
     public function is_sold_out($actual = false)
965 965
     {
966
-        if (!$actual) {
966
+        if ( ! $actual) {
967 967
             return $this->status() === EEM_Event::sold_out;
968 968
         }
969 969
         return $this->perform_sold_out_status_check();
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
     public function get_active_status($reset = false)
1009 1009
     {
1010 1010
         // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1011
+        if ( ! empty($this->_active_status) && ! $reset) {
1012 1012
             return $this->_active_status;
1013 1013
         }
1014 1014
         //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1015
+        if ( ! $this->ID()) {
1016 1016
             return false;
1017 1017
         }
1018 1018
         $where_params_for_event = array(array('EVT_ID' => $this->ID()));
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
     public function get_number_of_tickets_sold()
1090 1090
     {
1091 1091
         $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1092
+        if ( ! $this->ID()) {
1093 1093
             return 0;
1094 1094
         }
1095 1095
         $datetimes = $this->datetimes();
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
     {
1156 1156
         $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157 1157
         $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1158
+        if ( ! $latest_ticket instanceof EE_Ticket && ! $earliest_ticket instanceof EE_Ticket) {
1159 1159
             return false;
1160 1160
         }
1161 1161
         //check on sale for these two tickets.
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
      */
1222 1222
     public function question_groups($query_params = array())
1223 1223
     {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1224
+        $query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225 1225
         return $this->get_many_related('Question_Group', $query_params);
1226 1226
     }
1227 1227
 
Please login to merge, or discard this patch.
core/EE_Deprecated.core.php 2 patches
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
 		);
1048 1048
 		do_action(
1049 1049
 			'AHEE__EE_Capabilities__init_role_caps__complete',
1050
-            $capabilities_map
1050
+			$capabilities_map
1051 1051
 		);
1052 1052
 	}
1053 1053
 );
@@ -1067,9 +1067,9 @@  discard block
 block discarded – undo
1067 1067
 			'filter'
1068 1068
 		);
1069 1069
 		return apply_filters(
1070
-            'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee',
1071
-            $existing_attendee, $registration, $attendee_data
1072
-        );
1070
+			'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee',
1071
+			$existing_attendee, $registration, $attendee_data
1072
+		);
1073 1073
 	},
1074 1074
 	10,3
1075 1075
 );
@@ -1082,88 +1082,88 @@  discard block
 block discarded – undo
1082 1082
 class EE_Event_List_Query extends WP_Query
1083 1083
 {
1084 1084
 
1085
-    private $title;
1086
-
1087
-    private $css_class;
1088
-
1089
-    private $category_slug;
1090
-
1091
-    /**
1092
-     * EE_Event_List_Query constructor.
1093
-     *
1094
-     * @param array $args
1095
-     */
1096
-    public function __construct($args = array())
1097
-    {
1098
-        \EE_Error::doing_it_wrong(
1099
-            __METHOD__,
1100
-            __(
1101
-                'Usage is deprecated. Please use \EventEspresso\core\domain\services\wp_queries\EventListQuery instead.',
1102
-                'event_espresso'
1103
-            ),
1104
-            '4.9.27',
1105
-            '5.0.0'
1106
-        );
1107
-        $this->title = isset($args['title']) ? $args['title'] : '';
1108
-        $this->css_class = isset($args['css_class']) ? $args['css_class'] : '';
1109
-        $this->category_slug = isset($args['category_slug']) ? $args['category_slug'] : '';
1110
-        $limit = isset($args['limit']) && absint($args['limit']) ? $args['limit'] : 10;
1111
-        // the current "page" we are viewing
1112
-        $paged = max(1, get_query_var('paged'));
1113
-        // Force these args
1114
-        $args = array_merge(
1115
-            $args, array(
1116
-            'post_type'              => 'espresso_events',
1117
-            'posts_per_page'         => $limit,
1118
-            'update_post_term_cache' => false,
1119
-            'update_post_meta_cache' => false,
1120
-            'paged'                  => $paged,
1121
-            'offset'                 => ($paged - 1) * $limit
1122
-        )
1123
-        );
1124
-        // run the query
1125
-        parent::__construct($args);
1126
-    }
1127
-
1128
-
1129
-
1130
-    /**
1131
-     * event_list_title
1132
-     *
1133
-     * @param string $event_list_title
1134
-     * @return string
1135
-     */
1136
-    public function event_list_title($event_list_title = '')
1137
-    {
1138
-        if (! empty($this->title)) {
1139
-            return $this->title;
1140
-        }
1141
-        return $event_list_title;
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * event_list_css
1148
-     *
1149
-     * @param string $event_list_css
1150
-     * @return string
1151
-     */
1152
-    public function event_list_css($event_list_css = '')
1153
-    {
1154
-        $event_list_css .= ! empty($event_list_css)
1155
-            ? ' '
1156
-            : '';
1157
-        $event_list_css .= ! empty($this->css_class)
1158
-            ? $this->css_class
1159
-            : '';
1160
-        $event_list_css .= ! empty($event_list_css)
1161
-            ? ' '
1162
-            : '';
1163
-        $event_list_css .= ! empty($this->category_slug)
1164
-            ? $this->category_slug
1165
-            : '';
1166
-        return $event_list_css;
1167
-    }
1085
+	private $title;
1086
+
1087
+	private $css_class;
1088
+
1089
+	private $category_slug;
1090
+
1091
+	/**
1092
+	 * EE_Event_List_Query constructor.
1093
+	 *
1094
+	 * @param array $args
1095
+	 */
1096
+	public function __construct($args = array())
1097
+	{
1098
+		\EE_Error::doing_it_wrong(
1099
+			__METHOD__,
1100
+			__(
1101
+				'Usage is deprecated. Please use \EventEspresso\core\domain\services\wp_queries\EventListQuery instead.',
1102
+				'event_espresso'
1103
+			),
1104
+			'4.9.27',
1105
+			'5.0.0'
1106
+		);
1107
+		$this->title = isset($args['title']) ? $args['title'] : '';
1108
+		$this->css_class = isset($args['css_class']) ? $args['css_class'] : '';
1109
+		$this->category_slug = isset($args['category_slug']) ? $args['category_slug'] : '';
1110
+		$limit = isset($args['limit']) && absint($args['limit']) ? $args['limit'] : 10;
1111
+		// the current "page" we are viewing
1112
+		$paged = max(1, get_query_var('paged'));
1113
+		// Force these args
1114
+		$args = array_merge(
1115
+			$args, array(
1116
+			'post_type'              => 'espresso_events',
1117
+			'posts_per_page'         => $limit,
1118
+			'update_post_term_cache' => false,
1119
+			'update_post_meta_cache' => false,
1120
+			'paged'                  => $paged,
1121
+			'offset'                 => ($paged - 1) * $limit
1122
+		)
1123
+		);
1124
+		// run the query
1125
+		parent::__construct($args);
1126
+	}
1127
+
1128
+
1129
+
1130
+	/**
1131
+	 * event_list_title
1132
+	 *
1133
+	 * @param string $event_list_title
1134
+	 * @return string
1135
+	 */
1136
+	public function event_list_title($event_list_title = '')
1137
+	{
1138
+		if (! empty($this->title)) {
1139
+			return $this->title;
1140
+		}
1141
+		return $event_list_title;
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * event_list_css
1148
+	 *
1149
+	 * @param string $event_list_css
1150
+	 * @return string
1151
+	 */
1152
+	public function event_list_css($event_list_css = '')
1153
+	{
1154
+		$event_list_css .= ! empty($event_list_css)
1155
+			? ' '
1156
+			: '';
1157
+		$event_list_css .= ! empty($this->css_class)
1158
+			? $this->css_class
1159
+			: '';
1160
+		$event_list_css .= ! empty($event_list_css)
1161
+			? ' '
1162
+			: '';
1163
+		$event_list_css .= ! empty($this->category_slug)
1164
+			? $this->category_slug
1165
+			: '';
1166
+		return $event_list_css;
1167
+	}
1168 1168
 
1169 1169
 }
Please login to merge, or discard this patch.
Spacing   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
3
-	exit( 'No direct script access allowed' );
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 /**
6 6
  * ************************************************************************
@@ -43,8 +43,8 @@  discard block
 block discarded – undo
43 43
 	$action_or_filter = 'action'
44 44
 ) {
45 45
 	$action_or_filter = $action_or_filter === 'action'
46
-		? esc_html__( 'action', 'event_espresso' )
47
-		: esc_html__( 'filter', 'event_espresso' );
46
+		? esc_html__('action', 'event_espresso')
47
+		: esc_html__('filter', 'event_espresso');
48 48
 	EE_Error::doing_it_wrong(
49 49
 		$deprecated_filter,
50 50
 		sprintf(
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
  * @param \EE_Checkout $checkout
69 69
  * @return string
70 70
  */
71
-function ee_deprecated__registration_checkout__button_text( $submit_button_text, EE_Checkout $checkout ) {
71
+function ee_deprecated__registration_checkout__button_text($submit_button_text, EE_Checkout $checkout) {
72 72
 	// list of old filters
73 73
 	$deprecated_filters = array(
74 74
 		'update_registration_details' => true,
@@ -78,16 +78,16 @@  discard block
 block discarded – undo
78 78
 		'proceed_to' => true,
79 79
 	);
80 80
 	// loop thru and call doing_it_wrong() or remove any that aren't being used
81
-	foreach ( $deprecated_filters as $deprecated_filter => $on ) {
81
+	foreach ($deprecated_filters as $deprecated_filter => $on) {
82 82
 		// was this filter called ?
83
-		if ( has_action( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter )) {
83
+		if (has_action('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter)) {
84 84
 			// only display doing_it_wrong() notice to Event Admins during non-AJAX requests
85
-			if ( EE_Registry::instance()->CAP->current_user_can( 'ee_read_ee', 'hide_doing_it_wrong_for_deprecated_SPCO_filter' ) && ! defined( 'DOING_AJAX' ) ) {
85
+			if (EE_Registry::instance()->CAP->current_user_can('ee_read_ee', 'hide_doing_it_wrong_for_deprecated_SPCO_filter') && ! defined('DOING_AJAX')) {
86 86
 				EE_Error::doing_it_wrong(
87
-					'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter,
87
+					'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter,
88 88
 					sprintf(
89
-						__( 'The %1$s filter is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new filter: %2$s"%3$s" found in "%4$s"', 'event_espresso' ),
90
-						'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__' . $deprecated_filter,
89
+						__('The %1$s filter is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new filter: %2$s"%3$s" found in "%4$s"', 'event_espresso'),
90
+						'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__'.$deprecated_filter,
91 91
 						'<br />',
92 92
 						'FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text',
93 93
 						'/modules/single_page_checkout/inc/EE_SPCO_Reg_Step.class.php'
@@ -96,24 +96,24 @@  discard block
 block discarded – undo
96 96
 				);
97 97
 			}
98 98
 		} else {
99
-			unset( $deprecated_filters[ $deprecated_filter ] );
99
+			unset($deprecated_filters[$deprecated_filter]);
100 100
 		}
101 101
 	}
102
-	if ( ! empty( $deprecated_filters )) {
103
-
104
-		if ( $checkout->current_step->slug() == 'attendee_information' && $checkout->revisit && isset( $deprecated_filters[ 'update_registration_details' ] )) {
105
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__update_registration_details', $submit_button_text );
106
-		} else if ( $checkout->current_step->slug() == 'payment_options' && $checkout->revisit && isset( $deprecated_filters[ 'process_payment' ] ) ) {
107
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__process_payment', $submit_button_text );
108
-		} else if ( $checkout->next_step instanceof EE_SPCO_Reg_Step && $checkout->next_step->slug() == 'finalize_registration' && isset( $deprecated_filters[ 'finalize_registration' ] ) ) {
109
-			$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__finalize_registration', $submit_button_text );
102
+	if ( ! empty($deprecated_filters)) {
103
+
104
+		if ($checkout->current_step->slug() == 'attendee_information' && $checkout->revisit && isset($deprecated_filters['update_registration_details'])) {
105
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__update_registration_details', $submit_button_text);
106
+		} else if ($checkout->current_step->slug() == 'payment_options' && $checkout->revisit && isset($deprecated_filters['process_payment'])) {
107
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__process_payment', $submit_button_text);
108
+		} else if ($checkout->next_step instanceof EE_SPCO_Reg_Step && $checkout->next_step->slug() == 'finalize_registration' && isset($deprecated_filters['finalize_registration'])) {
109
+			$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__finalize_registration', $submit_button_text);
110 110
 		}
111
-		if ( $checkout->next_step instanceof EE_SPCO_Reg_Step ) {
112
-			if ( $checkout->payment_required() && $checkout->next_step->slug() == 'payment_options' && isset( $deprecated_filters[ 'and_proceed_to_payment' ] ) ) {
113
-				$submit_button_text .= apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__and_proceed_to_payment', $submit_button_text );
111
+		if ($checkout->next_step instanceof EE_SPCO_Reg_Step) {
112
+			if ($checkout->payment_required() && $checkout->next_step->slug() == 'payment_options' && isset($deprecated_filters['and_proceed_to_payment'])) {
113
+				$submit_button_text .= apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__and_proceed_to_payment', $submit_button_text);
114 114
 			}
115
-			if ( $checkout->next_step->slug() != 'finalize_registration' && ! $checkout->revisit && isset( $deprecated_filters[ 'proceed_to' ] ) ) {
116
-				$submit_button_text = apply_filters( 'FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__proceed_to', $submit_button_text ) . $checkout->next_step->name();
115
+			if ($checkout->next_step->slug() != 'finalize_registration' && ! $checkout->revisit && isset($deprecated_filters['proceed_to'])) {
116
+				$submit_button_text = apply_filters('FHEE__EED_Single_Page_Checkout__registration_checkout__button_text__proceed_to', $submit_button_text).$checkout->next_step->name();
117 117
 			}
118 118
 		}
119 119
 
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	return $submit_button_text;
122 122
 
123 123
 }
124
-add_filter( 'FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text', 'ee_deprecated__registration_checkout__button_text', 10, 2 );
124
+add_filter('FHEE__EE_SPCO_Reg_Step__set_submit_button_text___submit_button_text', 'ee_deprecated__registration_checkout__button_text', 10, 2);
125 125
 
126 126
 
127 127
 
@@ -132,16 +132,16 @@  discard block
 block discarded – undo
132 132
  * @param \EE_Checkout $checkout
133 133
  * @param boolean $status_updates
134 134
  */
135
-function ee_deprecated_finalize_transaction( EE_Checkout $checkout, $status_updates ) {
135
+function ee_deprecated_finalize_transaction(EE_Checkout $checkout, $status_updates) {
136 136
 	$action_ref = NULL;
137
-	$action_ref = has_action( 'AHEE__EE_Transaction__finalize__new_transaction' ) ? 'AHEE__EE_Transaction__finalize__new_transaction' : $action_ref;
138
-	$action_ref = has_action( 'AHEE__EE_Transaction__finalize__all_transaction' ) ? 'AHEE__EE_Transaction__finalize__all_transaction' : $action_ref;
139
-	if ( $action_ref ) {
137
+	$action_ref = has_action('AHEE__EE_Transaction__finalize__new_transaction') ? 'AHEE__EE_Transaction__finalize__new_transaction' : $action_ref;
138
+	$action_ref = has_action('AHEE__EE_Transaction__finalize__all_transaction') ? 'AHEE__EE_Transaction__finalize__all_transaction' : $action_ref;
139
+	if ($action_ref) {
140 140
 
141 141
 		EE_Error::doing_it_wrong(
142 142
 			$action_ref,
143 143
 			sprintf(
144
-				__( 'This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use one of the following new actions: %1$s"%3$s" found in "%2$s" %1$s"%4$s" found in "%2$s" %1$s"%5$s" found in "%2$s" %1$s"%6$s" found in "%2$s"', 'event_espresso' ),
144
+				__('This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use one of the following new actions: %1$s"%3$s" found in "%2$s" %1$s"%4$s" found in "%2$s" %1$s"%5$s" found in "%2$s" %1$s"%6$s" found in "%2$s"', 'event_espresso'),
145 145
 				'<br />',
146 146
 				'/core/business/EE_Transaction_Processor.class.php',
147 147
 				'AHEE__EE_Transaction_Processor__finalize',
@@ -151,39 +151,39 @@  discard block
 block discarded – undo
151 151
 			),
152 152
 			'4.6.0'
153 153
 		);
154
-		switch ( $action_ref ) {
154
+		switch ($action_ref) {
155 155
 			case 'AHEE__EE_Transaction__finalize__new_transaction' :
156
-				do_action( 'AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, $checkout->admin_request );
156
+				do_action('AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, $checkout->admin_request);
157 157
 				break;
158 158
 			case 'AHEE__EE_Transaction__finalize__all_transaction' :
159
-				do_action( 'AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, array( 'new_reg' => ! $checkout->revisit, 'to_approved' => $status_updates ), $checkout->admin_request );
159
+				do_action('AHEE__EE_Transaction__finalize__new_transaction', $checkout->transaction, array('new_reg' => ! $checkout->revisit, 'to_approved' => $status_updates), $checkout->admin_request);
160 160
 				break;
161 161
 		}
162 162
 	}
163 163
 }
164
-add_action( 'AHEE__EE_SPCO_Reg_Step_Finalize_Registration__process_reg_step__completed', 'ee_deprecated_finalize_transaction', 10, 2 );
164
+add_action('AHEE__EE_SPCO_Reg_Step_Finalize_Registration__process_reg_step__completed', 'ee_deprecated_finalize_transaction', 10, 2);
165 165
 /**
166 166
  * ee_deprecated_finalize_registration
167 167
  *
168 168
  * @param EE_Registration $registration
169 169
  */
170
-function ee_deprecated_finalize_registration( EE_Registration $registration ) {
171
-	$action_ref = has_action( 'AHEE__EE_Registration__finalize__update_and_new_reg' ) ? 'AHEE__EE_Registration__finalize__update_and_new_reg' : NULL;
172
-	if ( $action_ref ) {
170
+function ee_deprecated_finalize_registration(EE_Registration $registration) {
171
+	$action_ref = has_action('AHEE__EE_Registration__finalize__update_and_new_reg') ? 'AHEE__EE_Registration__finalize__update_and_new_reg' : NULL;
172
+	if ($action_ref) {
173 173
 		EE_Error::doing_it_wrong(
174 174
 			$action_ref,
175 175
 			sprintf(
176
-				__( 'This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new action: %1$s"%3$s" found in "%2$s"', 'event_espresso' ),
176
+				__('This action is deprecated.  It *may* work as an attempt to build in backwards compatibility.  However, it is recommended to use the following new action: %1$s"%3$s" found in "%2$s"', 'event_espresso'),
177 177
 				'<br />',
178 178
 				'/core/business/EE_Registration_Processor.class.php',
179 179
 				'AHEE__EE_Registration_Processor__trigger_registration_status_changed_hook'
180 180
 			),
181 181
 			'4.6.0'
182 182
 		);
183
-		do_action( 'AHEE__EE_Registration__finalize__update_and_new_reg', $registration, ( is_admin() && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX )));
183
+		do_action('AHEE__EE_Registration__finalize__update_and_new_reg', $registration, (is_admin() && ! (defined('DOING_AJAX') && DOING_AJAX)));
184 184
 	}
185 185
 }
186
-add_action( 'AHEE__EE_Registration_Processor__trigger_registration_update_notifications', 'ee_deprecated_finalize_registration', 10, 1 );
186
+add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications', 'ee_deprecated_finalize_registration', 10, 1);
187 187
 
188 188
 
189 189
 
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
  * Called after EED_Module::set_hooks() and EED_Module::set_admin_hooks() was called.
192 192
  * Checks if any deprecated hooks were hooked-into and provide doing_it_wrong messages appropriately.
193 193
  */
194
-function ee_deprecated_hooks(){
194
+function ee_deprecated_hooks() {
195 195
 	/**
196 196
 	 * @var $hooks array where keys are hook names, and their values are array{
197 197
 	 *			@type string $version  when deprecated
@@ -202,25 +202,25 @@  discard block
 block discarded – undo
202 202
 	$hooks = array(
203 203
 		'AHEE__EE_System___do_setup_validations' => array(
204 204
 			'version' => '4.6.0',
205
-			'alternative' => __( 'Instead use "AHEE__EEH_Activation__validate_messages_system" which is called after validating messages (done on every new install, upgrade, reactivation, and downgrade)', 'event_espresso' ),
205
+			'alternative' => __('Instead use "AHEE__EEH_Activation__validate_messages_system" which is called after validating messages (done on every new install, upgrade, reactivation, and downgrade)', 'event_espresso'),
206 206
 			'still_works' => FALSE
207 207
 		)
208 208
 	);
209
-	foreach( $hooks as $name => $deprecation_info ){
210
-		if( has_action( $name ) ){
209
+	foreach ($hooks as $name => $deprecation_info) {
210
+		if (has_action($name)) {
211 211
 			EE_Error::doing_it_wrong(
212 212
 				$name,
213 213
 				sprintf(
214
-					__('This filter is deprecated. %1$s%2$s','event_espresso'),
215
-					$deprecation_info[ 'still_works' ] ?  __('It *may* work as an attempt to build in backwards compatibility.', 'event_espresso') : __( 'It has been completely removed.', 'event_espresso' ),
216
-					isset( $deprecation_info[ 'alternative' ] ) ? $deprecation_info[ 'alternative' ] : __( 'Please read the current EE4 documentation further or contact Support.', 'event_espresso' )
214
+					__('This filter is deprecated. %1$s%2$s', 'event_espresso'),
215
+					$deprecation_info['still_works'] ?  __('It *may* work as an attempt to build in backwards compatibility.', 'event_espresso') : __('It has been completely removed.', 'event_espresso'),
216
+					isset($deprecation_info['alternative']) ? $deprecation_info['alternative'] : __('Please read the current EE4 documentation further or contact Support.', 'event_espresso')
217 217
 				),
218
-				isset( $deprecation_info[ 'version' ] ) ? $deprecation_info[ 'version' ] : __( 'recently', 'event_espresso' )
218
+				isset($deprecation_info['version']) ? $deprecation_info['version'] : __('recently', 'event_espresso')
219 219
 			);
220 220
 		}
221 221
 	}
222 222
 }
223
-add_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons', 'ee_deprecated_hooks' );
223
+add_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons', 'ee_deprecated_hooks');
224 224
 
225 225
 
226 226
 
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
  * @return boolean
232 232
  */
233 233
 function ee_deprecated_using_old_registration_admin_custom_questions_form_hooks() {
234
-	$in_use =  has_filter( 'FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns' )
235
-			|| has_action( 'AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save' );
236
-	if( $in_use ) {
234
+	$in_use = has_filter('FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns')
235
+			|| has_action('AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save');
236
+	if ($in_use) {
237 237
 		$msg = __(
238 238
 			'We detected you are using the filter FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns or AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save.'
239 239
 			. 'Both of these have been deprecated and should not be used anymore. You should instead use FHEE__EE_Form_Section_Proper___construct__options_array to customize the contents of the form,'
@@ -242,18 +242,18 @@  discard block
 block discarded – undo
242 242
 			'event_espresso' )
243 243
 		;
244 244
 		EE_Error::doing_it_wrong(
245
-			__CLASS__ . '::' . __FUNCTION__,
245
+			__CLASS__.'::'.__FUNCTION__,
246 246
 			$msg,
247 247
 			'4.8.32.rc.000'
248 248
 		);
249 249
 		//it seems the doing_it_wrong messages get output during some hidden html tags, so add an error to make sure this gets noticed
250
-		if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
251
-			EE_Error::add_error( $msg, __FILE__, __FUNCTION__, __LINE__ );
250
+		if (is_admin() && ! defined('DOING_AJAX')) {
251
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
252 252
 		}
253 253
 	}
254 254
 	return $in_use;
255 255
 }
256
-add_action( 'AHEE__Registrations_Admin_Page___registration_details_metabox__start', 'ee_deprecated_using_old_registration_admin_custom_questions_form_hooks' );
256
+add_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', 'ee_deprecated_using_old_registration_admin_custom_questions_form_hooks');
257 257
 
258 258
 /**
259 259
  * @deprecated since 4.8.32.rc.000 because it has issues on https://events.codebasehq.com/projects/event-espresso/tickets/9165
@@ -262,34 +262,34 @@  discard block
 block discarded – undo
262 262
  * @param EE_Admin_Page $admin_page
263 263
  * @return void
264 264
  */
265
-function ee_deprecated_update_attendee_registration_form_old( $admin_page ) {
265
+function ee_deprecated_update_attendee_registration_form_old($admin_page) {
266 266
 	//check if the old hooks are in use. If not, do the default
267
-	if( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
268
-		|| ! $admin_page instanceof EE_Admin_Page ) {
267
+	if ( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
268
+		|| ! $admin_page instanceof EE_Admin_Page) {
269 269
 		return;
270 270
 	}
271 271
 	$req_data = $admin_page->get_request_data();
272
-	$qstns = isset( $req_data['qstn'] ) ? $req_data['qstn'] : FALSE;
273
-	$REG_ID = isset( $req_data['_REG_ID'] ) ? absint( $req_data['_REG_ID'] ) : FALSE;
274
-	$qstns = apply_filters( 'FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns', $qstns );
275
-	if ( ! $REG_ID || ! $qstns ) {
276
-		EE_Error::add_error( __('An error occurred. No registration ID and/or registration questions were received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
272
+	$qstns = isset($req_data['qstn']) ? $req_data['qstn'] : FALSE;
273
+	$REG_ID = isset($req_data['_REG_ID']) ? absint($req_data['_REG_ID']) : FALSE;
274
+	$qstns = apply_filters('FHEE__Registrations_Admin_Page___update_attendee_registration_form__qstns', $qstns);
275
+	if ( ! $REG_ID || ! $qstns) {
276
+		EE_Error::add_error(__('An error occurred. No registration ID and/or registration questions were received.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
277 277
 	}
278 278
 	$success = TRUE;
279 279
 
280 280
 	// allow others to get in on this awesome fun   :D
281
-	do_action( 'AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save', $REG_ID, $qstns );
281
+	do_action('AHEE__Registrations_Admin_Page___save_attendee_registration_form__after_reg_and_attendee_save', $REG_ID, $qstns);
282 282
 	// loop thru questions... FINALLY!!!
283 283
 
284
-	foreach ( $qstns as $QST_ID => $qstn ) {
284
+	foreach ($qstns as $QST_ID => $qstn) {
285 285
 		//if $qstn isn't an array then it doesn't already have an answer, so let's create the answer
286
-		if ( !is_array($qstn) ) {
287
-			$success = $this->_save_new_answer( $REG_ID, $QST_ID, $qstn);
286
+		if ( ! is_array($qstn)) {
287
+			$success = $this->_save_new_answer($REG_ID, $QST_ID, $qstn);
288 288
 			continue;
289 289
 		}
290 290
 
291 291
 
292
-		foreach ( $qstn as $ANS_ID => $ANS_value ) {
292
+		foreach ($qstn as $ANS_ID => $ANS_value) {
293 293
 			//get answer
294 294
 			$query_params = array(
295 295
 				0 => array(
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 				);
301 301
 			$answer = EEM_Answer::instance()->get_one($query_params);
302 302
 			//this MAY be an array but NOT have an answer because its multi select.  If so then we need to create the answer
303
-			if ( ! $answer instanceof EE_Answer ) {
303
+			if ( ! $answer instanceof EE_Answer) {
304 304
 				$set_values = array(
305 305
 					'QST_ID' => $QST_ID,
306 306
 					'REG_ID' => $REG_ID,
@@ -315,11 +315,11 @@  discard block
 block discarded – undo
315 315
 		}
316 316
 	}
317 317
 	$what = __('Registration Form', 'event_espresso');
318
-	$route = $REG_ID ? array( 'action' => 'view_registration', '_REG_ID' => $REG_ID ) : array( 'action' => 'default' );
319
-	$admin_page->redirect_after_action( $success, $what, __('updated', 'event_espresso'), $route );
318
+	$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID) : array('action' => 'default');
319
+	$admin_page->redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
320 320
 	exit;
321 321
 }
322
-add_action( 'AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', 'ee_deprecated_update_attendee_registration_form_old', 10, 1 );
322
+add_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', 'ee_deprecated_update_attendee_registration_form_old', 10, 1);
323 323
 /**
324 324
  * Render the registration admin page's custom questions area in the old fashion
325 325
  * and firing the old hooks. When this method is removed, we can probably also
@@ -332,31 +332,31 @@  discard block
 block discarded – undo
332 332
  * @return bool
333 333
  * @throws \EE_Error
334 334
  */
335
-function ee_deprecated_reg_questions_meta_box_old( $do_default_action, $admin_page, $registration ) {
335
+function ee_deprecated_reg_questions_meta_box_old($do_default_action, $admin_page, $registration) {
336 336
 	//check if the old hooks are in use. If not, do the default
337
-	if( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
338
-		|| ! $admin_page instanceof EE_Admin_Page ) {
337
+	if ( ! ee_deprecated_using_old_registration_admin_custom_questions_form_hooks()
338
+		|| ! $admin_page instanceof EE_Admin_Page) {
339 339
 		return $do_default_action;
340 340
 	}
341
-	add_filter( 'FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', array( $admin_page, 'form_before_question_group' ), 10, 1 );
342
-	add_filter( 'FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', array( $admin_page, 'form_after_question_group' ), 10, 1 );
343
-	add_filter( 'FHEE__EEH_Form_Fields__label_html', array( $admin_page, 'form_form_field_label_wrap' ), 10, 1 );
344
-	add_filter( 'FHEE__EEH_Form_Fields__input_html', array( $admin_page, 'form_form_field_input__wrap' ), 10, 1 );
341
+	add_filter('FHEE__EEH_Form_Fields__generate_question_groups_html__before_question_group_questions', array($admin_page, 'form_before_question_group'), 10, 1);
342
+	add_filter('FHEE__EEH_Form_Fields__generate_question_groups_html__after_question_group_questions', array($admin_page, 'form_after_question_group'), 10, 1);
343
+	add_filter('FHEE__EEH_Form_Fields__label_html', array($admin_page, 'form_form_field_label_wrap'), 10, 1);
344
+	add_filter('FHEE__EEH_Form_Fields__input_html', array($admin_page, 'form_form_field_input__wrap'), 10, 1);
345 345
 
346
-	$question_groups = EEM_Event::instance()->assemble_array_of_groups_questions_and_options( $registration, $registration->get('EVT_ID') );
346
+	$question_groups = EEM_Event::instance()->assemble_array_of_groups_questions_and_options($registration, $registration->get('EVT_ID'));
347 347
 
348
-	EE_Registry::instance()->load_helper( 'Form_Fields' );
348
+	EE_Registry::instance()->load_helper('Form_Fields');
349 349
 	$template_args = array(
350
-		'att_questions' => EEH_Form_Fields::generate_question_groups_html( $question_groups ),
350
+		'att_questions' => EEH_Form_Fields::generate_question_groups_html($question_groups),
351 351
 		'reg_questions_form_action' => 'edit_registration',
352 352
 		'REG_ID' => $registration->ID()
353 353
 	);
354
-	$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
355
-	echo EEH_Template::display_template( $template_path, $template_args, TRUE );
354
+	$template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_questions.template.php';
355
+	echo EEH_Template::display_template($template_path, $template_args, TRUE);
356 356
 	//indicate that we should not do the default admin page code
357 357
 	return false;
358 358
 }
359
-add_action( 'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', 'ee_deprecated_reg_questions_meta_box_old', 10, 3 );
359
+add_action('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', 'ee_deprecated_reg_questions_meta_box_old', 10, 3);
360 360
 
361 361
 
362 362
 
@@ -397,9 +397,9 @@  discard block
 block discarded – undo
397 397
 			'4.9.0'
398 398
 		);
399 399
 		/** @var EE_Message_Resource_Manager $message_resource_manager */
400
-		$message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
401
-		$messenger = $message_resource_manager->get_messenger( $messenger_name );
402
-		$message_type = $message_resource_manager->get_message_type( $message_type_name );
400
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
401
+		$messenger = $message_resource_manager->get_messenger($messenger_name);
402
+		$message_type = $message_resource_manager->get_message_type($message_type_name);
403 403
 		return EE_Registry::instance()->load_lib(
404 404
 			'Messages_Template_Defaults',
405 405
 			array(
@@ -464,15 +464,15 @@  discard block
 block discarded – undo
464 464
 	/**
465 465
 	 * @param string $method
466 466
 	 */
467
-	public function _class_is_deprecated( $method ) {
467
+	public function _class_is_deprecated($method) {
468 468
 		EE_Error::doing_it_wrong(
469
-			'EE_messages::' . $method,
470
-			__( 'EE_messages has been deprecated.  Please use EE_Message_Resource_Manager instead.' ),
469
+			'EE_messages::'.$method,
470
+			__('EE_messages has been deprecated.  Please use EE_Message_Resource_Manager instead.'),
471 471
 			'4.9.0',
472 472
 			'4.10.0.p'
473 473
 		);
474 474
 		// Please use EE_Message_Resource_Manager instead
475
-		$this->_message_resource_manager = EE_Registry::instance()->load_lib( 'Message_Resource_Manager' );
475
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
476 476
 	}
477 477
 
478 478
 
@@ -482,10 +482,10 @@  discard block
 block discarded – undo
482 482
 	 * @param string $messenger_name
483 483
 	 * @return boolean TRUE if it was PREVIOUSLY active, and FALSE if it was previously inactive
484 484
 	 */
485
-	public function ensure_messenger_is_active( $messenger_name ) {
485
+	public function ensure_messenger_is_active($messenger_name) {
486 486
 		// EE_messages has been deprecated
487
-		$this->_class_is_deprecated( __FUNCTION__ );
488
-		return $this->_message_resource_manager->ensure_messenger_is_active( $messenger_name );
487
+		$this->_class_is_deprecated(__FUNCTION__);
488
+		return $this->_message_resource_manager->ensure_messenger_is_active($messenger_name);
489 489
 	}
490 490
 
491 491
 
@@ -497,10 +497,10 @@  discard block
 block discarded – undo
497 497
 	 * @return bool true if it got activated (or was active) and false if not.
498 498
 	 * @throws \EE_Error
499 499
 	 */
500
-	public function ensure_message_type_is_active( $message_type, $messenger ) {
500
+	public function ensure_message_type_is_active($message_type, $messenger) {
501 501
 		// EE_messages has been deprecated
502
-		$this->_class_is_deprecated( __FUNCTION__ );
503
-		return $this->_message_resource_manager->ensure_message_type_is_active( $message_type, $messenger );
502
+		$this->_class_is_deprecated(__FUNCTION__);
503
+		return $this->_message_resource_manager->ensure_message_type_is_active($message_type, $messenger);
504 504
 	}
505 505
 
506 506
 
@@ -513,10 +513,10 @@  discard block
 block discarded – undo
513 513
 	 *                                            they are already setup.)
514 514
 	 * @return boolean an array of generated templates or false if nothing generated/activated.
515 515
 	 */
516
-	public function activate_messenger( $messenger_name, $mts_to_activate = array() ) {
516
+	public function activate_messenger($messenger_name, $mts_to_activate = array()) {
517 517
 		// EE_messages has been deprecated
518
-		$this->_class_is_deprecated( __FUNCTION__ );
519
-		return $this->_message_resource_manager->activate_messenger( $messenger_name, $mts_to_activate );
518
+		$this->_class_is_deprecated(__FUNCTION__);
519
+		return $this->_message_resource_manager->activate_messenger($messenger_name, $mts_to_activate);
520 520
 	}
521 521
 
522 522
 
@@ -528,10 +528,10 @@  discard block
 block discarded – undo
528 528
 	 *
529 529
 	 * @return bool true is a generating messenger and can be sent OR FALSE meaning cannot send.
530 530
 	 */
531
-	public function is_generating_messenger_and_active( EE_messenger $messenger, EE_message_type $message_type ) {
531
+	public function is_generating_messenger_and_active(EE_messenger $messenger, EE_message_type $message_type) {
532 532
 		// EE_messages has been deprecated
533
-		$this->_class_is_deprecated( __FUNCTION__ );
534
-		return $this->_message_resource_manager->is_generating_messenger_and_active( $messenger, $message_type );
533
+		$this->_class_is_deprecated(__FUNCTION__);
534
+		return $this->_message_resource_manager->is_generating_messenger_and_active($messenger, $message_type);
535 535
 	}
536 536
 
537 537
 
@@ -541,10 +541,10 @@  discard block
 block discarded – undo
541 541
 	 * @param string $messenger
542 542
 	 * @return EE_messenger | null
543 543
 	 */
544
-	public function get_messenger_if_active( $messenger ) {
544
+	public function get_messenger_if_active($messenger) {
545 545
 		// EE_messages has been deprecated
546
-		$this->_class_is_deprecated( __FUNCTION__ );
547
-		return $this->_message_resource_manager->get_active_messenger( $messenger );
546
+		$this->_class_is_deprecated(__FUNCTION__);
547
+		return $this->_message_resource_manager->get_active_messenger($messenger);
548 548
 	}
549 549
 
550 550
 
@@ -565,9 +565,9 @@  discard block
 block discarded – undo
565 565
 	 *                  'message_type' => null
566 566
 	 *                  )
567 567
 	 */
568
-	public function validate_for_use( EE_Message $message ) {
568
+	public function validate_for_use(EE_Message $message) {
569 569
 		// EE_messages has been deprecated
570
-		$this->_class_is_deprecated( __FUNCTION__ );
570
+		$this->_class_is_deprecated(__FUNCTION__);
571 571
 		return array(
572 572
 			'messenger'    => $message->messenger_object(),
573 573
 			'message_type' => $message->message_type_object(),
@@ -595,41 +595,41 @@  discard block
 block discarded – undo
595 595
 		$send = true
596 596
 	) {
597 597
 		// EE_messages has been deprecated
598
-		$this->_class_is_deprecated( __FUNCTION__ );
598
+		$this->_class_is_deprecated(__FUNCTION__);
599 599
 		/** @type EE_Messages_Processor $processor */
600
-		$processor = EE_Registry::instance()->load_lib( 'Messages_Processor' );
600
+		$processor = EE_Registry::instance()->load_lib('Messages_Processor');
601 601
 		$error = false;
602 602
 		//try to intelligently determine what method we'll call based on the incoming data.
603 603
 		//if generating and sending are different then generate and send immediately.
604
-		if ( ! empty( $sending_messenger ) && $sending_messenger != $generating_messenger && $send ) {
604
+		if ( ! empty($sending_messenger) && $sending_messenger != $generating_messenger && $send) {
605 605
 			//in the legacy system, when generating and sending were different, that means all the
606 606
 			//vars are already in the request object.  So let's just use that.
607 607
 			try {
608 608
 				/** @type EE_Message_To_Generate_From_Request $mtg */
609
-				$mtg = EE_Registry::instance()->load_lib( 'Message_To_Generate_From_Request' );
610
-				$processor->generate_and_send_now( $mtg );
611
-			} catch ( EE_Error $e ) {
609
+				$mtg = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
610
+				$processor->generate_and_send_now($mtg);
611
+			} catch (EE_Error $e) {
612 612
 				$error_msg = __(
613 613
 					'Please note that a system message failed to send due to a technical issue.',
614 614
 					'event_espresso'
615 615
 				);
616 616
 				// add specific message for developers if WP_DEBUG in on
617
-				$error_msg .= '||' . $e->getMessage();
618
-				EE_Error::add_error( $error_msg, __FILE__, __FUNCTION__, __LINE__ );
617
+				$error_msg .= '||'.$e->getMessage();
618
+				EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
619 619
 				$error = true;
620 620
 			}
621 621
 		} else {
622
-			$processor->generate_for_all_active_messengers( $type, $vars, $send );
622
+			$processor->generate_for_all_active_messengers($type, $vars, $send);
623 623
 			//let's find out if there were any errors and how many successfully were queued.
624 624
 			$count_errors = $processor->get_queue()->count_STS_in_queue(
625
-				array( EEM_Message::status_failed, EEM_Message::status_debug_only )
625
+				array(EEM_Message::status_failed, EEM_Message::status_debug_only)
626 626
 			);
627
-			$count_queued = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_incomplete );
628
-			$count_retry = $processor->get_queue()->count_STS_in_queue( EEM_Message::status_retry );
627
+			$count_queued = $processor->get_queue()->count_STS_in_queue(EEM_Message::status_incomplete);
628
+			$count_retry = $processor->get_queue()->count_STS_in_queue(EEM_Message::status_retry);
629 629
 			$count_errors = $count_errors + $count_retry;
630
-			if ( $count_errors > 0 ) {
630
+			if ($count_errors > 0) {
631 631
 				$error = true;
632
-				if ( $count_errors > 1 && $count_retry > 1 && $count_queued > 1 ) {
632
+				if ($count_errors > 1 && $count_retry > 1 && $count_queued > 1) {
633 633
 					$message = sprintf(
634 634
 						__(
635 635
 							'There were %d errors and %d messages successfully queued for generation and sending',
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 						$count_errors,
639 639
 						$count_queued
640 640
 					);
641
-				} elseif ( $count_errors > 1 && $count_queued === 1 ) {
641
+				} elseif ($count_errors > 1 && $count_queued === 1) {
642 642
 					$message = sprintf(
643 643
 						__(
644 644
 							'There were %d errors and %d message successfully queued for generation.',
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
 						$count_errors,
648 648
 						$count_queued
649 649
 					);
650
-				} elseif ( $count_errors === 1 && $count_queued > 1 ) {
650
+				} elseif ($count_errors === 1 && $count_queued > 1) {
651 651
 					$message = sprintf(
652 652
 						__(
653 653
 							'There was %d error and %d messages successfully queued for generation.',
@@ -665,9 +665,9 @@  discard block
 block discarded – undo
665 665
 						$count_errors
666 666
 					);
667 667
 				}
668
-				EE_Error::add_error( $message, __FILE__, __FUNCTION__, __LINE__ );
668
+				EE_Error::add_error($message, __FILE__, __FUNCTION__, __LINE__);
669 669
 			} else {
670
-				if ( $count_queued === 1 ) {
670
+				if ($count_queued === 1) {
671 671
 					$message = sprintf(
672 672
 						__(
673 673
 							'%d message successfully queued for generation.',
@@ -684,18 +684,18 @@  discard block
 block discarded – undo
684 684
 						$count_queued
685 685
 					);
686 686
 				}
687
-				EE_Error::add_success( $message );
687
+				EE_Error::add_success($message);
688 688
 			}
689 689
 		}
690 690
 		//if no error then return the generated message(s).
691
-		if ( ! $error && ! $send ) {
692
-			$generated_queue = $processor->generate_queue( false );
691
+		if ( ! $error && ! $send) {
692
+			$generated_queue = $processor->generate_queue(false);
693 693
 			//get message and return.
694 694
 			$generated_queue->get_message_repository()->rewind();
695 695
 			$messages = array();
696
-			while ( $generated_queue->get_message_repository()->valid() ) {
696
+			while ($generated_queue->get_message_repository()->valid()) {
697 697
 				$message = $generated_queue->get_message_repository()->current();
698
-				if ( $message instanceof EE_Message ) {
698
+				if ($message instanceof EE_Message) {
699 699
 					//set properties that might be expected by add-ons (backward compat)
700 700
 					$message->content = $message->content();
701 701
 					$message->template_pack = $message->get_template_pack();
@@ -720,10 +720,10 @@  discard block
 block discarded – undo
720 720
 	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular preview
721 721
 	 * @return string          The body of the message.
722 722
 	 */
723
-	public function preview_message( $type, $context, $messenger, $send = false ) {
723
+	public function preview_message($type, $context, $messenger, $send = false) {
724 724
 		// EE_messages has been deprecated
725
-		$this->_class_is_deprecated( __FUNCTION__ );
726
-		return EED_Messages::preview_message( $type, $context, $messenger, $send );
725
+		$this->_class_is_deprecated(__FUNCTION__);
726
+		return EED_Messages::preview_message($type, $context, $messenger, $send);
727 727
 	}
728 728
 
729 729
 
@@ -737,14 +737,14 @@  discard block
 block discarded – undo
737 737
 	 *
738 738
 	 * @return bool          success or fail.
739 739
 	 */
740
-	public function send_message_with_messenger_only( $messenger, $message_type, $message ) {
740
+	public function send_message_with_messenger_only($messenger, $message_type, $message) {
741 741
 		// EE_messages has been deprecated
742
-		$this->_class_is_deprecated( __FUNCTION__ );
742
+		$this->_class_is_deprecated(__FUNCTION__);
743 743
 		//setup for sending to new method.
744 744
 		/** @type EE_Messages_Queue $queue */
745
-		$queue = EE_Registry::instance()->load_lib( 'Messages_Queue' );
745
+		$queue = EE_Registry::instance()->load_lib('Messages_Queue');
746 746
 		//make sure we have a proper message object
747
-		if ( ! $message instanceof EE_Message && is_object( $message ) && isset( $message->content ) ) {
747
+		if ( ! $message instanceof EE_Message && is_object($message) && isset($message->content)) {
748 748
 			$msg = EE_Message_Factory::create(
749 749
 				array(
750 750
 					'MSG_messenger'    => $messenger,
@@ -756,15 +756,15 @@  discard block
 block discarded – undo
756 756
 		} else {
757 757
 			$msg = $message;
758 758
 		}
759
-		if ( ! $msg instanceof EE_Message ) {
759
+		if ( ! $msg instanceof EE_Message) {
760 760
 			return false;
761 761
 		}
762 762
 		//make sure any content in a content property (if not empty) is set on the MSG_content.
763
-		if ( ! empty( $msg->content ) ) {
764
-			$msg->set( 'MSG_content', $msg->content );
763
+		if ( ! empty($msg->content)) {
764
+			$msg->set('MSG_content', $msg->content);
765 765
 		}
766
-		$queue->add( $msg );
767
-		return EED_Messages::send_message_with_messenger_only( $messenger, $message_type, $queue );
766
+		$queue->add($msg);
767
+		return EED_Messages::send_message_with_messenger_only($messenger, $message_type, $queue);
768 768
 	}
769 769
 
770 770
 
@@ -778,11 +778,11 @@  discard block
 block discarded – undo
778 778
 	 * @return array|object if creation is successful then we return an array of info, otherwise an error_object is returned.
779 779
 	 * @throws \EE_Error
780 780
 	 */
781
-	public function create_new_templates( $messenger, $message_type, $GRP_ID = 0, $is_global = false ) {
781
+	public function create_new_templates($messenger, $message_type, $GRP_ID = 0, $is_global = false) {
782 782
 		// EE_messages has been deprecated
783
-		$this->_class_is_deprecated( __FUNCTION__ );
784
-		EE_Registry::instance()->load_helper( 'MSG_Template' );
785
-		return EEH_MSG_Template::create_new_templates( $messenger, $message_type, $GRP_ID, $is_global );
783
+		$this->_class_is_deprecated(__FUNCTION__);
784
+		EE_Registry::instance()->load_helper('MSG_Template');
785
+		return EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $is_global);
786 786
 	}
787 787
 
788 788
 
@@ -793,11 +793,11 @@  discard block
 block discarded – undo
793 793
 	 * @param  string $message_type_name name of EE_message_type
794 794
 	 * @return array
795 795
 	 */
796
-	public function get_fields( $messenger_name, $message_type_name ) {
796
+	public function get_fields($messenger_name, $message_type_name) {
797 797
 		// EE_messages has been deprecated
798
-		$this->_class_is_deprecated( __FUNCTION__ );
799
-		EE_Registry::instance()->load_helper( 'MSG_Template' );
800
-		return EEH_MSG_Template::get_fields( $messenger_name, $message_type_name );
798
+		$this->_class_is_deprecated(__FUNCTION__);
799
+		EE_Registry::instance()->load_helper('MSG_Template');
800
+		return EEH_MSG_Template::get_fields($messenger_name, $message_type_name);
801 801
 	}
802 802
 
803 803
 
@@ -811,13 +811,13 @@  discard block
 block discarded – undo
811 811
 	 * @return array                    multidimensional array of messenger and message_type objects
812 812
 	 *                                    (messengers index, and message_type index);
813 813
 	 */
814
-	public function get_installed( $type = 'all', $skip_cache = false ) {
814
+	public function get_installed($type = 'all', $skip_cache = false) {
815 815
 		// EE_messages has been deprecated
816
-		$this->_class_is_deprecated( __FUNCTION__ );
817
-		if ( $skip_cache ) {
816
+		$this->_class_is_deprecated(__FUNCTION__);
817
+		if ($skip_cache) {
818 818
 			$this->_message_resource_manager->reset_active_messengers_and_message_types();
819 819
 		}
820
-		switch ( $type ) {
820
+		switch ($type) {
821 821
 			case 'messengers' :
822 822
 				return array(
823 823
 					'messenger' => $this->_message_resource_manager->installed_messengers(),
@@ -846,7 +846,7 @@  discard block
 block discarded – undo
846 846
 	 */
847 847
 	public function get_active_messengers() {
848 848
 		// EE_messages has been deprecated
849
-		$this->_class_is_deprecated( __FUNCTION__ );
849
+		$this->_class_is_deprecated(__FUNCTION__);
850 850
 		return $this->_message_resource_manager->active_messengers();
851 851
 	}
852 852
 
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
 	 */
859 859
 	public function get_active_message_types() {
860 860
 		// EE_messages has been deprecated
861
-		$this->_class_is_deprecated( __FUNCTION__ );
861
+		$this->_class_is_deprecated(__FUNCTION__);
862 862
 		return $this->_message_resource_manager->list_of_active_message_types();
863 863
 	}
864 864
 
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 	 */
871 871
 	public function get_active_message_type_objects() {
872 872
 		// EE_messages has been deprecated
873
-		$this->_class_is_deprecated( __FUNCTION__ );
873
+		$this->_class_is_deprecated(__FUNCTION__);
874 874
 		return $this->_message_resource_manager->get_active_message_type_objects();
875 875
 	}
876 876
 
@@ -882,10 +882,10 @@  discard block
 block discarded – undo
882 882
 	 * @param string $messenger The messenger being checked
883 883
 	 * @return EE_message_type[]    (or empty array if none present)
884 884
 	 */
885
-	public function get_active_message_types_per_messenger( $messenger ) {
885
+	public function get_active_message_types_per_messenger($messenger) {
886 886
 		// EE_messages has been deprecated
887
-		$this->_class_is_deprecated( __FUNCTION__ );
888
-		return $this->_message_resource_manager->get_active_message_types_for_messenger( $messenger );
887
+		$this->_class_is_deprecated(__FUNCTION__);
888
+		return $this->_message_resource_manager->get_active_message_types_for_messenger($messenger);
889 889
 	}
890 890
 
891 891
 
@@ -896,10 +896,10 @@  discard block
 block discarded – undo
896 896
 	 * @param string $message_type The string should correspond to a message type.
897 897
 	 * @return EE_message_type|null
898 898
 	 */
899
-	public function get_active_message_type( $messenger, $message_type ) {
899
+	public function get_active_message_type($messenger, $message_type) {
900 900
 		// EE_messages has been deprecated
901
-		$this->_class_is_deprecated( __FUNCTION__ );
902
-		return $this->_message_resource_manager->get_active_message_type_for_messenger( $messenger, $message_type );
901
+		$this->_class_is_deprecated(__FUNCTION__);
902
+		return $this->_message_resource_manager->get_active_message_type_for_messenger($messenger, $message_type);
903 903
 	}
904 904
 
905 905
 
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
 	 */
911 911
 	public function get_installed_message_types() {
912 912
 		// EE_messages has been deprecated
913
-		$this->_class_is_deprecated( __FUNCTION__ );
913
+		$this->_class_is_deprecated(__FUNCTION__);
914 914
 		return $this->_message_resource_manager->installed_message_types();
915 915
 	}
916 916
 
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
 	 */
923 923
 	public function get_installed_messengers() {
924 924
 		// EE_messages has been deprecated
925
-		$this->_class_is_deprecated( __FUNCTION__ );
925
+		$this->_class_is_deprecated(__FUNCTION__);
926 926
 		return $this->_message_resource_manager->installed_messengers();
927 927
 	}
928 928
 
@@ -933,10 +933,10 @@  discard block
 block discarded – undo
933 933
 	 * @param   bool $slugs_only Whether to return an array of just slugs and labels (true) or all contexts indexed by message type.
934 934
 	 * @return array
935 935
 	 */
936
-	public function get_all_contexts( $slugs_only = true ) {
936
+	public function get_all_contexts($slugs_only = true) {
937 937
 		// EE_messages has been deprecated
938
-		$this->_class_is_deprecated( __FUNCTION__ );
939
-		return $this->_message_resource_manager->get_all_contexts( $slugs_only );
938
+		$this->_class_is_deprecated(__FUNCTION__);
939
+		return $this->_message_resource_manager->get_all_contexts($slugs_only);
940 940
 	}
941 941
 
942 942
 
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 add_filter(
996 996
 	'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__css',
997 997
 	function($event_list_iframe_css) {
998
-		if ( ! has_filter( 'FHEE__EventsArchiveIframe__event_list_iframe__css' )) {
998
+		if ( ! has_filter('FHEE__EventsArchiveIframe__event_list_iframe__css')) {
999 999
 			return $event_list_iframe_css;
1000 1000
 		}
1001 1001
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
 add_filter(
1016 1016
 	'FHEE__EventEspresso_modules_events_archive_EventsArchiveIframe__display__js',
1017 1017
 	function($event_list_iframe_js) {
1018
-		if ( ! has_filter( 'FHEE__EED_Ticket_Selector__ticket_selector_iframe__js' )) {
1018
+		if ( ! has_filter('FHEE__EED_Ticket_Selector__ticket_selector_iframe__js')) {
1019 1019
 			return $event_list_iframe_js;
1020 1020
 		}
1021 1021
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
 add_action(
1036 1036
 	'AHEE__EE_Capabilities__addCaps__complete',
1037 1037
 	function($capabilities_map) {
1038
-		if ( ! has_action( 'AHEE__EE_Capabilities__init_role_caps__complete' )) {
1038
+		if ( ! has_action('AHEE__EE_Capabilities__init_role_caps__complete')) {
1039 1039
 			return;
1040 1040
 		}
1041 1041
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
 add_filter(
1056 1056
 	'FHEE_EventEspresso_core_services_commands_attendee_CreateAttendeeCommandHandler__findExistingAttendee__existing_attendee',
1057 1057
 	function($existing_attendee, $registration, $attendee_data) {
1058
-		if ( ! has_filter( 'FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee' )) {
1058
+		if ( ! has_filter('FHEE_EE_Single_Page_Checkout__save_registration_items__find_existing_attendee')) {
1059 1059
 			return $existing_attendee;
1060 1060
 		}
1061 1061
 		deprecated_espresso_action_or_filter_doing_it_wrong(
@@ -1071,7 +1071,7 @@  discard block
 block discarded – undo
1071 1071
             $existing_attendee, $registration, $attendee_data
1072 1072
         );
1073 1073
 	},
1074
-	10,3
1074
+	10, 3
1075 1075
 );
1076 1076
 
1077 1077
 /**
@@ -1135,7 +1135,7 @@  discard block
 block discarded – undo
1135 1135
      */
1136 1136
     public function event_list_title($event_list_title = '')
1137 1137
     {
1138
-        if (! empty($this->title)) {
1138
+        if ( ! empty($this->title)) {
1139 1139
             return $this->title;
1140 1140
         }
1141 1141
         return $event_list_title;
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 1 patch
Indentation   +1652 added lines, -1652 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\ResettableInterface;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -17,243 +17,243 @@  discard block
 block discarded – undo
17 17
 class EEH_Activation implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * constant used to indicate a cron task is no longer in use
22
-     */
23
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
24
-
25
-    /**
26
-     * option name that will indicate whether or not we still
27
-     * need to create EE's folders in the uploads directory
28
-     * (because if EE was installed without file system access,
29
-     * we need to request credentials before we can create them)
30
-     */
31
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
32
-
33
-    /**
34
-     * WP_User->ID
35
-     *
36
-     * @var int
37
-     */
38
-    private static $_default_creator_id;
39
-
40
-    /**
41
-     * indicates whether or not we've already verified core's default data during this request,
42
-     * because after migrations are done, any addons activated while in maintenance mode
43
-     * will want to setup their own default data, and they might hook into core's default data
44
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
45
-     * This prevents doing that for EVERY single addon.
46
-     *
47
-     * @var boolean
48
-     */
49
-    protected static $_initialized_db_content_already_in_this_request = false;
50
-
51
-    /**
52
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
53
-     */
54
-    private static $table_analysis;
55
-
56
-    /**
57
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
58
-     */
59
-    private static $table_manager;
60
-
61
-
62
-    /**
63
-     * @return \EventEspresso\core\services\database\TableAnalysis
64
-     */
65
-    public static function getTableAnalysis()
66
-    {
67
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
68
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
69
-        }
70
-        return self::$table_analysis;
71
-    }
72
-
73
-
74
-    /**
75
-     * @return \EventEspresso\core\services\database\TableManager
76
-     */
77
-    public static function getTableManager()
78
-    {
79
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
80
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
81
-        }
82
-        return self::$table_manager;
83
-    }
84
-
85
-
86
-    /**
87
-     *    _ensure_table_name_has_prefix
88
-     *
89
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
90
-     * @access     public
91
-     * @static
92
-     * @param $table_name
93
-     * @return string
94
-     */
95
-    public static function ensure_table_name_has_prefix($table_name)
96
-    {
97
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
98
-    }
99
-
100
-
101
-    /**
102
-     *    system_initialization
103
-     *    ensures the EE configuration settings are loaded with at least default options set
104
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
105
-     *
106
-     * @access public
107
-     * @static
108
-     * @return void
109
-     */
110
-    public static function system_initialization()
111
-    {
112
-        EEH_Activation::reset_and_update_config();
113
-        //which is fired BEFORE activation of plugin anyways
114
-        EEH_Activation::verify_default_pages_exist();
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets the database schema and creates folders. This should
120
-     * be called on plugin activation and reactivation
121
-     *
122
-     * @return boolean success, whether the database and folders are setup properly
123
-     * @throws \EE_Error
124
-     */
125
-    public static function initialize_db_and_folders()
126
-    {
127
-        $good_filesystem = EEH_Activation::create_upload_directories();
128
-        $good_db         = EEH_Activation::create_database_tables();
129
-        return $good_filesystem && $good_db;
130
-    }
131
-
132
-
133
-    /**
134
-     * assuming we have an up-to-date database schema, this will populate it
135
-     * with default and initial data. This should be called
136
-     * upon activation of a new plugin, reactivation, and at the end
137
-     * of running migration scripts
138
-     *
139
-     * @throws \EE_Error
140
-     */
141
-    public static function initialize_db_content()
142
-    {
143
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
144
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
145
-            return;
146
-        }
147
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
148
-
149
-        EEH_Activation::initialize_system_questions();
150
-        EEH_Activation::insert_default_status_codes();
151
-        EEH_Activation::generate_default_message_templates();
152
-        EEH_Activation::create_no_ticket_prices_array();
153
-
154
-        EEH_Activation::validate_messages_system();
155
-        EEH_Activation::insert_default_payment_methods();
156
-        //in case we've
157
-        EEH_Activation::remove_cron_tasks();
158
-        EEH_Activation::create_cron_tasks();
159
-        // remove all TXN locks since that is being done via extra meta now
160
-        delete_option('ee_locked_transactions');
161
-        //also, check for CAF default db content
162
-        do_action('AHEE__EEH_Activation__initialize_db_content');
163
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
164
-        //which users really won't care about on initial activation
165
-        EE_Error::overwrite_success();
166
-    }
167
-
168
-
169
-    /**
170
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
171
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
172
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
173
-     * (null)
174
-     *
175
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
176
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
177
-     * @return array
178
-     * @throws \EE_Error
179
-     */
180
-    public static function get_cron_tasks($which_to_include)
181
-    {
182
-        $cron_tasks = apply_filters(
183
-            'FHEE__EEH_Activation__get_cron_tasks',
184
-            array(
185
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
20
+	/**
21
+	 * constant used to indicate a cron task is no longer in use
22
+	 */
23
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
24
+
25
+	/**
26
+	 * option name that will indicate whether or not we still
27
+	 * need to create EE's folders in the uploads directory
28
+	 * (because if EE was installed without file system access,
29
+	 * we need to request credentials before we can create them)
30
+	 */
31
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
32
+
33
+	/**
34
+	 * WP_User->ID
35
+	 *
36
+	 * @var int
37
+	 */
38
+	private static $_default_creator_id;
39
+
40
+	/**
41
+	 * indicates whether or not we've already verified core's default data during this request,
42
+	 * because after migrations are done, any addons activated while in maintenance mode
43
+	 * will want to setup their own default data, and they might hook into core's default data
44
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
45
+	 * This prevents doing that for EVERY single addon.
46
+	 *
47
+	 * @var boolean
48
+	 */
49
+	protected static $_initialized_db_content_already_in_this_request = false;
50
+
51
+	/**
52
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
53
+	 */
54
+	private static $table_analysis;
55
+
56
+	/**
57
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
58
+	 */
59
+	private static $table_manager;
60
+
61
+
62
+	/**
63
+	 * @return \EventEspresso\core\services\database\TableAnalysis
64
+	 */
65
+	public static function getTableAnalysis()
66
+	{
67
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
68
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
69
+		}
70
+		return self::$table_analysis;
71
+	}
72
+
73
+
74
+	/**
75
+	 * @return \EventEspresso\core\services\database\TableManager
76
+	 */
77
+	public static function getTableManager()
78
+	{
79
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
80
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
81
+		}
82
+		return self::$table_manager;
83
+	}
84
+
85
+
86
+	/**
87
+	 *    _ensure_table_name_has_prefix
88
+	 *
89
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
90
+	 * @access     public
91
+	 * @static
92
+	 * @param $table_name
93
+	 * @return string
94
+	 */
95
+	public static function ensure_table_name_has_prefix($table_name)
96
+	{
97
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
98
+	}
99
+
100
+
101
+	/**
102
+	 *    system_initialization
103
+	 *    ensures the EE configuration settings are loaded with at least default options set
104
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
105
+	 *
106
+	 * @access public
107
+	 * @static
108
+	 * @return void
109
+	 */
110
+	public static function system_initialization()
111
+	{
112
+		EEH_Activation::reset_and_update_config();
113
+		//which is fired BEFORE activation of plugin anyways
114
+		EEH_Activation::verify_default_pages_exist();
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets the database schema and creates folders. This should
120
+	 * be called on plugin activation and reactivation
121
+	 *
122
+	 * @return boolean success, whether the database and folders are setup properly
123
+	 * @throws \EE_Error
124
+	 */
125
+	public static function initialize_db_and_folders()
126
+	{
127
+		$good_filesystem = EEH_Activation::create_upload_directories();
128
+		$good_db         = EEH_Activation::create_database_tables();
129
+		return $good_filesystem && $good_db;
130
+	}
131
+
132
+
133
+	/**
134
+	 * assuming we have an up-to-date database schema, this will populate it
135
+	 * with default and initial data. This should be called
136
+	 * upon activation of a new plugin, reactivation, and at the end
137
+	 * of running migration scripts
138
+	 *
139
+	 * @throws \EE_Error
140
+	 */
141
+	public static function initialize_db_content()
142
+	{
143
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
144
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
145
+			return;
146
+		}
147
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
148
+
149
+		EEH_Activation::initialize_system_questions();
150
+		EEH_Activation::insert_default_status_codes();
151
+		EEH_Activation::generate_default_message_templates();
152
+		EEH_Activation::create_no_ticket_prices_array();
153
+
154
+		EEH_Activation::validate_messages_system();
155
+		EEH_Activation::insert_default_payment_methods();
156
+		//in case we've
157
+		EEH_Activation::remove_cron_tasks();
158
+		EEH_Activation::create_cron_tasks();
159
+		// remove all TXN locks since that is being done via extra meta now
160
+		delete_option('ee_locked_transactions');
161
+		//also, check for CAF default db content
162
+		do_action('AHEE__EEH_Activation__initialize_db_content');
163
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
164
+		//which users really won't care about on initial activation
165
+		EE_Error::overwrite_success();
166
+	}
167
+
168
+
169
+	/**
170
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
171
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
172
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
173
+	 * (null)
174
+	 *
175
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
176
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
177
+	 * @return array
178
+	 * @throws \EE_Error
179
+	 */
180
+	public static function get_cron_tasks($which_to_include)
181
+	{
182
+		$cron_tasks = apply_filters(
183
+			'FHEE__EEH_Activation__get_cron_tasks',
184
+			array(
185
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
186 186
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
187
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
188
-                //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
189
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
190
-            )
191
-        );
192
-        if ($which_to_include === 'old') {
193
-            $cron_tasks = array_filter(
194
-                $cron_tasks,
195
-                function ($value) {
196
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
197
-                }
198
-            );
199
-        } elseif ($which_to_include === 'current') {
200
-            $cron_tasks = array_filter($cron_tasks);
201
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
202
-            throw new EE_Error(
203
-                sprintf(
204
-                    __(
205
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
206
-                        'event_espresso'
207
-                    ),
208
-                    $which_to_include
209
-                )
210
-            );
211
-        }
212
-        return $cron_tasks;
213
-    }
214
-
215
-
216
-    /**
217
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
218
-     *
219
-     * @throws \EE_Error
220
-     */
221
-    public static function create_cron_tasks()
222
-    {
223
-
224
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
225
-            if (! wp_next_scheduled($hook_name)) {
226
-                /**
227
-                 * This allows client code to define the initial start timestamp for this schedule.
228
-                 */
229
-                if (is_array($frequency)
230
-                    && count($frequency) === 2
231
-                    && isset($frequency[0], $frequency[1])
232
-                ) {
233
-                    $start_timestamp = $frequency[0];
234
-                    $frequency = $frequency[1];
235
-                } else {
236
-                    $start_timestamp = time();
237
-                }
238
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
239
-            }
240
-        }
241
-
242
-    }
243
-
244
-
245
-    /**
246
-     * Remove the currently-existing and now-removed cron tasks.
247
-     *
248
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
249
-     * @throws \EE_Error
250
-     */
251
-    public static function remove_cron_tasks($remove_all = true)
252
-    {
253
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
254
-        $crons                = _get_cron_array();
255
-        $crons                = is_array($crons) ? $crons : array();
256
-        /* reminder of what $crons look like:
187
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
188
+				//there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
189
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
190
+			)
191
+		);
192
+		if ($which_to_include === 'old') {
193
+			$cron_tasks = array_filter(
194
+				$cron_tasks,
195
+				function ($value) {
196
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
197
+				}
198
+			);
199
+		} elseif ($which_to_include === 'current') {
200
+			$cron_tasks = array_filter($cron_tasks);
201
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
202
+			throw new EE_Error(
203
+				sprintf(
204
+					__(
205
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
206
+						'event_espresso'
207
+					),
208
+					$which_to_include
209
+				)
210
+			);
211
+		}
212
+		return $cron_tasks;
213
+	}
214
+
215
+
216
+	/**
217
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
218
+	 *
219
+	 * @throws \EE_Error
220
+	 */
221
+	public static function create_cron_tasks()
222
+	{
223
+
224
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
225
+			if (! wp_next_scheduled($hook_name)) {
226
+				/**
227
+				 * This allows client code to define the initial start timestamp for this schedule.
228
+				 */
229
+				if (is_array($frequency)
230
+					&& count($frequency) === 2
231
+					&& isset($frequency[0], $frequency[1])
232
+				) {
233
+					$start_timestamp = $frequency[0];
234
+					$frequency = $frequency[1];
235
+				} else {
236
+					$start_timestamp = time();
237
+				}
238
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
239
+			}
240
+		}
241
+
242
+	}
243
+
244
+
245
+	/**
246
+	 * Remove the currently-existing and now-removed cron tasks.
247
+	 *
248
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
249
+	 * @throws \EE_Error
250
+	 */
251
+	public static function remove_cron_tasks($remove_all = true)
252
+	{
253
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
254
+		$crons                = _get_cron_array();
255
+		$crons                = is_array($crons) ? $crons : array();
256
+		/* reminder of what $crons look like:
257 257
          * Top-level keys are timestamps, and their values are arrays.
258 258
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
259 259
          * and their values are arrays.
@@ -270,912 +270,912 @@  discard block
 block discarded – undo
270 270
          *					...
271 271
          *      ...
272 272
          */
273
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
274
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
275
-            if (is_array($hooks_to_fire_at_time)) {
276
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
277
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
278
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
279
-                    ) {
280
-                        unset($crons[$timestamp][$hook_name]);
281
-                    }
282
-                }
283
-                //also take care of any empty cron timestamps.
284
-                if (empty($hooks_to_fire_at_time)) {
285
-                    unset($crons[$timestamp]);
286
-                }
287
-            }
288
-        }
289
-        _set_cron_array($crons);
290
-    }
291
-
292
-
293
-    /**
294
-     *    CPT_initialization
295
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
296
-     *
297
-     * @access public
298
-     * @static
299
-     * @return void
300
-     */
301
-    public static function CPT_initialization()
302
-    {
303
-        // register Custom Post Types
304
-        EE_Registry::instance()->load_core('Register_CPTs');
305
-        flush_rewrite_rules();
306
-    }
307
-
308
-
309
-
310
-    /**
311
-     *    reset_and_update_config
312
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
313
-     * If there is old calendar config data saved, then it will get converted on activation.
314
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
315
-     *
316
-     * @access public
317
-     * @static
318
-     * @return void
319
-     */
320
-    public static function reset_and_update_config()
321
-    {
322
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
323
-        add_filter(
324
-            'FHEE__EE_Config___load_core_config__config_settings',
325
-            array('EEH_Activation', 'migrate_old_config_data'),
326
-            10,
327
-            3
328
-        );
329
-        //EE_Config::reset();
330
-        if (! EE_Config::logging_enabled()) {
331
-            delete_option(EE_Config::LOG_NAME);
332
-        }
333
-    }
334
-
335
-
336
-    /**
337
-     *    load_calendar_config
338
-     *
339
-     * @access    public
340
-     * @return    void
341
-     */
342
-    public static function load_calendar_config()
343
-    {
344
-        // grab array of all plugin folders and loop thru it
345
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
346
-        if (empty($plugins)) {
347
-            return;
348
-        }
349
-        foreach ($plugins as $plugin_path) {
350
-            // grab plugin folder name from path
351
-            $plugin = basename($plugin_path);
352
-            // drill down to Espresso plugins
353
-            // then to calendar related plugins
354
-            if (
355
-                strpos($plugin, 'espresso') !== false
356
-                || strpos($plugin, 'Espresso') !== false
357
-                || strpos($plugin, 'ee4') !== false
358
-                || strpos($plugin, 'EE4') !== false
359
-                || strpos($plugin, 'calendar') !== false
360
-            ) {
361
-                // this is what we are looking for
362
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
363
-                // does it exist in this folder ?
364
-                if (is_readable($calendar_config)) {
365
-                    // YEAH! let's load it
366
-                    require_once($calendar_config);
367
-                }
368
-            }
369
-        }
370
-    }
371
-
372
-
373
-
374
-    /**
375
-     *    _migrate_old_config_data
376
-     *
377
-     * @access    public
378
-     * @param array|stdClass $settings
379
-     * @param string         $config
380
-     * @param \EE_Config     $EE_Config
381
-     * @return \stdClass
382
-     */
383
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
384
-    {
385
-        $convert_from_array = array('addons');
386
-        // in case old settings were saved as an array
387
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
388
-            // convert existing settings to an object
389
-            $config_array = $settings;
390
-            $settings = new stdClass();
391
-            foreach ($config_array as $key => $value) {
392
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
393
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
394
-                } else {
395
-                    $settings->{$key} = $value;
396
-                }
397
-            }
398
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
399
-        }
400
-        return $settings;
401
-    }
402
-
403
-
404
-    /**
405
-     * deactivate_event_espresso
406
-     *
407
-     * @access public
408
-     * @static
409
-     * @return void
410
-     */
411
-    public static function deactivate_event_espresso()
412
-    {
413
-        // check permissions
414
-        if (current_user_can('activate_plugins')) {
415
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
416
-        }
417
-    }
418
-
419
-
420
-
421
-
422
-
423
-    /**
424
-     * verify_default_pages_exist
425
-     *
426
-     * @access public
427
-     * @static
428
-     * @return void
429
-     */
430
-    public static function verify_default_pages_exist()
431
-    {
432
-        $critical_page_problem = false;
433
-        $critical_pages = array(
434
-            array(
435
-                'id'   => 'reg_page_id',
436
-                'name' => __('Registration Checkout', 'event_espresso'),
437
-                'post' => null,
438
-                'code' => 'ESPRESSO_CHECKOUT',
439
-            ),
440
-            array(
441
-                'id'   => 'txn_page_id',
442
-                'name' => __('Transactions', 'event_espresso'),
443
-                'post' => null,
444
-                'code' => 'ESPRESSO_TXN_PAGE',
445
-            ),
446
-            array(
447
-                'id'   => 'thank_you_page_id',
448
-                'name' => __('Thank You', 'event_espresso'),
449
-                'post' => null,
450
-                'code' => 'ESPRESSO_THANK_YOU',
451
-            ),
452
-            array(
453
-                'id'   => 'cancel_page_id',
454
-                'name' => __('Registration Cancelled', 'event_espresso'),
455
-                'post' => null,
456
-                'code' => 'ESPRESSO_CANCELLED',
457
-            ),
458
-        );
459
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
460
-        foreach ($critical_pages as $critical_page) {
461
-            // is critical page ID set in config ?
462
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
463
-                // attempt to find post by ID
464
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
465
-            }
466
-            // no dice?
467
-            if ($critical_page['post'] === null) {
468
-                // attempt to find post by title
469
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
470
-                // still nothing?
471
-                if ($critical_page['post'] === null) {
472
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
473
-                    // REALLY? Still nothing ??!?!?
474
-                    if ($critical_page['post'] === null) {
475
-                        $msg = __(
476
-                            'The Event Espresso critical page configuration settings could not be updated.',
477
-                            'event_espresso'
478
-                        );
479
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
480
-                        break;
481
-                    }
482
-                }
483
-            }
484
-            // check that Post ID matches critical page ID in config
485
-            if (
486
-                isset($critical_page['post']->ID)
487
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
488
-            ) {
489
-                //update Config with post ID
490
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
491
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
492
-                    $msg = __(
493
-                        'The Event Espresso critical page configuration settings could not be updated.',
494
-                        'event_espresso'
495
-                    );
496
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
497
-                }
498
-            }
499
-            $critical_page_problem =
500
-                ! isset($critical_page['post']->post_status)
501
-                || $critical_page['post']->post_status !== 'publish'
502
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
503
-                    ? true
504
-                    : $critical_page_problem;
505
-        }
506
-        if ($critical_page_problem) {
507
-            $msg = sprintf(
508
-                __(
509
-                    'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
510
-                    'event_espresso'
511
-                ),
512
-                '<a href="'
513
-                . admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
514
-                . '">'
515
-                . __('Event Espresso Critical Pages Settings', 'event_espresso')
516
-                . '</a>'
517
-            );
518
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
519
-        }
520
-        if (EE_Error::has_notices()) {
521
-            EE_Error::get_notices(false, true, true);
522
-        }
523
-    }
524
-
525
-
526
-
527
-    /**
528
-     * Returns the first post which uses the specified shortcode
529
-     *
530
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
531
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
532
-     *                             "[ESPRESSO_THANK_YOU"
533
-     *                             (we don't search for the closing shortcode bracket because they might have added
534
-     *                             parameter to the shortcode
535
-     * @return WP_Post or NULl
536
-     */
537
-    public static function get_page_by_ee_shortcode($ee_shortcode)
538
-    {
539
-        global $wpdb;
540
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
541
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
542
-        if ($post_id) {
543
-            return get_post($post_id);
544
-        } else {
545
-            return null;
546
-        }
547
-    }
548
-
549
-
550
-    /**
551
-     *    This function generates a post for critical espresso pages
552
-     *
553
-     * @access public
554
-     * @static
555
-     * @param array $critical_page
556
-     * @return array
557
-     */
558
-    public static function create_critical_page($critical_page)
559
-    {
560
-
561
-        $post_args = array(
562
-            'post_title'     => $critical_page['name'],
563
-            'post_status'    => 'publish',
564
-            'post_type'      => 'page',
565
-            'comment_status' => 'closed',
566
-            'post_content'   => '[' . $critical_page['code'] . ']',
567
-        );
568
-
569
-        $post_id = wp_insert_post($post_args);
570
-        if (! $post_id) {
571
-            $msg = sprintf(
572
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
573
-                $critical_page['name']
574
-            );
575
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
576
-            return $critical_page;
577
-        }
578
-        // get newly created post's details
579
-        if (! $critical_page['post'] = get_post($post_id)) {
580
-            $msg = sprintf(
581
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
582
-                $critical_page['name']
583
-            );
584
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
585
-        }
586
-
587
-        return $critical_page;
588
-
589
-    }
590
-
591
-
592
-
593
-
594
-    /**
595
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
596
-     * The role being used to check is filterable.
597
-     *
598
-     * @since  4.6.0
599
-     * @global WPDB $wpdb
600
-     * @return mixed null|int WP_user ID or NULL
601
-     */
602
-    public static function get_default_creator_id()
603
-    {
604
-        global $wpdb;
605
-        if ( ! empty(self::$_default_creator_id)) {
606
-            return self::$_default_creator_id;
607
-        }/**/
608
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
609
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
610
-        $pre_filtered_id = apply_filters(
611
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
612
-            false,
613
-            $role_to_check
614
-        );
615
-        if ($pre_filtered_id !== false) {
616
-            return (int)$pre_filtered_id;
617
-        }
618
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
619
-        $query = $wpdb->prepare(
620
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
621
-            '%' . $role_to_check . '%'
622
-        );
623
-        $user_id = $wpdb->get_var($query);
624
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
625
-        if ($user_id && (int)$user_id) {
626
-            self::$_default_creator_id = (int)$user_id;
627
-            return self::$_default_creator_id;
628
-        } else {
629
-            return null;
630
-        }
631
-    }
632
-
633
-
634
-
635
-    /**
636
-     * used by EE and EE addons during plugin activation to create tables.
637
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
638
-     * but includes extra logic regarding activations.
639
-     *
640
-     * @access public
641
-     * @static
642
-     * @param string  $table_name              without the $wpdb->prefix
643
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
644
-     *                                         table query)
645
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
646
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
647
-     *                                         and new once this function is done (ie, you really do want to CREATE a
648
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
649
-     *                                         you just want to verify the table exists and matches this definition
650
-     *                                         (and if it HAS data in it you want to leave it be)
651
-     * @return void
652
-     * @throws EE_Error if there are database errors
653
-     */
654
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
655
-    {
656
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
657
-            return;
658
-        }
659
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
660
-        if ( ! function_exists('dbDelta')) {
661
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
662
-        }
663
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
664
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
665
-        // do we need to first delete an existing version of this table ?
666
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
667
-            // ok, delete the table... but ONLY if it's empty
668
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
669
-            // table is NOT empty, are you SURE you want to delete this table ???
670
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
671
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
672
-            } else if ( ! $deleted_safely) {
673
-                // so we should be more cautious rather than just dropping tables so easily
674
-                error_log(
675
-                    sprintf(
676
-                        __(
677
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
678
-                            'event_espresso'
679
-                        ),
680
-                        $wp_table_name,
681
-                        '<br/>',
682
-                        'espresso_db_update'
683
-                    )
684
-                );
685
-            }
686
-        }
687
-        $engine = str_replace('ENGINE=', '', $engine);
688
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
689
-    }
690
-
691
-
692
-
693
-    /**
694
-     *    add_column_if_it_doesn't_exist
695
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
696
-     *
697
-     * @access     public
698
-     * @static
699
-     * @deprecated instead use TableManager::addColumn()
700
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
701
-     * @param string $column_name
702
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
703
-     *                            'VARCHAR(10)'
704
-     * @return bool|int
705
-     */
706
-    public static function add_column_if_it_doesnt_exist(
707
-        $table_name,
708
-        $column_name,
709
-        $column_info = 'INT UNSIGNED NOT NULL'
710
-    ) {
711
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
712
-    }
713
-
714
-
715
-    /**
716
-     * get_fields_on_table
717
-     * Gets all the fields on the database table.
718
-     *
719
-     * @access     public
720
-     * @deprecated instead use TableManager::getTableColumns()
721
-     * @static
722
-     * @param string $table_name , without prefixed $wpdb->prefix
723
-     * @return array of database column names
724
-     */
725
-    public static function get_fields_on_table($table_name = null)
726
-    {
727
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
728
-    }
729
-
730
-
731
-    /**
732
-     * db_table_is_empty
733
-     *
734
-     * @access     public\
735
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
736
-     * @static
737
-     * @param string $table_name
738
-     * @return bool
739
-     */
740
-    public static function db_table_is_empty($table_name)
741
-    {
742
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
743
-    }
744
-
745
-
746
-    /**
747
-     * delete_db_table_if_empty
748
-     *
749
-     * @access public
750
-     * @static
751
-     * @param string $table_name
752
-     * @return bool | int
753
-     */
754
-    public static function delete_db_table_if_empty($table_name)
755
-    {
756
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
757
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
758
-        }
759
-        return false;
760
-    }
761
-
762
-
763
-    /**
764
-     * delete_unused_db_table
765
-     *
766
-     * @access     public
767
-     * @static
768
-     * @deprecated instead use TableManager::dropTable()
769
-     * @param string $table_name
770
-     * @return bool | int
771
-     */
772
-    public static function delete_unused_db_table($table_name)
773
-    {
774
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
775
-    }
776
-
777
-
778
-    /**
779
-     * drop_index
780
-     *
781
-     * @access     public
782
-     * @static
783
-     * @deprecated instead use TableManager::dropIndex()
784
-     * @param string $table_name
785
-     * @param string $index_name
786
-     * @return bool | int
787
-     */
788
-    public static function drop_index($table_name, $index_name)
789
-    {
790
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
791
-    }
792
-
793
-
794
-
795
-    /**
796
-     * create_database_tables
797
-     *
798
-     * @access public
799
-     * @static
800
-     * @throws EE_Error
801
-     * @return boolean success (whether database is setup properly or not)
802
-     */
803
-    public static function create_database_tables()
804
-    {
805
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
806
-        //find the migration script that sets the database to be compatible with the code
807
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
808
-        if ($dms_name) {
809
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
810
-            $current_data_migration_script->set_migrating(false);
811
-            $current_data_migration_script->schema_changes_before_migration();
812
-            $current_data_migration_script->schema_changes_after_migration();
813
-            if ($current_data_migration_script->get_errors()) {
814
-                if (WP_DEBUG) {
815
-                    foreach ($current_data_migration_script->get_errors() as $error) {
816
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
817
-                    }
818
-                } else {
819
-                    EE_Error::add_error(
820
-                        __(
821
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
273
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
274
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
275
+			if (is_array($hooks_to_fire_at_time)) {
276
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
277
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
278
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
279
+					) {
280
+						unset($crons[$timestamp][$hook_name]);
281
+					}
282
+				}
283
+				//also take care of any empty cron timestamps.
284
+				if (empty($hooks_to_fire_at_time)) {
285
+					unset($crons[$timestamp]);
286
+				}
287
+			}
288
+		}
289
+		_set_cron_array($crons);
290
+	}
291
+
292
+
293
+	/**
294
+	 *    CPT_initialization
295
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
296
+	 *
297
+	 * @access public
298
+	 * @static
299
+	 * @return void
300
+	 */
301
+	public static function CPT_initialization()
302
+	{
303
+		// register Custom Post Types
304
+		EE_Registry::instance()->load_core('Register_CPTs');
305
+		flush_rewrite_rules();
306
+	}
307
+
308
+
309
+
310
+	/**
311
+	 *    reset_and_update_config
312
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
313
+	 * If there is old calendar config data saved, then it will get converted on activation.
314
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
315
+	 *
316
+	 * @access public
317
+	 * @static
318
+	 * @return void
319
+	 */
320
+	public static function reset_and_update_config()
321
+	{
322
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
323
+		add_filter(
324
+			'FHEE__EE_Config___load_core_config__config_settings',
325
+			array('EEH_Activation', 'migrate_old_config_data'),
326
+			10,
327
+			3
328
+		);
329
+		//EE_Config::reset();
330
+		if (! EE_Config::logging_enabled()) {
331
+			delete_option(EE_Config::LOG_NAME);
332
+		}
333
+	}
334
+
335
+
336
+	/**
337
+	 *    load_calendar_config
338
+	 *
339
+	 * @access    public
340
+	 * @return    void
341
+	 */
342
+	public static function load_calendar_config()
343
+	{
344
+		// grab array of all plugin folders and loop thru it
345
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
346
+		if (empty($plugins)) {
347
+			return;
348
+		}
349
+		foreach ($plugins as $plugin_path) {
350
+			// grab plugin folder name from path
351
+			$plugin = basename($plugin_path);
352
+			// drill down to Espresso plugins
353
+			// then to calendar related plugins
354
+			if (
355
+				strpos($plugin, 'espresso') !== false
356
+				|| strpos($plugin, 'Espresso') !== false
357
+				|| strpos($plugin, 'ee4') !== false
358
+				|| strpos($plugin, 'EE4') !== false
359
+				|| strpos($plugin, 'calendar') !== false
360
+			) {
361
+				// this is what we are looking for
362
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
363
+				// does it exist in this folder ?
364
+				if (is_readable($calendar_config)) {
365
+					// YEAH! let's load it
366
+					require_once($calendar_config);
367
+				}
368
+			}
369
+		}
370
+	}
371
+
372
+
373
+
374
+	/**
375
+	 *    _migrate_old_config_data
376
+	 *
377
+	 * @access    public
378
+	 * @param array|stdClass $settings
379
+	 * @param string         $config
380
+	 * @param \EE_Config     $EE_Config
381
+	 * @return \stdClass
382
+	 */
383
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
384
+	{
385
+		$convert_from_array = array('addons');
386
+		// in case old settings were saved as an array
387
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
388
+			// convert existing settings to an object
389
+			$config_array = $settings;
390
+			$settings = new stdClass();
391
+			foreach ($config_array as $key => $value) {
392
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
393
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
394
+				} else {
395
+					$settings->{$key} = $value;
396
+				}
397
+			}
398
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
399
+		}
400
+		return $settings;
401
+	}
402
+
403
+
404
+	/**
405
+	 * deactivate_event_espresso
406
+	 *
407
+	 * @access public
408
+	 * @static
409
+	 * @return void
410
+	 */
411
+	public static function deactivate_event_espresso()
412
+	{
413
+		// check permissions
414
+		if (current_user_can('activate_plugins')) {
415
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
416
+		}
417
+	}
418
+
419
+
420
+
421
+
422
+
423
+	/**
424
+	 * verify_default_pages_exist
425
+	 *
426
+	 * @access public
427
+	 * @static
428
+	 * @return void
429
+	 */
430
+	public static function verify_default_pages_exist()
431
+	{
432
+		$critical_page_problem = false;
433
+		$critical_pages = array(
434
+			array(
435
+				'id'   => 'reg_page_id',
436
+				'name' => __('Registration Checkout', 'event_espresso'),
437
+				'post' => null,
438
+				'code' => 'ESPRESSO_CHECKOUT',
439
+			),
440
+			array(
441
+				'id'   => 'txn_page_id',
442
+				'name' => __('Transactions', 'event_espresso'),
443
+				'post' => null,
444
+				'code' => 'ESPRESSO_TXN_PAGE',
445
+			),
446
+			array(
447
+				'id'   => 'thank_you_page_id',
448
+				'name' => __('Thank You', 'event_espresso'),
449
+				'post' => null,
450
+				'code' => 'ESPRESSO_THANK_YOU',
451
+			),
452
+			array(
453
+				'id'   => 'cancel_page_id',
454
+				'name' => __('Registration Cancelled', 'event_espresso'),
455
+				'post' => null,
456
+				'code' => 'ESPRESSO_CANCELLED',
457
+			),
458
+		);
459
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
460
+		foreach ($critical_pages as $critical_page) {
461
+			// is critical page ID set in config ?
462
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
463
+				// attempt to find post by ID
464
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
465
+			}
466
+			// no dice?
467
+			if ($critical_page['post'] === null) {
468
+				// attempt to find post by title
469
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
470
+				// still nothing?
471
+				if ($critical_page['post'] === null) {
472
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
473
+					// REALLY? Still nothing ??!?!?
474
+					if ($critical_page['post'] === null) {
475
+						$msg = __(
476
+							'The Event Espresso critical page configuration settings could not be updated.',
477
+							'event_espresso'
478
+						);
479
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
480
+						break;
481
+					}
482
+				}
483
+			}
484
+			// check that Post ID matches critical page ID in config
485
+			if (
486
+				isset($critical_page['post']->ID)
487
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
488
+			) {
489
+				//update Config with post ID
490
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
491
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
492
+					$msg = __(
493
+						'The Event Espresso critical page configuration settings could not be updated.',
494
+						'event_espresso'
495
+					);
496
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
497
+				}
498
+			}
499
+			$critical_page_problem =
500
+				! isset($critical_page['post']->post_status)
501
+				|| $critical_page['post']->post_status !== 'publish'
502
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
503
+					? true
504
+					: $critical_page_problem;
505
+		}
506
+		if ($critical_page_problem) {
507
+			$msg = sprintf(
508
+				__(
509
+					'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
510
+					'event_espresso'
511
+				),
512
+				'<a href="'
513
+				. admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
514
+				. '">'
515
+				. __('Event Espresso Critical Pages Settings', 'event_espresso')
516
+				. '</a>'
517
+			);
518
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
519
+		}
520
+		if (EE_Error::has_notices()) {
521
+			EE_Error::get_notices(false, true, true);
522
+		}
523
+	}
524
+
525
+
526
+
527
+	/**
528
+	 * Returns the first post which uses the specified shortcode
529
+	 *
530
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
531
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
532
+	 *                             "[ESPRESSO_THANK_YOU"
533
+	 *                             (we don't search for the closing shortcode bracket because they might have added
534
+	 *                             parameter to the shortcode
535
+	 * @return WP_Post or NULl
536
+	 */
537
+	public static function get_page_by_ee_shortcode($ee_shortcode)
538
+	{
539
+		global $wpdb;
540
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
541
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
542
+		if ($post_id) {
543
+			return get_post($post_id);
544
+		} else {
545
+			return null;
546
+		}
547
+	}
548
+
549
+
550
+	/**
551
+	 *    This function generates a post for critical espresso pages
552
+	 *
553
+	 * @access public
554
+	 * @static
555
+	 * @param array $critical_page
556
+	 * @return array
557
+	 */
558
+	public static function create_critical_page($critical_page)
559
+	{
560
+
561
+		$post_args = array(
562
+			'post_title'     => $critical_page['name'],
563
+			'post_status'    => 'publish',
564
+			'post_type'      => 'page',
565
+			'comment_status' => 'closed',
566
+			'post_content'   => '[' . $critical_page['code'] . ']',
567
+		);
568
+
569
+		$post_id = wp_insert_post($post_args);
570
+		if (! $post_id) {
571
+			$msg = sprintf(
572
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
573
+				$critical_page['name']
574
+			);
575
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
576
+			return $critical_page;
577
+		}
578
+		// get newly created post's details
579
+		if (! $critical_page['post'] = get_post($post_id)) {
580
+			$msg = sprintf(
581
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
582
+				$critical_page['name']
583
+			);
584
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
585
+		}
586
+
587
+		return $critical_page;
588
+
589
+	}
590
+
591
+
592
+
593
+
594
+	/**
595
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
596
+	 * The role being used to check is filterable.
597
+	 *
598
+	 * @since  4.6.0
599
+	 * @global WPDB $wpdb
600
+	 * @return mixed null|int WP_user ID or NULL
601
+	 */
602
+	public static function get_default_creator_id()
603
+	{
604
+		global $wpdb;
605
+		if ( ! empty(self::$_default_creator_id)) {
606
+			return self::$_default_creator_id;
607
+		}/**/
608
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
609
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
610
+		$pre_filtered_id = apply_filters(
611
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
612
+			false,
613
+			$role_to_check
614
+		);
615
+		if ($pre_filtered_id !== false) {
616
+			return (int)$pre_filtered_id;
617
+		}
618
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
619
+		$query = $wpdb->prepare(
620
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
621
+			'%' . $role_to_check . '%'
622
+		);
623
+		$user_id = $wpdb->get_var($query);
624
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
625
+		if ($user_id && (int)$user_id) {
626
+			self::$_default_creator_id = (int)$user_id;
627
+			return self::$_default_creator_id;
628
+		} else {
629
+			return null;
630
+		}
631
+	}
632
+
633
+
634
+
635
+	/**
636
+	 * used by EE and EE addons during plugin activation to create tables.
637
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
638
+	 * but includes extra logic regarding activations.
639
+	 *
640
+	 * @access public
641
+	 * @static
642
+	 * @param string  $table_name              without the $wpdb->prefix
643
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
644
+	 *                                         table query)
645
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
646
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
647
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
648
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
649
+	 *                                         you just want to verify the table exists and matches this definition
650
+	 *                                         (and if it HAS data in it you want to leave it be)
651
+	 * @return void
652
+	 * @throws EE_Error if there are database errors
653
+	 */
654
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
655
+	{
656
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
657
+			return;
658
+		}
659
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
660
+		if ( ! function_exists('dbDelta')) {
661
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
662
+		}
663
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
664
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
665
+		// do we need to first delete an existing version of this table ?
666
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
667
+			// ok, delete the table... but ONLY if it's empty
668
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
669
+			// table is NOT empty, are you SURE you want to delete this table ???
670
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
671
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
672
+			} else if ( ! $deleted_safely) {
673
+				// so we should be more cautious rather than just dropping tables so easily
674
+				error_log(
675
+					sprintf(
676
+						__(
677
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
678
+							'event_espresso'
679
+						),
680
+						$wp_table_name,
681
+						'<br/>',
682
+						'espresso_db_update'
683
+					)
684
+				);
685
+			}
686
+		}
687
+		$engine = str_replace('ENGINE=', '', $engine);
688
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
689
+	}
690
+
691
+
692
+
693
+	/**
694
+	 *    add_column_if_it_doesn't_exist
695
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
696
+	 *
697
+	 * @access     public
698
+	 * @static
699
+	 * @deprecated instead use TableManager::addColumn()
700
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
701
+	 * @param string $column_name
702
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
703
+	 *                            'VARCHAR(10)'
704
+	 * @return bool|int
705
+	 */
706
+	public static function add_column_if_it_doesnt_exist(
707
+		$table_name,
708
+		$column_name,
709
+		$column_info = 'INT UNSIGNED NOT NULL'
710
+	) {
711
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
712
+	}
713
+
714
+
715
+	/**
716
+	 * get_fields_on_table
717
+	 * Gets all the fields on the database table.
718
+	 *
719
+	 * @access     public
720
+	 * @deprecated instead use TableManager::getTableColumns()
721
+	 * @static
722
+	 * @param string $table_name , without prefixed $wpdb->prefix
723
+	 * @return array of database column names
724
+	 */
725
+	public static function get_fields_on_table($table_name = null)
726
+	{
727
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
728
+	}
729
+
730
+
731
+	/**
732
+	 * db_table_is_empty
733
+	 *
734
+	 * @access     public\
735
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
736
+	 * @static
737
+	 * @param string $table_name
738
+	 * @return bool
739
+	 */
740
+	public static function db_table_is_empty($table_name)
741
+	{
742
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
743
+	}
744
+
745
+
746
+	/**
747
+	 * delete_db_table_if_empty
748
+	 *
749
+	 * @access public
750
+	 * @static
751
+	 * @param string $table_name
752
+	 * @return bool | int
753
+	 */
754
+	public static function delete_db_table_if_empty($table_name)
755
+	{
756
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
757
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
758
+		}
759
+		return false;
760
+	}
761
+
762
+
763
+	/**
764
+	 * delete_unused_db_table
765
+	 *
766
+	 * @access     public
767
+	 * @static
768
+	 * @deprecated instead use TableManager::dropTable()
769
+	 * @param string $table_name
770
+	 * @return bool | int
771
+	 */
772
+	public static function delete_unused_db_table($table_name)
773
+	{
774
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
775
+	}
776
+
777
+
778
+	/**
779
+	 * drop_index
780
+	 *
781
+	 * @access     public
782
+	 * @static
783
+	 * @deprecated instead use TableManager::dropIndex()
784
+	 * @param string $table_name
785
+	 * @param string $index_name
786
+	 * @return bool | int
787
+	 */
788
+	public static function drop_index($table_name, $index_name)
789
+	{
790
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
791
+	}
792
+
793
+
794
+
795
+	/**
796
+	 * create_database_tables
797
+	 *
798
+	 * @access public
799
+	 * @static
800
+	 * @throws EE_Error
801
+	 * @return boolean success (whether database is setup properly or not)
802
+	 */
803
+	public static function create_database_tables()
804
+	{
805
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
806
+		//find the migration script that sets the database to be compatible with the code
807
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
808
+		if ($dms_name) {
809
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
810
+			$current_data_migration_script->set_migrating(false);
811
+			$current_data_migration_script->schema_changes_before_migration();
812
+			$current_data_migration_script->schema_changes_after_migration();
813
+			if ($current_data_migration_script->get_errors()) {
814
+				if (WP_DEBUG) {
815
+					foreach ($current_data_migration_script->get_errors() as $error) {
816
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
817
+					}
818
+				} else {
819
+					EE_Error::add_error(
820
+						__(
821
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
822 822
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
823
-                            'event_espresso'
824
-                        )
825
-                    );
826
-                }
827
-                return false;
828
-            }
829
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
830
-        } else {
831
-            EE_Error::add_error(
832
-                __(
833
-                    'Could not determine most up-to-date data migration script from which to pull database schema
823
+							'event_espresso'
824
+						)
825
+					);
826
+				}
827
+				return false;
828
+			}
829
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
830
+		} else {
831
+			EE_Error::add_error(
832
+				__(
833
+					'Could not determine most up-to-date data migration script from which to pull database schema
834 834
                      structure. So database is probably not setup properly',
835
-                    'event_espresso'
836
-                ),
837
-                __FILE__,
838
-                __FUNCTION__,
839
-                __LINE__
840
-            );
841
-            return false;
842
-        }
843
-        return true;
844
-    }
845
-
846
-
847
-
848
-    /**
849
-     * initialize_system_questions
850
-     *
851
-     * @access public
852
-     * @static
853
-     * @return void
854
-     */
855
-    public static function initialize_system_questions()
856
-    {
857
-        // QUESTION GROUPS
858
-        global $wpdb;
859
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
860
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
861
-        // what we have
862
-        $question_groups = $wpdb->get_col($SQL);
863
-        // check the response
864
-        $question_groups = is_array($question_groups) ? $question_groups : array();
865
-        // what we should have
866
-        $QSG_systems = array(1, 2);
867
-        // loop thru what we should have and compare to what we have
868
-        foreach ($QSG_systems as $QSG_system) {
869
-            // reset values array
870
-            $QSG_values = array();
871
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
872
-            if (! in_array("$QSG_system", $question_groups)) {
873
-                // add it
874
-                switch ($QSG_system) {
875
-                    case 1:
876
-                        $QSG_values = array(
877
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
878
-                            'QSG_identifier'      => 'personal-information-' . time(),
879
-                            'QSG_desc'            => '',
880
-                            'QSG_order'           => 1,
881
-                            'QSG_show_group_name' => 1,
882
-                            'QSG_show_group_desc' => 1,
883
-                            'QSG_system'          => EEM_Question_Group::system_personal,
884
-                            'QSG_deleted'         => 0,
885
-                        );
886
-                        break;
887
-                    case 2:
888
-                        $QSG_values = array(
889
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
890
-                            'QSG_identifier'      => 'address-information-' . time(),
891
-                            'QSG_desc'            => '',
892
-                            'QSG_order'           => 2,
893
-                            'QSG_show_group_name' => 1,
894
-                            'QSG_show_group_desc' => 1,
895
-                            'QSG_system'          => EEM_Question_Group::system_address,
896
-                            'QSG_deleted'         => 0,
897
-                        );
898
-                        break;
899
-                }
900
-                // make sure we have some values before inserting them
901
-                if (! empty($QSG_values)) {
902
-                    // insert system question
903
-                    $wpdb->insert(
904
-                        $table_name,
905
-                        $QSG_values,
906
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
907
-                    );
908
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
909
-                }
910
-            }
911
-        }
912
-        // QUESTIONS
913
-        global $wpdb;
914
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
915
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
916
-        // what we have
917
-        $questions = $wpdb->get_col($SQL);
918
-        // what we should have
919
-        $QST_systems = array(
920
-            'fname',
921
-            'lname',
922
-            'email',
923
-            'address',
924
-            'address2',
925
-            'city',
926
-            'country',
927
-            'state',
928
-            'zip',
929
-            'phone',
930
-        );
931
-        $order_for_group_1 = 1;
932
-        $order_for_group_2 = 1;
933
-        // loop thru what we should have and compare to what we have
934
-        foreach ($QST_systems as $QST_system) {
935
-            // reset values array
936
-            $QST_values = array();
937
-            // if we don't have what we should have
938
-            if (! in_array($QST_system, $questions)) {
939
-                // add it
940
-                switch ($QST_system) {
941
-                    case 'fname':
942
-                        $QST_values = array(
943
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
944
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
945
-                            'QST_system'        => 'fname',
946
-                            'QST_type'          => 'TEXT',
947
-                            'QST_required'      => 1,
948
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
949
-                            'QST_order'         => 1,
950
-                            'QST_admin_only'    => 0,
951
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
952
-                            'QST_wp_user'       => self::get_default_creator_id(),
953
-                            'QST_deleted'       => 0,
954
-                        );
955
-                        break;
956
-                    case 'lname':
957
-                        $QST_values = array(
958
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
959
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
960
-                            'QST_system'        => 'lname',
961
-                            'QST_type'          => 'TEXT',
962
-                            'QST_required'      => 1,
963
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
964
-                            'QST_order'         => 2,
965
-                            'QST_admin_only'    => 0,
966
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
967
-                            'QST_wp_user'       => self::get_default_creator_id(),
968
-                            'QST_deleted'       => 0,
969
-                        );
970
-                        break;
971
-                    case 'email':
972
-                        $QST_values = array(
973
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
974
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
975
-                            'QST_system'        => 'email',
976
-                            'QST_type'          => 'EMAIL',
977
-                            'QST_required'      => 1,
978
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
979
-                            'QST_order'         => 3,
980
-                            'QST_admin_only'    => 0,
981
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
982
-                            'QST_wp_user'       => self::get_default_creator_id(),
983
-                            'QST_deleted'       => 0,
984
-                        );
985
-                        break;
986
-                    case 'address':
987
-                        $QST_values = array(
988
-                            'QST_display_text'  => __('Address', 'event_espresso'),
989
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
990
-                            'QST_system'        => 'address',
991
-                            'QST_type'          => 'TEXT',
992
-                            'QST_required'      => 0,
993
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
994
-                            'QST_order'         => 4,
995
-                            'QST_admin_only'    => 0,
996
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
997
-                            'QST_wp_user'       => self::get_default_creator_id(),
998
-                            'QST_deleted'       => 0,
999
-                        );
1000
-                        break;
1001
-                    case 'address2':
1002
-                        $QST_values = array(
1003
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1004
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1005
-                            'QST_system'        => 'address2',
1006
-                            'QST_type'          => 'TEXT',
1007
-                            'QST_required'      => 0,
1008
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1009
-                            'QST_order'         => 5,
1010
-                            'QST_admin_only'    => 0,
1011
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1012
-                            'QST_wp_user'       => self::get_default_creator_id(),
1013
-                            'QST_deleted'       => 0,
1014
-                        );
1015
-                        break;
1016
-                    case 'city':
1017
-                        $QST_values = array(
1018
-                            'QST_display_text'  => __('City', 'event_espresso'),
1019
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1020
-                            'QST_system'        => 'city',
1021
-                            'QST_type'          => 'TEXT',
1022
-                            'QST_required'      => 0,
1023
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1024
-                            'QST_order'         => 6,
1025
-                            'QST_admin_only'    => 0,
1026
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1027
-                            'QST_wp_user'       => self::get_default_creator_id(),
1028
-                            'QST_deleted'       => 0,
1029
-                        );
1030
-                        break;
1031
-                    case 'country':
1032
-                        $QST_values = array(
1033
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1034
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1035
-                            'QST_system'        => 'country',
1036
-                            'QST_type'          => 'COUNTRY',
1037
-                            'QST_required'      => 0,
1038
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1039
-                            'QST_order'         => 7,
1040
-                            'QST_admin_only'    => 0,
1041
-                            'QST_wp_user'       => self::get_default_creator_id(),
1042
-                            'QST_deleted'       => 0,
1043
-                        );
1044
-                        break;
1045
-                    case 'state':
1046
-                        $QST_values = array(
1047
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1048
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1049
-                            'QST_system'        => 'state',
1050
-                            'QST_type'          => 'STATE',
1051
-                            'QST_required'      => 0,
1052
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1053
-                            'QST_order'         => 8,
1054
-                            'QST_admin_only'    => 0,
1055
-                            'QST_wp_user'       => self::get_default_creator_id(),
1056
-                            'QST_deleted'       => 0,
1057
-                        );
1058
-                        break;
1059
-                    case 'zip':
1060
-                        $QST_values = array(
1061
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1062
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1063
-                            'QST_system'        => 'zip',
1064
-                            'QST_type'          => 'TEXT',
1065
-                            'QST_required'      => 0,
1066
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1067
-                            'QST_order'         => 9,
1068
-                            'QST_admin_only'    => 0,
1069
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1070
-                            'QST_wp_user'       => self::get_default_creator_id(),
1071
-                            'QST_deleted'       => 0,
1072
-                        );
1073
-                        break;
1074
-                    case 'phone':
1075
-                        $QST_values = array(
1076
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1077
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1078
-                            'QST_system'        => 'phone',
1079
-                            'QST_type'          => 'TEXT',
1080
-                            'QST_required'      => 0,
1081
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1082
-                            'QST_order'         => 10,
1083
-                            'QST_admin_only'    => 0,
1084
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1085
-                            'QST_wp_user'       => self::get_default_creator_id(),
1086
-                            'QST_deleted'       => 0,
1087
-                        );
1088
-                        break;
1089
-                }
1090
-                if (! empty($QST_values)) {
1091
-                    // insert system question
1092
-                    $wpdb->insert(
1093
-                        $table_name,
1094
-                        $QST_values,
1095
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1096
-                    );
1097
-                    $QST_ID = $wpdb->insert_id;
1098
-                    // QUESTION GROUP QUESTIONS
1099
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1100
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1101
-                    } else {
1102
-                        $system_question_we_want = EEM_Question_Group::system_address;
1103
-                    }
1104
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1105
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1106
-                    } else {
1107
-                        $id_col = EEM_Question_Group::instance()
1108
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1109
-                        if (is_array($id_col)) {
1110
-                            $QSG_ID = reset($id_col);
1111
-                        } else {
1112
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1113
-                            EE_Log::instance()->log(
1114
-                                __FILE__,
1115
-                                __FUNCTION__,
1116
-                                sprintf(
1117
-                                    __(
1118
-                                        'Could not associate question %1$s to a question group because no system question
835
+					'event_espresso'
836
+				),
837
+				__FILE__,
838
+				__FUNCTION__,
839
+				__LINE__
840
+			);
841
+			return false;
842
+		}
843
+		return true;
844
+	}
845
+
846
+
847
+
848
+	/**
849
+	 * initialize_system_questions
850
+	 *
851
+	 * @access public
852
+	 * @static
853
+	 * @return void
854
+	 */
855
+	public static function initialize_system_questions()
856
+	{
857
+		// QUESTION GROUPS
858
+		global $wpdb;
859
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
860
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
861
+		// what we have
862
+		$question_groups = $wpdb->get_col($SQL);
863
+		// check the response
864
+		$question_groups = is_array($question_groups) ? $question_groups : array();
865
+		// what we should have
866
+		$QSG_systems = array(1, 2);
867
+		// loop thru what we should have and compare to what we have
868
+		foreach ($QSG_systems as $QSG_system) {
869
+			// reset values array
870
+			$QSG_values = array();
871
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
872
+			if (! in_array("$QSG_system", $question_groups)) {
873
+				// add it
874
+				switch ($QSG_system) {
875
+					case 1:
876
+						$QSG_values = array(
877
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
878
+							'QSG_identifier'      => 'personal-information-' . time(),
879
+							'QSG_desc'            => '',
880
+							'QSG_order'           => 1,
881
+							'QSG_show_group_name' => 1,
882
+							'QSG_show_group_desc' => 1,
883
+							'QSG_system'          => EEM_Question_Group::system_personal,
884
+							'QSG_deleted'         => 0,
885
+						);
886
+						break;
887
+					case 2:
888
+						$QSG_values = array(
889
+							'QSG_name'            => __('Address Information', 'event_espresso'),
890
+							'QSG_identifier'      => 'address-information-' . time(),
891
+							'QSG_desc'            => '',
892
+							'QSG_order'           => 2,
893
+							'QSG_show_group_name' => 1,
894
+							'QSG_show_group_desc' => 1,
895
+							'QSG_system'          => EEM_Question_Group::system_address,
896
+							'QSG_deleted'         => 0,
897
+						);
898
+						break;
899
+				}
900
+				// make sure we have some values before inserting them
901
+				if (! empty($QSG_values)) {
902
+					// insert system question
903
+					$wpdb->insert(
904
+						$table_name,
905
+						$QSG_values,
906
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
907
+					);
908
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
909
+				}
910
+			}
911
+		}
912
+		// QUESTIONS
913
+		global $wpdb;
914
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
915
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
916
+		// what we have
917
+		$questions = $wpdb->get_col($SQL);
918
+		// what we should have
919
+		$QST_systems = array(
920
+			'fname',
921
+			'lname',
922
+			'email',
923
+			'address',
924
+			'address2',
925
+			'city',
926
+			'country',
927
+			'state',
928
+			'zip',
929
+			'phone',
930
+		);
931
+		$order_for_group_1 = 1;
932
+		$order_for_group_2 = 1;
933
+		// loop thru what we should have and compare to what we have
934
+		foreach ($QST_systems as $QST_system) {
935
+			// reset values array
936
+			$QST_values = array();
937
+			// if we don't have what we should have
938
+			if (! in_array($QST_system, $questions)) {
939
+				// add it
940
+				switch ($QST_system) {
941
+					case 'fname':
942
+						$QST_values = array(
943
+							'QST_display_text'  => __('First Name', 'event_espresso'),
944
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
945
+							'QST_system'        => 'fname',
946
+							'QST_type'          => 'TEXT',
947
+							'QST_required'      => 1,
948
+							'QST_required_text' => __('This field is required', 'event_espresso'),
949
+							'QST_order'         => 1,
950
+							'QST_admin_only'    => 0,
951
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
952
+							'QST_wp_user'       => self::get_default_creator_id(),
953
+							'QST_deleted'       => 0,
954
+						);
955
+						break;
956
+					case 'lname':
957
+						$QST_values = array(
958
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
959
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
960
+							'QST_system'        => 'lname',
961
+							'QST_type'          => 'TEXT',
962
+							'QST_required'      => 1,
963
+							'QST_required_text' => __('This field is required', 'event_espresso'),
964
+							'QST_order'         => 2,
965
+							'QST_admin_only'    => 0,
966
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
967
+							'QST_wp_user'       => self::get_default_creator_id(),
968
+							'QST_deleted'       => 0,
969
+						);
970
+						break;
971
+					case 'email':
972
+						$QST_values = array(
973
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
974
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
975
+							'QST_system'        => 'email',
976
+							'QST_type'          => 'EMAIL',
977
+							'QST_required'      => 1,
978
+							'QST_required_text' => __('This field is required', 'event_espresso'),
979
+							'QST_order'         => 3,
980
+							'QST_admin_only'    => 0,
981
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
982
+							'QST_wp_user'       => self::get_default_creator_id(),
983
+							'QST_deleted'       => 0,
984
+						);
985
+						break;
986
+					case 'address':
987
+						$QST_values = array(
988
+							'QST_display_text'  => __('Address', 'event_espresso'),
989
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
990
+							'QST_system'        => 'address',
991
+							'QST_type'          => 'TEXT',
992
+							'QST_required'      => 0,
993
+							'QST_required_text' => __('This field is required', 'event_espresso'),
994
+							'QST_order'         => 4,
995
+							'QST_admin_only'    => 0,
996
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
997
+							'QST_wp_user'       => self::get_default_creator_id(),
998
+							'QST_deleted'       => 0,
999
+						);
1000
+						break;
1001
+					case 'address2':
1002
+						$QST_values = array(
1003
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1004
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1005
+							'QST_system'        => 'address2',
1006
+							'QST_type'          => 'TEXT',
1007
+							'QST_required'      => 0,
1008
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1009
+							'QST_order'         => 5,
1010
+							'QST_admin_only'    => 0,
1011
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1012
+							'QST_wp_user'       => self::get_default_creator_id(),
1013
+							'QST_deleted'       => 0,
1014
+						);
1015
+						break;
1016
+					case 'city':
1017
+						$QST_values = array(
1018
+							'QST_display_text'  => __('City', 'event_espresso'),
1019
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1020
+							'QST_system'        => 'city',
1021
+							'QST_type'          => 'TEXT',
1022
+							'QST_required'      => 0,
1023
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1024
+							'QST_order'         => 6,
1025
+							'QST_admin_only'    => 0,
1026
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1027
+							'QST_wp_user'       => self::get_default_creator_id(),
1028
+							'QST_deleted'       => 0,
1029
+						);
1030
+						break;
1031
+					case 'country':
1032
+						$QST_values = array(
1033
+							'QST_display_text'  => __('Country', 'event_espresso'),
1034
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1035
+							'QST_system'        => 'country',
1036
+							'QST_type'          => 'COUNTRY',
1037
+							'QST_required'      => 0,
1038
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1039
+							'QST_order'         => 7,
1040
+							'QST_admin_only'    => 0,
1041
+							'QST_wp_user'       => self::get_default_creator_id(),
1042
+							'QST_deleted'       => 0,
1043
+						);
1044
+						break;
1045
+					case 'state':
1046
+						$QST_values = array(
1047
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1048
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1049
+							'QST_system'        => 'state',
1050
+							'QST_type'          => 'STATE',
1051
+							'QST_required'      => 0,
1052
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1053
+							'QST_order'         => 8,
1054
+							'QST_admin_only'    => 0,
1055
+							'QST_wp_user'       => self::get_default_creator_id(),
1056
+							'QST_deleted'       => 0,
1057
+						);
1058
+						break;
1059
+					case 'zip':
1060
+						$QST_values = array(
1061
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1062
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1063
+							'QST_system'        => 'zip',
1064
+							'QST_type'          => 'TEXT',
1065
+							'QST_required'      => 0,
1066
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1067
+							'QST_order'         => 9,
1068
+							'QST_admin_only'    => 0,
1069
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1070
+							'QST_wp_user'       => self::get_default_creator_id(),
1071
+							'QST_deleted'       => 0,
1072
+						);
1073
+						break;
1074
+					case 'phone':
1075
+						$QST_values = array(
1076
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1077
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1078
+							'QST_system'        => 'phone',
1079
+							'QST_type'          => 'TEXT',
1080
+							'QST_required'      => 0,
1081
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1082
+							'QST_order'         => 10,
1083
+							'QST_admin_only'    => 0,
1084
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1085
+							'QST_wp_user'       => self::get_default_creator_id(),
1086
+							'QST_deleted'       => 0,
1087
+						);
1088
+						break;
1089
+				}
1090
+				if (! empty($QST_values)) {
1091
+					// insert system question
1092
+					$wpdb->insert(
1093
+						$table_name,
1094
+						$QST_values,
1095
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1096
+					);
1097
+					$QST_ID = $wpdb->insert_id;
1098
+					// QUESTION GROUP QUESTIONS
1099
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1100
+						$system_question_we_want = EEM_Question_Group::system_personal;
1101
+					} else {
1102
+						$system_question_we_want = EEM_Question_Group::system_address;
1103
+					}
1104
+					if (isset($QSG_IDs[$system_question_we_want])) {
1105
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1106
+					} else {
1107
+						$id_col = EEM_Question_Group::instance()
1108
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1109
+						if (is_array($id_col)) {
1110
+							$QSG_ID = reset($id_col);
1111
+						} else {
1112
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1113
+							EE_Log::instance()->log(
1114
+								__FILE__,
1115
+								__FUNCTION__,
1116
+								sprintf(
1117
+									__(
1118
+										'Could not associate question %1$s to a question group because no system question
1119 1119
                                          group existed',
1120
-                                        'event_espresso'
1121
-                                    ),
1122
-                                    $QST_ID),
1123
-                                'error');
1124
-                            continue;
1125
-                        }
1126
-                    }
1127
-                    // add system questions to groups
1128
-                    $wpdb->insert(
1129
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1130
-                        array(
1131
-                            'QSG_ID'    => $QSG_ID,
1132
-                            'QST_ID'    => $QST_ID,
1133
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1134
-                        ),
1135
-                        array('%d', '%d', '%d')
1136
-                    );
1137
-                }
1138
-            }
1139
-        }
1140
-    }
1141
-
1142
-
1143
-    /**
1144
-     * Makes sure the default payment method (Invoice) is active.
1145
-     * This used to be done automatically as part of constructing the old gateways config
1146
-     *
1147
-     * @throws \EE_Error
1148
-     */
1149
-    public static function insert_default_payment_methods()
1150
-    {
1151
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1152
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1153
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1154
-        } else {
1155
-            EEM_Payment_Method::instance()->verify_button_urls();
1156
-        }
1157
-    }
1158
-
1159
-    /**
1160
-     * insert_default_status_codes
1161
-     *
1162
-     * @access public
1163
-     * @static
1164
-     * @return void
1165
-     */
1166
-    public static function insert_default_status_codes()
1167
-    {
1168
-
1169
-        global $wpdb;
1170
-
1171
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1172
-
1173
-            $table_name = EEM_Status::instance()->table();
1174
-
1175
-            $SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1176
-            $wpdb->query($SQL);
1177
-
1178
-            $SQL = "INSERT INTO $table_name
1120
+										'event_espresso'
1121
+									),
1122
+									$QST_ID),
1123
+								'error');
1124
+							continue;
1125
+						}
1126
+					}
1127
+					// add system questions to groups
1128
+					$wpdb->insert(
1129
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1130
+						array(
1131
+							'QSG_ID'    => $QSG_ID,
1132
+							'QST_ID'    => $QST_ID,
1133
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1134
+						),
1135
+						array('%d', '%d', '%d')
1136
+					);
1137
+				}
1138
+			}
1139
+		}
1140
+	}
1141
+
1142
+
1143
+	/**
1144
+	 * Makes sure the default payment method (Invoice) is active.
1145
+	 * This used to be done automatically as part of constructing the old gateways config
1146
+	 *
1147
+	 * @throws \EE_Error
1148
+	 */
1149
+	public static function insert_default_payment_methods()
1150
+	{
1151
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1152
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1153
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1154
+		} else {
1155
+			EEM_Payment_Method::instance()->verify_button_urls();
1156
+		}
1157
+	}
1158
+
1159
+	/**
1160
+	 * insert_default_status_codes
1161
+	 *
1162
+	 * @access public
1163
+	 * @static
1164
+	 * @return void
1165
+	 */
1166
+	public static function insert_default_status_codes()
1167
+	{
1168
+
1169
+		global $wpdb;
1170
+
1171
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1172
+
1173
+			$table_name = EEM_Status::instance()->table();
1174
+
1175
+			$SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1176
+			$wpdb->query($SQL);
1177
+
1178
+			$SQL = "INSERT INTO $table_name
1179 1179
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1180 1180
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1181 1181
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1215,521 +1215,521 @@  discard block
 block discarded – undo
1215 1215
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1216 1216
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1217 1217
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1218
-            $wpdb->query($SQL);
1219
-
1220
-        }
1221
-
1222
-    }
1223
-
1224
-
1225
-    /**
1226
-     * create_upload_directories
1227
-     * Creates folders in the uploads directory to facilitate addons and templates
1228
-     *
1229
-     * @access public
1230
-     * @static
1231
-     * @return boolean success of verifying upload directories exist
1232
-     */
1233
-    public static function create_upload_directories()
1234
-    {
1235
-        // Create the required folders
1236
-        $folders = array(
1237
-            EVENT_ESPRESSO_TEMPLATE_DIR,
1238
-            EVENT_ESPRESSO_GATEWAY_DIR,
1239
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1240
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1241
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1242
-        );
1243
-        foreach ($folders as $folder) {
1244
-            try {
1245
-                EEH_File::ensure_folder_exists_and_is_writable($folder);
1246
-                @ chmod($folder, 0755);
1247
-            } catch (EE_Error $e) {
1248
-                EE_Error::add_error(
1249
-                    sprintf(
1250
-                        __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1251
-                        $folder,
1252
-                        '<br />' . $e->getMessage()
1253
-                    ),
1254
-                    __FILE__, __FUNCTION__, __LINE__
1255
-                );
1256
-                //indicate we'll need to fix this later
1257
-                update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1258
-                return false;
1259
-            }
1260
-        }
1261
-        //just add the .htaccess file to the logs directory to begin with. Even if logging
1262
-        //is disabled, there might be activation errors recorded in there
1263
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1264
-        //remember EE's folders are all good
1265
-        delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1266
-        return true;
1267
-    }
1268
-
1269
-    /**
1270
-     * Whether the upload directories need to be fixed or not.
1271
-     * If EE is installed but filesystem access isn't initially available,
1272
-     * we need to get the user's filesystem credentials and THEN create them,
1273
-     * so there might be period of time when EE is installed but its
1274
-     * upload directories aren't available. This indicates such a state
1275
-     *
1276
-     * @return boolean
1277
-     */
1278
-    public static function upload_directories_incomplete()
1279
-    {
1280
-        return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1281
-    }
1282
-
1283
-
1284
-    /**
1285
-     * generate_default_message_templates
1286
-     *
1287
-     * @static
1288
-     * @throws EE_Error
1289
-     * @return bool     true means new templates were created.
1290
-     *                  false means no templates were created.
1291
-     *                  This is NOT an error flag. To check for errors you will want
1292
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1293
-     */
1294
-    public static function generate_default_message_templates()
1295
-    {
1296
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1297
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1298
-        /*
1218
+			$wpdb->query($SQL);
1219
+
1220
+		}
1221
+
1222
+	}
1223
+
1224
+
1225
+	/**
1226
+	 * create_upload_directories
1227
+	 * Creates folders in the uploads directory to facilitate addons and templates
1228
+	 *
1229
+	 * @access public
1230
+	 * @static
1231
+	 * @return boolean success of verifying upload directories exist
1232
+	 */
1233
+	public static function create_upload_directories()
1234
+	{
1235
+		// Create the required folders
1236
+		$folders = array(
1237
+			EVENT_ESPRESSO_TEMPLATE_DIR,
1238
+			EVENT_ESPRESSO_GATEWAY_DIR,
1239
+			EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1240
+			EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1241
+			EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1242
+		);
1243
+		foreach ($folders as $folder) {
1244
+			try {
1245
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1246
+				@ chmod($folder, 0755);
1247
+			} catch (EE_Error $e) {
1248
+				EE_Error::add_error(
1249
+					sprintf(
1250
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1251
+						$folder,
1252
+						'<br />' . $e->getMessage()
1253
+					),
1254
+					__FILE__, __FUNCTION__, __LINE__
1255
+				);
1256
+				//indicate we'll need to fix this later
1257
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1258
+				return false;
1259
+			}
1260
+		}
1261
+		//just add the .htaccess file to the logs directory to begin with. Even if logging
1262
+		//is disabled, there might be activation errors recorded in there
1263
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1264
+		//remember EE's folders are all good
1265
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1266
+		return true;
1267
+	}
1268
+
1269
+	/**
1270
+	 * Whether the upload directories need to be fixed or not.
1271
+	 * If EE is installed but filesystem access isn't initially available,
1272
+	 * we need to get the user's filesystem credentials and THEN create them,
1273
+	 * so there might be period of time when EE is installed but its
1274
+	 * upload directories aren't available. This indicates such a state
1275
+	 *
1276
+	 * @return boolean
1277
+	 */
1278
+	public static function upload_directories_incomplete()
1279
+	{
1280
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1281
+	}
1282
+
1283
+
1284
+	/**
1285
+	 * generate_default_message_templates
1286
+	 *
1287
+	 * @static
1288
+	 * @throws EE_Error
1289
+	 * @return bool     true means new templates were created.
1290
+	 *                  false means no templates were created.
1291
+	 *                  This is NOT an error flag. To check for errors you will want
1292
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1293
+	 */
1294
+	public static function generate_default_message_templates()
1295
+	{
1296
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1297
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1298
+		/*
1299 1299
          * This first method is taking care of ensuring any default messengers
1300 1300
          * that should be made active and have templates generated are done.
1301 1301
          */
1302
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1303
-            $message_resource_manager
1304
-        );
1305
-        /**
1306
-         * This method is verifying there are no NEW default message types
1307
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1308
-         */
1309
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1310
-            $message_resource_manager
1311
-        );
1312
-        //after all is done, let's persist these changes to the db.
1313
-        $message_resource_manager->update_has_activated_messengers_option();
1314
-        $message_resource_manager->update_active_messengers_option();
1315
-        // will return true if either of these are true.  Otherwise will return false.
1316
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1317
-    }
1318
-
1319
-
1320
-
1321
-    /**
1322
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1323
-     * @return array|bool
1324
-     * @throws \EE_Error
1325
-     */
1326
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1327
-        EE_Message_Resource_Manager $message_resource_manager
1328
-    ) {
1329
-        /** @type EE_messenger[] $active_messengers */
1330
-        $active_messengers = $message_resource_manager->active_messengers();
1331
-        $installed_message_types = $message_resource_manager->installed_message_types();
1332
-        $templates_created = false;
1333
-        foreach ($active_messengers as $active_messenger) {
1334
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1335
-            $default_message_type_names_to_activate = array();
1336
-            // looping through each default message type reported by the messenger
1337
-            // and setup the actual message types to activate.
1338
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1339
-                // if already active or has already been activated before we skip
1340
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1341
-                // we also skip if the message type is not installed.
1342
-                if (
1343
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1344
-                        $default_message_type_name_for_messenger,
1345
-                        $active_messenger->name
1346
-                    )
1347
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1348
-                        $active_messenger->name,
1349
-                        $default_message_type_name_for_messenger
1350
-                    )
1351
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1352
-                ) {
1353
-                    continue;
1354
-                }
1355
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1356
-            }
1357
-            //let's activate!
1358
-            $message_resource_manager->ensure_message_types_are_active(
1359
-                $default_message_type_names_to_activate,
1360
-                $active_messenger->name,
1361
-                false
1362
-            );
1363
-            //activate the templates for these message types
1364
-            if ( ! empty($default_message_type_names_to_activate)) {
1365
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1366
-                    $active_messenger->name,
1367
-                    $default_message_type_names_for_messenger,
1368
-                    '',
1369
-                    true
1370
-                );
1371
-            }
1372
-        }
1373
-        return $templates_created;
1374
-    }
1375
-
1376
-
1377
-
1378
-    /**
1379
-     * This will activate and generate default messengers and default message types for those messengers.
1380
-     *
1381
-     * @param EE_message_Resource_Manager $message_resource_manager
1382
-     * @return array|bool  True means there were default messengers and message type templates generated.
1383
-     *                     False means that there were no templates generated
1384
-     *                     (which could simply mean there are no default message types for a messenger).
1385
-     * @throws EE_Error
1386
-     */
1387
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1388
-        EE_Message_Resource_Manager $message_resource_manager
1389
-    ) {
1390
-        /** @type EE_messenger[] $messengers_to_generate */
1391
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1392
-        $installed_message_types = $message_resource_manager->installed_message_types();
1393
-        $templates_generated = false;
1394
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1395
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1396
-            //verify the default message types match an installed message type.
1397
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1398
-                if (
1399
-                    ! isset($installed_message_types[$name])
1400
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1401
-                        $name,
1402
-                        $messenger_to_generate->name
1403
-                    )
1404
-                ) {
1405
-                    unset($default_message_type_names_for_messenger[$key]);
1406
-                }
1407
-            }
1408
-            // in previous iterations, the active_messengers option in the db
1409
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1410
-            // This comment is left here just in case we discover that we _do_ need to update before
1411
-            // passing off to create templates (after the refactor is done).
1412
-            // @todo remove this comment when determined not necessary.
1413
-            $message_resource_manager->activate_messenger(
1414
-                $messenger_to_generate->name,
1415
-                $default_message_type_names_for_messenger,
1416
-                false
1417
-            );
1418
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1419
-            if ( ! empty($default_message_type_names_for_messenger)) {
1420
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1421
-                    $messenger_to_generate->name,
1422
-                    $default_message_type_names_for_messenger,
1423
-                    '',
1424
-                    true
1425
-                );
1426
-            }
1427
-        }
1428
-        return $templates_generated;
1429
-    }
1430
-
1431
-
1432
-    /**
1433
-     * This returns the default messengers to generate templates for on activation of EE.
1434
-     * It considers:
1435
-     * - whether a messenger is already active in the db.
1436
-     * - whether a messenger has been made active at any time in the past.
1437
-     *
1438
-     * @static
1439
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1440
-     * @return EE_messenger[]
1441
-     */
1442
-    protected static function _get_default_messengers_to_generate_on_activation(
1443
-        EE_Message_Resource_Manager $message_resource_manager
1444
-    ) {
1445
-        $active_messengers    = $message_resource_manager->active_messengers();
1446
-        $installed_messengers = $message_resource_manager->installed_messengers();
1447
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1448
-
1449
-        $messengers_to_generate = array();
1450
-        foreach ($installed_messengers as $installed_messenger) {
1451
-            //if installed messenger is a messenger that should be activated on install
1452
-            //and is not already active
1453
-            //and has never been activated
1454
-            if (
1455
-                ! $installed_messenger->activate_on_install
1456
-                || isset($active_messengers[$installed_messenger->name])
1457
-                || isset($has_activated[$installed_messenger->name])
1458
-            ) {
1459
-                continue;
1460
-            }
1461
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1462
-        }
1463
-        return $messengers_to_generate;
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This simply validates active message types to ensure they actually match installed
1469
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1470
-     * rows are set inactive.
1471
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1472
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1473
-     * are still handled in here.
1474
-     *
1475
-     * @since 4.3.1
1476
-     * @return void
1477
-     */
1478
-    public static function validate_messages_system()
1479
-    {
1480
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1481
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1482
-        $message_resource_manager->validate_active_message_types_are_installed();
1483
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1484
-    }
1485
-
1486
-
1487
-    /**
1488
-     * create_no_ticket_prices_array
1489
-     *
1490
-     * @access public
1491
-     * @static
1492
-     * @return void
1493
-     */
1494
-    public static function create_no_ticket_prices_array()
1495
-    {
1496
-        // this creates an array for tracking events that have no active ticket prices created
1497
-        // this allows us to warn admins of the situation so that it can be corrected
1498
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1499
-        if (! $espresso_no_ticket_prices) {
1500
-            add_option('ee_no_ticket_prices', array(), '', false);
1501
-        }
1502
-    }
1503
-
1504
-
1505
-    /**
1506
-     * plugin_deactivation
1507
-     *
1508
-     * @access public
1509
-     * @static
1510
-     * @return void
1511
-     */
1512
-    public static function plugin_deactivation()
1513
-    {
1514
-    }
1515
-
1516
-
1517
-    /**
1518
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1519
-     * (like post meta or term relations)
1520
-     *
1521
-     * @global wpdb $wpdb
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public static function delete_all_espresso_cpt_data()
1525
-    {
1526
-        global $wpdb;
1527
-        //get all the CPT post_types
1528
-        $ee_post_types = array();
1529
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1530
-            if (method_exists($model_name, 'instance')) {
1531
-                $model_obj = call_user_func(array($model_name, 'instance'));
1532
-                if ($model_obj instanceof EEM_CPT_Base) {
1533
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1534
-                }
1535
-            }
1536
-        }
1537
-        //get all our CPTs
1538
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1539
-        $cpt_ids = $wpdb->get_col($query);
1540
-        //delete each post meta and term relations too
1541
-        foreach ($cpt_ids as $post_id) {
1542
-            wp_delete_post($post_id, true);
1543
-        }
1544
-    }
1545
-
1546
-    /**
1547
-     * Deletes all EE custom tables
1548
-     *
1549
-     * @return array
1550
-     */
1551
-    public static function drop_espresso_tables()
1552
-    {
1553
-        $tables = array();
1554
-        // load registry
1555
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1556
-            if (method_exists($model_name, 'instance')) {
1557
-                $model_obj = call_user_func(array($model_name, 'instance'));
1558
-                if ($model_obj instanceof EEM_Base) {
1559
-                    foreach ($model_obj->get_tables() as $table) {
1560
-                        if (strpos($table->get_table_name(), 'esp_')
1561
-                            &&
1562
-                            (
1563
-                                is_main_site()//main site? nuke them all
1564
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1565
-                            )
1566
-                        ) {
1567
-                            $tables[$table->get_table_name()] = $table->get_table_name();
1568
-                        }
1569
-                    }
1570
-                }
1571
-            }
1572
-        }
1573
-
1574
-        //there are some tables whose models were removed.
1575
-        //they should be removed when removing all EE core's data
1576
-        $tables_without_models = array(
1577
-            'esp_promotion',
1578
-            'esp_promotion_applied',
1579
-            'esp_promotion_object',
1580
-            'esp_promotion_rule',
1581
-            'esp_rule',
1582
-        );
1583
-        foreach ($tables_without_models as $table) {
1584
-            $tables[$table] = $table;
1585
-        }
1586
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1587
-    }
1588
-
1589
-
1590
-
1591
-    /**
1592
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1593
-     * each table name provided has a wpdb prefix attached, and that it exists.
1594
-     * Returns the list actually deleted
1595
-     *
1596
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1597
-     * @global WPDB $wpdb
1598
-     * @param array $table_names
1599
-     * @return array of table names which we deleted
1600
-     */
1601
-    public static function drop_tables($table_names)
1602
-    {
1603
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1604
-    }
1605
-
1606
-
1607
-
1608
-    /**
1609
-     * plugin_uninstall
1610
-     *
1611
-     * @access public
1612
-     * @static
1613
-     * @param bool $remove_all
1614
-     * @return void
1615
-     */
1616
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1617
-    {
1618
-        global $wpdb;
1619
-        self::drop_espresso_tables();
1620
-        $wp_options_to_delete = array(
1621
-            'ee_no_ticket_prices'                => true,
1622
-            'ee_active_messengers'               => true,
1623
-            'ee_has_activated_messenger'         => true,
1624
-            'ee_flush_rewrite_rules'             => true,
1625
-            'ee_config'                          => false,
1626
-            'ee_data_migration_current_db_state' => true,
1627
-            'ee_data_migration_mapping_'         => false,
1628
-            'ee_data_migration_script_'          => false,
1629
-            'ee_data_migrations'                 => true,
1630
-            'ee_dms_map'                         => false,
1631
-            'ee_notices'                         => true,
1632
-            'lang_file_check_'                   => false,
1633
-            'ee_maintenance_mode'                => true,
1634
-            'ee_ueip_optin'                      => true,
1635
-            'ee_ueip_has_notified'               => true,
1636
-            'ee_plugin_activation_errors'        => true,
1637
-            'ee_id_mapping_from'                 => false,
1638
-            'espresso_persistent_admin_notices'  => true,
1639
-            'ee_encryption_key'                  => true,
1640
-            'pue_force_upgrade_'                 => false,
1641
-            'pue_json_error_'                    => false,
1642
-            'pue_install_key_'                   => false,
1643
-            'pue_verification_error_'            => false,
1644
-            'pu_dismissed_upgrade_'              => false,
1645
-            'external_updates-'                  => false,
1646
-            'ee_extra_data'                      => true,
1647
-            'ee_ssn_'                            => false,
1648
-            'ee_rss_'                            => false,
1649
-            'ee_rte_n_tx_'                       => false,
1650
-            'ee_pers_admin_notices'              => true,
1651
-            'ee_job_parameters_'                 => false,
1652
-            'ee_upload_directories_incomplete'   => true,
1653
-            'ee_verified_db_collations'          => true,
1654
-        );
1655
-        if (is_main_site()) {
1656
-            $wp_options_to_delete['ee_network_config'] = true;
1657
-        }
1658
-        $undeleted_options = array();
1659
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1660
-            if ($no_wildcard) {
1661
-                if ( ! delete_option($option_name)) {
1662
-                    $undeleted_options[] = $option_name;
1663
-                }
1664
-            } else {
1665
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1666
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1667
-                    if ( ! delete_option($option_name_from_wildcard)) {
1668
-                        $undeleted_options[] = $option_name_from_wildcard;
1669
-                    }
1670
-                }
1671
-            }
1672
-        }
1673
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1674
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1675
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1676
-            $db_update_sans_ee4 = array();
1677
-            foreach ($espresso_db_update as $version => $times_activated) {
1678
-                if ((string)$version[0] === '3') {//if its NON EE4
1679
-                    $db_update_sans_ee4[$version] = $times_activated;
1680
-                }
1681
-            }
1682
-            update_option('espresso_db_update', $db_update_sans_ee4);
1683
-        }
1684
-        $errors = '';
1685
-        if ( ! empty($undeleted_options)) {
1686
-            $errors .= sprintf(
1687
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1688
-                '<br/>',
1689
-                implode(',<br/>', $undeleted_options)
1690
-            );
1691
-        }
1692
-        if ( ! empty($errors)) {
1693
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1694
-        }
1695
-    }
1696
-
1697
-    /**
1698
-     * Gets the mysql error code from the last used query by wpdb
1699
-     *
1700
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1701
-     */
1702
-    public static function last_wpdb_error_code()
1703
-    {
1704
-        global $wpdb;
1705
-        if ($wpdb->use_mysqli) {
1706
-            return mysqli_errno($wpdb->dbh);
1707
-        } else {
1708
-            return mysql_errno($wpdb->dbh);
1709
-        }
1710
-    }
1711
-
1712
-    /**
1713
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1714
-     *
1715
-     * @global wpdb  $wpdb
1716
-     * @deprecated instead use TableAnalysis::tableExists()
1717
-     * @param string $table_name with or without $wpdb->prefix
1718
-     * @return boolean
1719
-     */
1720
-    public static function table_exists($table_name)
1721
-    {
1722
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1723
-    }
1724
-
1725
-    /**
1726
-     * Resets the cache on EEH_Activation
1727
-     */
1728
-    public static function reset()
1729
-    {
1730
-        self::$_default_creator_id                             = null;
1731
-        self::$_initialized_db_content_already_in_this_request = false;
1732
-    }
1302
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1303
+			$message_resource_manager
1304
+		);
1305
+		/**
1306
+		 * This method is verifying there are no NEW default message types
1307
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1308
+		 */
1309
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1310
+			$message_resource_manager
1311
+		);
1312
+		//after all is done, let's persist these changes to the db.
1313
+		$message_resource_manager->update_has_activated_messengers_option();
1314
+		$message_resource_manager->update_active_messengers_option();
1315
+		// will return true if either of these are true.  Otherwise will return false.
1316
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1317
+	}
1318
+
1319
+
1320
+
1321
+	/**
1322
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1323
+	 * @return array|bool
1324
+	 * @throws \EE_Error
1325
+	 */
1326
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1327
+		EE_Message_Resource_Manager $message_resource_manager
1328
+	) {
1329
+		/** @type EE_messenger[] $active_messengers */
1330
+		$active_messengers = $message_resource_manager->active_messengers();
1331
+		$installed_message_types = $message_resource_manager->installed_message_types();
1332
+		$templates_created = false;
1333
+		foreach ($active_messengers as $active_messenger) {
1334
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1335
+			$default_message_type_names_to_activate = array();
1336
+			// looping through each default message type reported by the messenger
1337
+			// and setup the actual message types to activate.
1338
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1339
+				// if already active or has already been activated before we skip
1340
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1341
+				// we also skip if the message type is not installed.
1342
+				if (
1343
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1344
+						$default_message_type_name_for_messenger,
1345
+						$active_messenger->name
1346
+					)
1347
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1348
+						$active_messenger->name,
1349
+						$default_message_type_name_for_messenger
1350
+					)
1351
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1352
+				) {
1353
+					continue;
1354
+				}
1355
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1356
+			}
1357
+			//let's activate!
1358
+			$message_resource_manager->ensure_message_types_are_active(
1359
+				$default_message_type_names_to_activate,
1360
+				$active_messenger->name,
1361
+				false
1362
+			);
1363
+			//activate the templates for these message types
1364
+			if ( ! empty($default_message_type_names_to_activate)) {
1365
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1366
+					$active_messenger->name,
1367
+					$default_message_type_names_for_messenger,
1368
+					'',
1369
+					true
1370
+				);
1371
+			}
1372
+		}
1373
+		return $templates_created;
1374
+	}
1375
+
1376
+
1377
+
1378
+	/**
1379
+	 * This will activate and generate default messengers and default message types for those messengers.
1380
+	 *
1381
+	 * @param EE_message_Resource_Manager $message_resource_manager
1382
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1383
+	 *                     False means that there were no templates generated
1384
+	 *                     (which could simply mean there are no default message types for a messenger).
1385
+	 * @throws EE_Error
1386
+	 */
1387
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1388
+		EE_Message_Resource_Manager $message_resource_manager
1389
+	) {
1390
+		/** @type EE_messenger[] $messengers_to_generate */
1391
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1392
+		$installed_message_types = $message_resource_manager->installed_message_types();
1393
+		$templates_generated = false;
1394
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1395
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1396
+			//verify the default message types match an installed message type.
1397
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1398
+				if (
1399
+					! isset($installed_message_types[$name])
1400
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1401
+						$name,
1402
+						$messenger_to_generate->name
1403
+					)
1404
+				) {
1405
+					unset($default_message_type_names_for_messenger[$key]);
1406
+				}
1407
+			}
1408
+			// in previous iterations, the active_messengers option in the db
1409
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1410
+			// This comment is left here just in case we discover that we _do_ need to update before
1411
+			// passing off to create templates (after the refactor is done).
1412
+			// @todo remove this comment when determined not necessary.
1413
+			$message_resource_manager->activate_messenger(
1414
+				$messenger_to_generate->name,
1415
+				$default_message_type_names_for_messenger,
1416
+				false
1417
+			);
1418
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1419
+			if ( ! empty($default_message_type_names_for_messenger)) {
1420
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1421
+					$messenger_to_generate->name,
1422
+					$default_message_type_names_for_messenger,
1423
+					'',
1424
+					true
1425
+				);
1426
+			}
1427
+		}
1428
+		return $templates_generated;
1429
+	}
1430
+
1431
+
1432
+	/**
1433
+	 * This returns the default messengers to generate templates for on activation of EE.
1434
+	 * It considers:
1435
+	 * - whether a messenger is already active in the db.
1436
+	 * - whether a messenger has been made active at any time in the past.
1437
+	 *
1438
+	 * @static
1439
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1440
+	 * @return EE_messenger[]
1441
+	 */
1442
+	protected static function _get_default_messengers_to_generate_on_activation(
1443
+		EE_Message_Resource_Manager $message_resource_manager
1444
+	) {
1445
+		$active_messengers    = $message_resource_manager->active_messengers();
1446
+		$installed_messengers = $message_resource_manager->installed_messengers();
1447
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1448
+
1449
+		$messengers_to_generate = array();
1450
+		foreach ($installed_messengers as $installed_messenger) {
1451
+			//if installed messenger is a messenger that should be activated on install
1452
+			//and is not already active
1453
+			//and has never been activated
1454
+			if (
1455
+				! $installed_messenger->activate_on_install
1456
+				|| isset($active_messengers[$installed_messenger->name])
1457
+				|| isset($has_activated[$installed_messenger->name])
1458
+			) {
1459
+				continue;
1460
+			}
1461
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1462
+		}
1463
+		return $messengers_to_generate;
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This simply validates active message types to ensure they actually match installed
1469
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1470
+	 * rows are set inactive.
1471
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1472
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1473
+	 * are still handled in here.
1474
+	 *
1475
+	 * @since 4.3.1
1476
+	 * @return void
1477
+	 */
1478
+	public static function validate_messages_system()
1479
+	{
1480
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1481
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1482
+		$message_resource_manager->validate_active_message_types_are_installed();
1483
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1484
+	}
1485
+
1486
+
1487
+	/**
1488
+	 * create_no_ticket_prices_array
1489
+	 *
1490
+	 * @access public
1491
+	 * @static
1492
+	 * @return void
1493
+	 */
1494
+	public static function create_no_ticket_prices_array()
1495
+	{
1496
+		// this creates an array for tracking events that have no active ticket prices created
1497
+		// this allows us to warn admins of the situation so that it can be corrected
1498
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1499
+		if (! $espresso_no_ticket_prices) {
1500
+			add_option('ee_no_ticket_prices', array(), '', false);
1501
+		}
1502
+	}
1503
+
1504
+
1505
+	/**
1506
+	 * plugin_deactivation
1507
+	 *
1508
+	 * @access public
1509
+	 * @static
1510
+	 * @return void
1511
+	 */
1512
+	public static function plugin_deactivation()
1513
+	{
1514
+	}
1515
+
1516
+
1517
+	/**
1518
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1519
+	 * (like post meta or term relations)
1520
+	 *
1521
+	 * @global wpdb $wpdb
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public static function delete_all_espresso_cpt_data()
1525
+	{
1526
+		global $wpdb;
1527
+		//get all the CPT post_types
1528
+		$ee_post_types = array();
1529
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1530
+			if (method_exists($model_name, 'instance')) {
1531
+				$model_obj = call_user_func(array($model_name, 'instance'));
1532
+				if ($model_obj instanceof EEM_CPT_Base) {
1533
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1534
+				}
1535
+			}
1536
+		}
1537
+		//get all our CPTs
1538
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1539
+		$cpt_ids = $wpdb->get_col($query);
1540
+		//delete each post meta and term relations too
1541
+		foreach ($cpt_ids as $post_id) {
1542
+			wp_delete_post($post_id, true);
1543
+		}
1544
+	}
1545
+
1546
+	/**
1547
+	 * Deletes all EE custom tables
1548
+	 *
1549
+	 * @return array
1550
+	 */
1551
+	public static function drop_espresso_tables()
1552
+	{
1553
+		$tables = array();
1554
+		// load registry
1555
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1556
+			if (method_exists($model_name, 'instance')) {
1557
+				$model_obj = call_user_func(array($model_name, 'instance'));
1558
+				if ($model_obj instanceof EEM_Base) {
1559
+					foreach ($model_obj->get_tables() as $table) {
1560
+						if (strpos($table->get_table_name(), 'esp_')
1561
+							&&
1562
+							(
1563
+								is_main_site()//main site? nuke them all
1564
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1565
+							)
1566
+						) {
1567
+							$tables[$table->get_table_name()] = $table->get_table_name();
1568
+						}
1569
+					}
1570
+				}
1571
+			}
1572
+		}
1573
+
1574
+		//there are some tables whose models were removed.
1575
+		//they should be removed when removing all EE core's data
1576
+		$tables_without_models = array(
1577
+			'esp_promotion',
1578
+			'esp_promotion_applied',
1579
+			'esp_promotion_object',
1580
+			'esp_promotion_rule',
1581
+			'esp_rule',
1582
+		);
1583
+		foreach ($tables_without_models as $table) {
1584
+			$tables[$table] = $table;
1585
+		}
1586
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1587
+	}
1588
+
1589
+
1590
+
1591
+	/**
1592
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1593
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1594
+	 * Returns the list actually deleted
1595
+	 *
1596
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1597
+	 * @global WPDB $wpdb
1598
+	 * @param array $table_names
1599
+	 * @return array of table names which we deleted
1600
+	 */
1601
+	public static function drop_tables($table_names)
1602
+	{
1603
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1604
+	}
1605
+
1606
+
1607
+
1608
+	/**
1609
+	 * plugin_uninstall
1610
+	 *
1611
+	 * @access public
1612
+	 * @static
1613
+	 * @param bool $remove_all
1614
+	 * @return void
1615
+	 */
1616
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1617
+	{
1618
+		global $wpdb;
1619
+		self::drop_espresso_tables();
1620
+		$wp_options_to_delete = array(
1621
+			'ee_no_ticket_prices'                => true,
1622
+			'ee_active_messengers'               => true,
1623
+			'ee_has_activated_messenger'         => true,
1624
+			'ee_flush_rewrite_rules'             => true,
1625
+			'ee_config'                          => false,
1626
+			'ee_data_migration_current_db_state' => true,
1627
+			'ee_data_migration_mapping_'         => false,
1628
+			'ee_data_migration_script_'          => false,
1629
+			'ee_data_migrations'                 => true,
1630
+			'ee_dms_map'                         => false,
1631
+			'ee_notices'                         => true,
1632
+			'lang_file_check_'                   => false,
1633
+			'ee_maintenance_mode'                => true,
1634
+			'ee_ueip_optin'                      => true,
1635
+			'ee_ueip_has_notified'               => true,
1636
+			'ee_plugin_activation_errors'        => true,
1637
+			'ee_id_mapping_from'                 => false,
1638
+			'espresso_persistent_admin_notices'  => true,
1639
+			'ee_encryption_key'                  => true,
1640
+			'pue_force_upgrade_'                 => false,
1641
+			'pue_json_error_'                    => false,
1642
+			'pue_install_key_'                   => false,
1643
+			'pue_verification_error_'            => false,
1644
+			'pu_dismissed_upgrade_'              => false,
1645
+			'external_updates-'                  => false,
1646
+			'ee_extra_data'                      => true,
1647
+			'ee_ssn_'                            => false,
1648
+			'ee_rss_'                            => false,
1649
+			'ee_rte_n_tx_'                       => false,
1650
+			'ee_pers_admin_notices'              => true,
1651
+			'ee_job_parameters_'                 => false,
1652
+			'ee_upload_directories_incomplete'   => true,
1653
+			'ee_verified_db_collations'          => true,
1654
+		);
1655
+		if (is_main_site()) {
1656
+			$wp_options_to_delete['ee_network_config'] = true;
1657
+		}
1658
+		$undeleted_options = array();
1659
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1660
+			if ($no_wildcard) {
1661
+				if ( ! delete_option($option_name)) {
1662
+					$undeleted_options[] = $option_name;
1663
+				}
1664
+			} else {
1665
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1666
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1667
+					if ( ! delete_option($option_name_from_wildcard)) {
1668
+						$undeleted_options[] = $option_name_from_wildcard;
1669
+					}
1670
+				}
1671
+			}
1672
+		}
1673
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1674
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1675
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1676
+			$db_update_sans_ee4 = array();
1677
+			foreach ($espresso_db_update as $version => $times_activated) {
1678
+				if ((string)$version[0] === '3') {//if its NON EE4
1679
+					$db_update_sans_ee4[$version] = $times_activated;
1680
+				}
1681
+			}
1682
+			update_option('espresso_db_update', $db_update_sans_ee4);
1683
+		}
1684
+		$errors = '';
1685
+		if ( ! empty($undeleted_options)) {
1686
+			$errors .= sprintf(
1687
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1688
+				'<br/>',
1689
+				implode(',<br/>', $undeleted_options)
1690
+			);
1691
+		}
1692
+		if ( ! empty($errors)) {
1693
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1694
+		}
1695
+	}
1696
+
1697
+	/**
1698
+	 * Gets the mysql error code from the last used query by wpdb
1699
+	 *
1700
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1701
+	 */
1702
+	public static function last_wpdb_error_code()
1703
+	{
1704
+		global $wpdb;
1705
+		if ($wpdb->use_mysqli) {
1706
+			return mysqli_errno($wpdb->dbh);
1707
+		} else {
1708
+			return mysql_errno($wpdb->dbh);
1709
+		}
1710
+	}
1711
+
1712
+	/**
1713
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1714
+	 *
1715
+	 * @global wpdb  $wpdb
1716
+	 * @deprecated instead use TableAnalysis::tableExists()
1717
+	 * @param string $table_name with or without $wpdb->prefix
1718
+	 * @return boolean
1719
+	 */
1720
+	public static function table_exists($table_name)
1721
+	{
1722
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1723
+	}
1724
+
1725
+	/**
1726
+	 * Resets the cache on EEH_Activation
1727
+	 */
1728
+	public static function reset()
1729
+	{
1730
+		self::$_default_creator_id                             = null;
1731
+		self::$_initialized_db_content_already_in_this_request = false;
1732
+	}
1733 1733
 }
1734 1734
 // End of file EEH_Activation.helper.php
1735 1735
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
core/helpers/EEH_Debug_Tools.helper.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 
376 376
 
377 377
     /**
378
-     * @param mixed      $var
378
+     * @param string      $var
379 379
      * @param string     $var_name
380 380
      * @param string     $file
381 381
      * @param int|string $line
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
      * @param mixed      $var
514 514
      * @param string     $var_name
515 515
      * @param string     $file
516
-     * @param int|string $line
516
+     * @param integer $line
517 517
      * @param int        $heading_tag
518 518
      * @param bool       $die
519 519
      */
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 
577 577
     /**
578 578
      * @deprecated 4.9.39.rc.034
579
-     * @param null $timer_name
579
+     * @param string $timer_name
580 580
      */
581 581
     public function start_timer($timer_name = null)
582 582
     {
Please login to merge, or discard this patch.
Indentation   +642 added lines, -642 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\Benchmark;
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
 
@@ -17,632 +17,632 @@  discard block
 block discarded – undo
17 17
 class EEH_Debug_Tools
18 18
 {
19 19
 
20
-    /**
21
-     *    instance of the EEH_Autoloader object
22
-     *
23
-     * @var    $_instance
24
-     * @access    private
25
-     */
26
-    private static $_instance;
27
-
28
-    /**
29
-     * @var array
30
-     */
31
-    protected $_memory_usage_points = array();
32
-
33
-
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @access    public
38
-     * @return EEH_Debug_Tools
39
-     */
40
-    public static function instance()
41
-    {
42
-        // check if class object is instantiated, and instantiated properly
43
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
44
-            self::$_instance = new self();
45
-        }
46
-        return self::$_instance;
47
-    }
48
-
49
-
50
-
51
-    /**
52
-     * private class constructor
53
-     */
54
-    private function __construct()
55
-    {
56
-        // load Kint PHP debugging library
57
-        if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
58
-            // despite EE4 having a check for an existing copy of the Kint debugging class,
59
-            // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60
-            // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61
-            // so we've moved it to our test folder so that it is not included with production releases
62
-            // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
-            require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
64
-        }
65
-        // if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66
-        //add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
67
-        // }
68
-        $plugin = basename(EE_PLUGIN_DIR_PATH);
69
-        add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
70
-        add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
71
-        add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     *    show_db_name
78
-     *
79
-     * @return void
80
-     */
81
-    public static function show_db_name()
82
-    {
83
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84
-            echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85
-                 . DB_NAME
86
-                 . '</p>';
87
-        }
88
-        if (EE_DEBUG) {
89
-            Benchmark::displayResults();
90
-        }
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     *    dump EE_Session object at bottom of page after everything else has happened
97
-     *
98
-     * @return void
99
-     */
100
-    public function espresso_session_footer_dump()
101
-    {
102
-        if (
103
-            (defined('WP_DEBUG') && WP_DEBUG)
104
-            && ! defined('DOING_AJAX')
105
-            && class_exists('Kint')
106
-            && function_exists('wp_get_current_user')
107
-            && current_user_can('update_core')
108
-            && class_exists('EE_Registry')
109
-        ) {
110
-            Kint::dump(EE_Registry::instance()->SSN->id());
111
-            Kint::dump(EE_Registry::instance()->SSN);
112
-            //			Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
113
-            $this->espresso_list_hooked_functions();
114
-            Benchmark::displayResults();
115
-        }
116
-    }
117
-
118
-
119
-
120
-    /**
121
-     *    List All Hooked Functions
122
-     *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
123
-     *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
124
-     *
125
-     * @param string $tag
126
-     * @return void
127
-     */
128
-    public function espresso_list_hooked_functions($tag = '')
129
-    {
130
-        global $wp_filter;
131
-        echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132
-        if ($tag) {
133
-            $hook[$tag] = $wp_filter[$tag];
134
-            if (! is_array($hook[$tag])) {
135
-                trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136
-                return;
137
-            }
138
-            echo '<h5>For Tag: ' . $tag . '</h5>';
139
-        } else {
140
-            $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141
-            ksort($hook);
142
-        }
143
-        foreach ($hook as $tag_name => $priorities) {
144
-            echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag_name</strong><br />";
145
-            ksort($priorities);
146
-            foreach ($priorities as $priority => $function) {
147
-                echo $priority;
148
-                foreach ($function as $name => $properties) {
149
-                    echo "\t$name<br />";
150
-                }
151
-            }
152
-        }
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     *    registered_filter_callbacks
159
-     *
160
-     * @param string $hook_name
161
-     * @return array
162
-     */
163
-    public static function registered_filter_callbacks($hook_name = '')
164
-    {
165
-        $filters = array();
166
-        global $wp_filter;
167
-        if (isset($wp_filter[$hook_name])) {
168
-            $filters[$hook_name] = array();
169
-            foreach ($wp_filter[$hook_name] as $priority => $callbacks) {
170
-                $filters[$hook_name][$priority] = array();
171
-                foreach ($callbacks as $callback) {
172
-                    $filters[$hook_name][$priority][] = $callback['function'];
173
-                }
174
-            }
175
-        }
176
-        return $filters;
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     *    captures plugin activation errors for debugging
183
-     *
184
-     * @return void
185
-     * @throws EE_Error
186
-     */
187
-    public static function ee_plugin_activation_errors()
188
-    {
189
-        if (WP_DEBUG) {
190
-            $activation_errors = ob_get_contents();
191
-            if (! empty($activation_errors)) {
192
-                $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
193
-            }
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
-            if (class_exists('EEH_File')) {
196
-                try {
197
-                    EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
199
-                    );
200
-                    EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
202
-                        $activation_errors
203
-                    );
204
-                } catch (EE_Error $e) {
205
-                    EE_Error::add_error(
206
-                        sprintf(
207
-                            __(
208
-                                'The Event Espresso activation errors file could not be setup because: %s',
209
-                                'event_espresso'
210
-                            ),
211
-                            $e->getMessage()
212
-                        ),
213
-                        __FILE__, __FUNCTION__, __LINE__
214
-                    );
215
-                }
216
-            } else {
217
-                // old school attempt
218
-                file_put_contents(
219
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
220
-                    $activation_errors
221
-                );
222
-            }
223
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
224
-            update_option('ee_plugin_activation_errors', $activation_errors);
225
-        }
226
-    }
227
-
228
-
229
-
230
-    /**
231
-     * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
232
-     * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
233
-     * or we want to make sure they use something the right way.
234
-     *
235
-     * @access public
236
-     * @param string $function      The function that was called
237
-     * @param string $message       A message explaining what has been done incorrectly
238
-     * @param string $version       The version of Event Espresso where the error was added
239
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
240
-     *                              for a deprecated function. This allows deprecation to occur during one version,
241
-     *                              but not have any notices appear until a later version. This allows developers
242
-     *                              extra time to update their code before notices appear.
243
-     * @param int    $error_type
244
-     * @uses   trigger_error()
245
-     */
246
-    public function doing_it_wrong(
247
-        $function,
248
-        $message,
249
-        $version,
250
-        $applies_when = '',
251
-        $error_type = null
252
-    ) {
253
-        $applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
254
-        $error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
255
-        // because we swapped the parameter order around for the last two params,
256
-        // let's verify that some third party isn't still passing an error type value for the third param
257
-        if (is_int($applies_when)) {
258
-            $error_type = $applies_when;
259
-            $applies_when = espresso_version();
260
-        }
261
-        // if not displaying notices yet, then just leave
262
-        if (version_compare(espresso_version(), $applies_when, '<')) {
263
-            return;
264
-        }
265
-        do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
266
-        $version = $version === null
267
-            ? ''
268
-            : sprintf(
269
-                __('(This message was added in version %s of Event Espresso)', 'event_espresso'),
270
-                $version
271
-            );
272
-        $error_message = sprintf(
273
-            esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
274
-            $function,
275
-            '<strong>',
276
-            '</strong>',
277
-            $message,
278
-            $version
279
-        );
280
-        // don't trigger error if doing ajax,
281
-        // instead we'll add a transient EE_Error notice that in theory should show on the next request.
282
-        if (defined('DOING_AJAX') && DOING_AJAX) {
283
-            $error_message .= ' ' . esc_html__(
284
-                    'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285
-                    'event_espresso'
286
-                );
287
-            $error_message .= '<ul><li>';
288
-            $error_message .= implode('</li><li>', EE_Registry::instance()->REQ->params());
289
-            $error_message .= '</ul>';
290
-            EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
291
-            //now we set this on the transient so it shows up on the next request.
292
-            EE_Error::get_notices(false, true);
293
-        } else {
294
-            trigger_error($error_message, $error_type);
295
-        }
296
-    }
297
-
298
-
299
-
300
-
301
-    /**
302
-     * Logger helpers
303
-     */
304
-    /**
305
-     * debug
306
-     *
307
-     * @param string $class
308
-     * @param string $func
309
-     * @param string $line
310
-     * @param array  $info
311
-     * @param bool   $display_request
312
-     * @param string $debug_index
313
-     * @param string $debug_key
314
-     * @throws EE_Error
315
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
316
-     */
317
-    public static function log(
318
-        $class = '',
319
-        $func = '',
320
-        $line = '',
321
-        $info = array(),
322
-        $display_request = false,
323
-        $debug_index = '',
324
-        $debug_key = 'EE_DEBUG_SPCO'
325
-    ) {
326
-        if (WP_DEBUG) {
327
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
328
-            $debug_data = get_option($debug_key, array());
329
-            $default_data = array(
330
-                $class => $func . '() : ' . $line,
331
-                'REQ'  => $display_request ? $_REQUEST : '',
332
-            );
333
-            // don't serialize objects
334
-            $info = self::strip_objects($info);
335
-            $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[$index])) {
337
-                $debug_data[$index] = array();
338
-            }
339
-            $debug_data[$index][microtime()] = array_merge($default_data, $info);
340
-            update_option($debug_key, $debug_data);
341
-        }
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * strip_objects
348
-     *
349
-     * @param array $info
350
-     * @return array
351
-     */
352
-    public static function strip_objects($info = array())
353
-    {
354
-        foreach ($info as $key => $value) {
355
-            if (is_array($value)) {
356
-                $info[$key] = self::strip_objects($value);
357
-            } else if (is_object($value)) {
358
-                $object_class = get_class($value);
359
-                $info[$object_class] = array();
360
-                $info[$object_class]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
-                if (method_exists($value, 'ID')) {
362
-                    $info[$object_class]['ID'] = $value->ID();
363
-                }
364
-                if (method_exists($value, 'status')) {
365
-                    $info[$object_class]['status'] = $value->status();
366
-                } else if (method_exists($value, 'status_ID')) {
367
-                    $info[$object_class]['status'] = $value->status_ID();
368
-                }
369
-                unset($info[$key]);
370
-            }
371
-        }
372
-        return (array)$info;
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * @param mixed      $var
379
-     * @param string     $var_name
380
-     * @param string     $file
381
-     * @param int|string $line
382
-     * @param int        $heading_tag
383
-     * @param bool       $die
384
-     * @param string     $margin
385
-     */
386
-    public static function printv(
387
-        $var,
388
-        $var_name = '',
389
-        $file = '',
390
-        $line = '',
391
-        $heading_tag = 5,
392
-        $die = false,
393
-        $margin = ''
394
-    ) {
395
-        $var_name = ! $var_name ? 'string' : $var_name;
396
-        $var_name = ucwords(str_replace('$', '', $var_name));
397
-        $is_method = method_exists($var_name, $var);
398
-        $var_name = ucwords(str_replace('_', ' ', $var_name));
399
-        $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401
-        $result .= $is_method
402
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
404
-        $result .= EEH_Debug_Tools::file_and_line($file, $line);
405
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
406
-        if ($die) {
407
-            die($result);
408
-        }
409
-        echo $result;
410
-    }
411
-
412
-
413
-
414
-    /**
415
-     * @param string $var_name
416
-     * @param string $heading_tag
417
-     * @param string $margin
418
-     * @return string
419
-     */
420
-    protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '')
421
-    {
422
-        if (defined('EE_TESTS_DIR')) {
423
-            return "\n{$var_name}";
424
-        }
425
-        $margin = "25px 0 0 {$margin}";
426
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
427
-    }
428
-
429
-
430
-
431
-    /**
432
-     * @param string $heading_tag
433
-     * @return string
434
-     */
435
-    protected static function headingX($heading_tag = 'h5')
436
-    {
437
-        if (defined('EE_TESTS_DIR')) {
438
-            return '';
439
-        }
440
-        return '</' . $heading_tag . '>';
441
-    }
442
-
443
-
444
-
445
-    /**
446
-     * @param string $content
447
-     * @return string
448
-     */
449
-    protected static function grey_span($content = '')
450
-    {
451
-        if (defined('EE_TESTS_DIR')) {
452
-            return $content;
453
-        }
454
-        return '<span style="color:#999">' . $content . '</span>';
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * @param string $file
461
-     * @param int    $line
462
-     * @return string
463
-     */
464
-    protected static function file_and_line($file, $line)
465
-    {
466
-        if ($file === '' || $line === '') {
467
-            return '';
468
-        }
469
-        if (defined('EE_TESTS_DIR')) {
470
-            return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
471
-        }
472
-        return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473
-               . $file
474
-               . '<br />line no: '
475
-               . $line
476
-               . '</span>';
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * @param string $content
483
-     * @return string
484
-     */
485
-    protected static function orange_span($content = '')
486
-    {
487
-        if (defined('EE_TESTS_DIR')) {
488
-            return $content;
489
-        }
490
-        return '<span style="color:#E76700">' . $content . '</span>';
491
-    }
492
-
493
-
494
-
495
-    /**
496
-     * @param mixed $var
497
-     * @return string
498
-     */
499
-    protected static function pre_span($var)
500
-    {
501
-        ob_start();
502
-        var_dump($var);
503
-        $var = ob_get_clean();
504
-        if (defined('EE_TESTS_DIR')) {
505
-            return "\n" . $var;
506
-        }
507
-        return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * @param mixed      $var
514
-     * @param string     $var_name
515
-     * @param string     $file
516
-     * @param int|string $line
517
-     * @param int        $heading_tag
518
-     * @param bool       $die
519
-     */
520
-    public static function printr(
521
-        $var,
522
-        $var_name = '',
523
-        $file = '',
524
-        $line = '',
525
-        $heading_tag = 5,
526
-        $die = false
527
-    ) {
528
-        // return;
529
-        $file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
530
-        $margin = is_admin() ? ' 180px' : '0';
531
-        //$print_r = false;
532
-        if (is_string($var)) {
533
-            EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
534
-            return;
535
-        }
536
-        if (is_object($var)) {
537
-            $var_name = ! $var_name ? 'object' : $var_name;
538
-            //$print_r = true;
539
-        } else if (is_array($var)) {
540
-            $var_name = ! $var_name ? 'array' : $var_name;
541
-            //$print_r = true;
542
-        } else if (is_numeric($var)) {
543
-            $var_name = ! $var_name ? 'numeric' : $var_name;
544
-        } else if ($var === null) {
545
-            $var_name = ! $var_name ? 'null' : $var_name;
546
-        }
547
-        $var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548
-        $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
551
-                EEH_Debug_Tools::pre_span($var)
552
-            );
553
-        $result .= EEH_Debug_Tools::file_and_line($file, $line);
554
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
555
-        if ($die) {
556
-            die($result);
557
-        }
558
-        echo $result;
559
-    }
560
-
561
-
562
-
563
-    /******************** deprecated ********************/
564
-
565
-
566
-
567
-    /**
568
-     * @deprecated 4.9.39.rc.034
569
-     */
570
-    public function reset_times()
571
-    {
572
-        Benchmark::resetTimes();
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * @deprecated 4.9.39.rc.034
579
-     * @param null $timer_name
580
-     */
581
-    public function start_timer($timer_name = null)
582
-    {
583
-        Benchmark::startTimer($timer_name);
584
-    }
585
-
586
-
587
-
588
-    /**
589
-     * @deprecated 4.9.39.rc.034
590
-     * @param string $timer_name
591
-     */
592
-    public function stop_timer($timer_name = '')
593
-    {
594
-        Benchmark::stopTimer($timer_name);
595
-    }
596
-
597
-
598
-
599
-    /**
600
-     * @deprecated 4.9.39.rc.034
601
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
602
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
603
-     * @return void
604
-     */
605
-    public function measure_memory($label, $output_now = false)
606
-    {
607
-        Benchmark::measureMemory($label, $output_now);
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * @deprecated 4.9.39.rc.034
614
-     * @param int $size
615
-     * @return string
616
-     */
617
-    public function convert($size)
618
-    {
619
-        return Benchmark::convert($size);
620
-    }
621
-
622
-
623
-
624
-    /**
625
-     * @deprecated 4.9.39.rc.034
626
-     * @param bool $output_now
627
-     * @return string
628
-     */
629
-    public function show_times($output_now = true)
630
-    {
631
-        return Benchmark::displayResults($output_now);
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * @deprecated 4.9.39.rc.034
638
-     * @param string $timer_name
639
-     * @param float  $total_time
640
-     * @return string
641
-     */
642
-    public function format_time($timer_name, $total_time)
643
-    {
644
-        return Benchmark::formatTime($timer_name, $total_time);
645
-    }
20
+	/**
21
+	 *    instance of the EEH_Autoloader object
22
+	 *
23
+	 * @var    $_instance
24
+	 * @access    private
25
+	 */
26
+	private static $_instance;
27
+
28
+	/**
29
+	 * @var array
30
+	 */
31
+	protected $_memory_usage_points = array();
32
+
33
+
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @access    public
38
+	 * @return EEH_Debug_Tools
39
+	 */
40
+	public static function instance()
41
+	{
42
+		// check if class object is instantiated, and instantiated properly
43
+		if (! self::$_instance instanceof EEH_Debug_Tools) {
44
+			self::$_instance = new self();
45
+		}
46
+		return self::$_instance;
47
+	}
48
+
49
+
50
+
51
+	/**
52
+	 * private class constructor
53
+	 */
54
+	private function __construct()
55
+	{
56
+		// load Kint PHP debugging library
57
+		if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
58
+			// despite EE4 having a check for an existing copy of the Kint debugging class,
59
+			// if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60
+			// then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61
+			// so we've moved it to our test folder so that it is not included with production releases
62
+			// plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
+			require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
64
+		}
65
+		// if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66
+		//add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
67
+		// }
68
+		$plugin = basename(EE_PLUGIN_DIR_PATH);
69
+		add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
70
+		add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
71
+		add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 *    show_db_name
78
+	 *
79
+	 * @return void
80
+	 */
81
+	public static function show_db_name()
82
+	{
83
+		if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84
+			echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85
+				 . DB_NAME
86
+				 . '</p>';
87
+		}
88
+		if (EE_DEBUG) {
89
+			Benchmark::displayResults();
90
+		}
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 *    dump EE_Session object at bottom of page after everything else has happened
97
+	 *
98
+	 * @return void
99
+	 */
100
+	public function espresso_session_footer_dump()
101
+	{
102
+		if (
103
+			(defined('WP_DEBUG') && WP_DEBUG)
104
+			&& ! defined('DOING_AJAX')
105
+			&& class_exists('Kint')
106
+			&& function_exists('wp_get_current_user')
107
+			&& current_user_can('update_core')
108
+			&& class_exists('EE_Registry')
109
+		) {
110
+			Kint::dump(EE_Registry::instance()->SSN->id());
111
+			Kint::dump(EE_Registry::instance()->SSN);
112
+			//			Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
113
+			$this->espresso_list_hooked_functions();
114
+			Benchmark::displayResults();
115
+		}
116
+	}
117
+
118
+
119
+
120
+	/**
121
+	 *    List All Hooked Functions
122
+	 *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
123
+	 *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
124
+	 *
125
+	 * @param string $tag
126
+	 * @return void
127
+	 */
128
+	public function espresso_list_hooked_functions($tag = '')
129
+	{
130
+		global $wp_filter;
131
+		echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132
+		if ($tag) {
133
+			$hook[$tag] = $wp_filter[$tag];
134
+			if (! is_array($hook[$tag])) {
135
+				trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136
+				return;
137
+			}
138
+			echo '<h5>For Tag: ' . $tag . '</h5>';
139
+		} else {
140
+			$hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141
+			ksort($hook);
142
+		}
143
+		foreach ($hook as $tag_name => $priorities) {
144
+			echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag_name</strong><br />";
145
+			ksort($priorities);
146
+			foreach ($priorities as $priority => $function) {
147
+				echo $priority;
148
+				foreach ($function as $name => $properties) {
149
+					echo "\t$name<br />";
150
+				}
151
+			}
152
+		}
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 *    registered_filter_callbacks
159
+	 *
160
+	 * @param string $hook_name
161
+	 * @return array
162
+	 */
163
+	public static function registered_filter_callbacks($hook_name = '')
164
+	{
165
+		$filters = array();
166
+		global $wp_filter;
167
+		if (isset($wp_filter[$hook_name])) {
168
+			$filters[$hook_name] = array();
169
+			foreach ($wp_filter[$hook_name] as $priority => $callbacks) {
170
+				$filters[$hook_name][$priority] = array();
171
+				foreach ($callbacks as $callback) {
172
+					$filters[$hook_name][$priority][] = $callback['function'];
173
+				}
174
+			}
175
+		}
176
+		return $filters;
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 *    captures plugin activation errors for debugging
183
+	 *
184
+	 * @return void
185
+	 * @throws EE_Error
186
+	 */
187
+	public static function ee_plugin_activation_errors()
188
+	{
189
+		if (WP_DEBUG) {
190
+			$activation_errors = ob_get_contents();
191
+			if (! empty($activation_errors)) {
192
+				$activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
193
+			}
194
+			espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
+			if (class_exists('EEH_File')) {
196
+				try {
197
+					EEH_File::ensure_file_exists_and_is_writable(
198
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
199
+					);
200
+					EEH_File::write_to_file(
201
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
202
+						$activation_errors
203
+					);
204
+				} catch (EE_Error $e) {
205
+					EE_Error::add_error(
206
+						sprintf(
207
+							__(
208
+								'The Event Espresso activation errors file could not be setup because: %s',
209
+								'event_espresso'
210
+							),
211
+							$e->getMessage()
212
+						),
213
+						__FILE__, __FUNCTION__, __LINE__
214
+					);
215
+				}
216
+			} else {
217
+				// old school attempt
218
+				file_put_contents(
219
+					EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
220
+					$activation_errors
221
+				);
222
+			}
223
+			$activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
224
+			update_option('ee_plugin_activation_errors', $activation_errors);
225
+		}
226
+	}
227
+
228
+
229
+
230
+	/**
231
+	 * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
232
+	 * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
233
+	 * or we want to make sure they use something the right way.
234
+	 *
235
+	 * @access public
236
+	 * @param string $function      The function that was called
237
+	 * @param string $message       A message explaining what has been done incorrectly
238
+	 * @param string $version       The version of Event Espresso where the error was added
239
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
240
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
241
+	 *                              but not have any notices appear until a later version. This allows developers
242
+	 *                              extra time to update their code before notices appear.
243
+	 * @param int    $error_type
244
+	 * @uses   trigger_error()
245
+	 */
246
+	public function doing_it_wrong(
247
+		$function,
248
+		$message,
249
+		$version,
250
+		$applies_when = '',
251
+		$error_type = null
252
+	) {
253
+		$applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
254
+		$error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
255
+		// because we swapped the parameter order around for the last two params,
256
+		// let's verify that some third party isn't still passing an error type value for the third param
257
+		if (is_int($applies_when)) {
258
+			$error_type = $applies_when;
259
+			$applies_when = espresso_version();
260
+		}
261
+		// if not displaying notices yet, then just leave
262
+		if (version_compare(espresso_version(), $applies_when, '<')) {
263
+			return;
264
+		}
265
+		do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
266
+		$version = $version === null
267
+			? ''
268
+			: sprintf(
269
+				__('(This message was added in version %s of Event Espresso)', 'event_espresso'),
270
+				$version
271
+			);
272
+		$error_message = sprintf(
273
+			esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
274
+			$function,
275
+			'<strong>',
276
+			'</strong>',
277
+			$message,
278
+			$version
279
+		);
280
+		// don't trigger error if doing ajax,
281
+		// instead we'll add a transient EE_Error notice that in theory should show on the next request.
282
+		if (defined('DOING_AJAX') && DOING_AJAX) {
283
+			$error_message .= ' ' . esc_html__(
284
+					'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285
+					'event_espresso'
286
+				);
287
+			$error_message .= '<ul><li>';
288
+			$error_message .= implode('</li><li>', EE_Registry::instance()->REQ->params());
289
+			$error_message .= '</ul>';
290
+			EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
291
+			//now we set this on the transient so it shows up on the next request.
292
+			EE_Error::get_notices(false, true);
293
+		} else {
294
+			trigger_error($error_message, $error_type);
295
+		}
296
+	}
297
+
298
+
299
+
300
+
301
+	/**
302
+	 * Logger helpers
303
+	 */
304
+	/**
305
+	 * debug
306
+	 *
307
+	 * @param string $class
308
+	 * @param string $func
309
+	 * @param string $line
310
+	 * @param array  $info
311
+	 * @param bool   $display_request
312
+	 * @param string $debug_index
313
+	 * @param string $debug_key
314
+	 * @throws EE_Error
315
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
316
+	 */
317
+	public static function log(
318
+		$class = '',
319
+		$func = '',
320
+		$line = '',
321
+		$info = array(),
322
+		$display_request = false,
323
+		$debug_index = '',
324
+		$debug_key = 'EE_DEBUG_SPCO'
325
+	) {
326
+		if (WP_DEBUG) {
327
+			$debug_key = $debug_key . '_' . EE_Session::instance()->id();
328
+			$debug_data = get_option($debug_key, array());
329
+			$default_data = array(
330
+				$class => $func . '() : ' . $line,
331
+				'REQ'  => $display_request ? $_REQUEST : '',
332
+			);
333
+			// don't serialize objects
334
+			$info = self::strip_objects($info);
335
+			$index = ! empty($debug_index) ? $debug_index : 0;
336
+			if (! isset($debug_data[$index])) {
337
+				$debug_data[$index] = array();
338
+			}
339
+			$debug_data[$index][microtime()] = array_merge($default_data, $info);
340
+			update_option($debug_key, $debug_data);
341
+		}
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * strip_objects
348
+	 *
349
+	 * @param array $info
350
+	 * @return array
351
+	 */
352
+	public static function strip_objects($info = array())
353
+	{
354
+		foreach ($info as $key => $value) {
355
+			if (is_array($value)) {
356
+				$info[$key] = self::strip_objects($value);
357
+			} else if (is_object($value)) {
358
+				$object_class = get_class($value);
359
+				$info[$object_class] = array();
360
+				$info[$object_class]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
+				if (method_exists($value, 'ID')) {
362
+					$info[$object_class]['ID'] = $value->ID();
363
+				}
364
+				if (method_exists($value, 'status')) {
365
+					$info[$object_class]['status'] = $value->status();
366
+				} else if (method_exists($value, 'status_ID')) {
367
+					$info[$object_class]['status'] = $value->status_ID();
368
+				}
369
+				unset($info[$key]);
370
+			}
371
+		}
372
+		return (array)$info;
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * @param mixed      $var
379
+	 * @param string     $var_name
380
+	 * @param string     $file
381
+	 * @param int|string $line
382
+	 * @param int        $heading_tag
383
+	 * @param bool       $die
384
+	 * @param string     $margin
385
+	 */
386
+	public static function printv(
387
+		$var,
388
+		$var_name = '',
389
+		$file = '',
390
+		$line = '',
391
+		$heading_tag = 5,
392
+		$die = false,
393
+		$margin = ''
394
+	) {
395
+		$var_name = ! $var_name ? 'string' : $var_name;
396
+		$var_name = ucwords(str_replace('$', '', $var_name));
397
+		$is_method = method_exists($var_name, $var);
398
+		$var_name = ucwords(str_replace('_', ' ', $var_name));
399
+		$heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401
+		$result .= $is_method
402
+			? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
+			: EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
404
+		$result .= EEH_Debug_Tools::file_and_line($file, $line);
405
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
406
+		if ($die) {
407
+			die($result);
408
+		}
409
+		echo $result;
410
+	}
411
+
412
+
413
+
414
+	/**
415
+	 * @param string $var_name
416
+	 * @param string $heading_tag
417
+	 * @param string $margin
418
+	 * @return string
419
+	 */
420
+	protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '')
421
+	{
422
+		if (defined('EE_TESTS_DIR')) {
423
+			return "\n{$var_name}";
424
+		}
425
+		$margin = "25px 0 0 {$margin}";
426
+		return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
427
+	}
428
+
429
+
430
+
431
+	/**
432
+	 * @param string $heading_tag
433
+	 * @return string
434
+	 */
435
+	protected static function headingX($heading_tag = 'h5')
436
+	{
437
+		if (defined('EE_TESTS_DIR')) {
438
+			return '';
439
+		}
440
+		return '</' . $heading_tag . '>';
441
+	}
442
+
443
+
444
+
445
+	/**
446
+	 * @param string $content
447
+	 * @return string
448
+	 */
449
+	protected static function grey_span($content = '')
450
+	{
451
+		if (defined('EE_TESTS_DIR')) {
452
+			return $content;
453
+		}
454
+		return '<span style="color:#999">' . $content . '</span>';
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * @param string $file
461
+	 * @param int    $line
462
+	 * @return string
463
+	 */
464
+	protected static function file_and_line($file, $line)
465
+	{
466
+		if ($file === '' || $line === '') {
467
+			return '';
468
+		}
469
+		if (defined('EE_TESTS_DIR')) {
470
+			return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
471
+		}
472
+		return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473
+			   . $file
474
+			   . '<br />line no: '
475
+			   . $line
476
+			   . '</span>';
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * @param string $content
483
+	 * @return string
484
+	 */
485
+	protected static function orange_span($content = '')
486
+	{
487
+		if (defined('EE_TESTS_DIR')) {
488
+			return $content;
489
+		}
490
+		return '<span style="color:#E76700">' . $content . '</span>';
491
+	}
492
+
493
+
494
+
495
+	/**
496
+	 * @param mixed $var
497
+	 * @return string
498
+	 */
499
+	protected static function pre_span($var)
500
+	{
501
+		ob_start();
502
+		var_dump($var);
503
+		$var = ob_get_clean();
504
+		if (defined('EE_TESTS_DIR')) {
505
+			return "\n" . $var;
506
+		}
507
+		return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * @param mixed      $var
514
+	 * @param string     $var_name
515
+	 * @param string     $file
516
+	 * @param int|string $line
517
+	 * @param int        $heading_tag
518
+	 * @param bool       $die
519
+	 */
520
+	public static function printr(
521
+		$var,
522
+		$var_name = '',
523
+		$file = '',
524
+		$line = '',
525
+		$heading_tag = 5,
526
+		$die = false
527
+	) {
528
+		// return;
529
+		$file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
530
+		$margin = is_admin() ? ' 180px' : '0';
531
+		//$print_r = false;
532
+		if (is_string($var)) {
533
+			EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
534
+			return;
535
+		}
536
+		if (is_object($var)) {
537
+			$var_name = ! $var_name ? 'object' : $var_name;
538
+			//$print_r = true;
539
+		} else if (is_array($var)) {
540
+			$var_name = ! $var_name ? 'array' : $var_name;
541
+			//$print_r = true;
542
+		} else if (is_numeric($var)) {
543
+			$var_name = ! $var_name ? 'numeric' : $var_name;
544
+		} else if ($var === null) {
545
+			$var_name = ! $var_name ? 'null' : $var_name;
546
+		}
547
+		$var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548
+		$heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
+		$result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
551
+				EEH_Debug_Tools::pre_span($var)
552
+			);
553
+		$result .= EEH_Debug_Tools::file_and_line($file, $line);
554
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
555
+		if ($die) {
556
+			die($result);
557
+		}
558
+		echo $result;
559
+	}
560
+
561
+
562
+
563
+	/******************** deprecated ********************/
564
+
565
+
566
+
567
+	/**
568
+	 * @deprecated 4.9.39.rc.034
569
+	 */
570
+	public function reset_times()
571
+	{
572
+		Benchmark::resetTimes();
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * @deprecated 4.9.39.rc.034
579
+	 * @param null $timer_name
580
+	 */
581
+	public function start_timer($timer_name = null)
582
+	{
583
+		Benchmark::startTimer($timer_name);
584
+	}
585
+
586
+
587
+
588
+	/**
589
+	 * @deprecated 4.9.39.rc.034
590
+	 * @param string $timer_name
591
+	 */
592
+	public function stop_timer($timer_name = '')
593
+	{
594
+		Benchmark::stopTimer($timer_name);
595
+	}
596
+
597
+
598
+
599
+	/**
600
+	 * @deprecated 4.9.39.rc.034
601
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
602
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
603
+	 * @return void
604
+	 */
605
+	public function measure_memory($label, $output_now = false)
606
+	{
607
+		Benchmark::measureMemory($label, $output_now);
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * @deprecated 4.9.39.rc.034
614
+	 * @param int $size
615
+	 * @return string
616
+	 */
617
+	public function convert($size)
618
+	{
619
+		return Benchmark::convert($size);
620
+	}
621
+
622
+
623
+
624
+	/**
625
+	 * @deprecated 4.9.39.rc.034
626
+	 * @param bool $output_now
627
+	 * @return string
628
+	 */
629
+	public function show_times($output_now = true)
630
+	{
631
+		return Benchmark::displayResults($output_now);
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * @deprecated 4.9.39.rc.034
638
+	 * @param string $timer_name
639
+	 * @param float  $total_time
640
+	 * @return string
641
+	 */
642
+	public function format_time($timer_name, $total_time)
643
+	{
644
+		return Benchmark::formatTime($timer_name, $total_time);
645
+	}
646 646
 
647 647
 
648 648
 
@@ -655,31 +655,31 @@  discard block
 block discarded – undo
655 655
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
656 656
  */
657 657
 if (class_exists('Kint') && ! function_exists('dump_wp_query')) {
658
-    function dump_wp_query()
659
-    {
660
-        global $wp_query;
661
-        d($wp_query);
662
-    }
658
+	function dump_wp_query()
659
+	{
660
+		global $wp_query;
661
+		d($wp_query);
662
+	}
663 663
 }
664 664
 /**
665 665
  * borrowed from Kint Debugger
666 666
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
667 667
  */
668 668
 if (class_exists('Kint') && ! function_exists('dump_wp')) {
669
-    function dump_wp()
670
-    {
671
-        global $wp;
672
-        d($wp);
673
-    }
669
+	function dump_wp()
670
+	{
671
+		global $wp;
672
+		d($wp);
673
+	}
674 674
 }
675 675
 /**
676 676
  * borrowed from Kint Debugger
677 677
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
678 678
  */
679 679
 if (class_exists('Kint') && ! function_exists('dump_post')) {
680
-    function dump_post()
681
-    {
682
-        global $post;
683
-        d($post);
684
-    }
680
+	function dump_post()
681
+	{
682
+		global $post;
683
+		d($post);
684
+	}
685 685
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\Benchmark;
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
 
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
     public static function instance()
41 41
     {
42 42
         // check if class object is instantiated, and instantiated properly
43
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
43
+        if ( ! self::$_instance instanceof EEH_Debug_Tools) {
44 44
             self::$_instance = new self();
45 45
         }
46 46
         return self::$_instance;
@@ -54,13 +54,13 @@  discard block
 block discarded – undo
54 54
     private function __construct()
55 55
     {
56 56
         // load Kint PHP debugging library
57
-        if (! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php')) {
57
+        if ( ! class_exists('Kint') && file_exists(EE_PLUGIN_DIR_PATH.'tests'.DS.'kint'.DS.'Kint.class.php')) {
58 58
             // despite EE4 having a check for an existing copy of the Kint debugging class,
59 59
             // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
60 60
             // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
61 61
             // so we've moved it to our test folder so that it is not included with production releases
62 62
             // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
63
-            require_once(EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php');
63
+            require_once(EE_PLUGIN_DIR_PATH.'tests'.DS.'kint'.DS.'Kint.class.php');
64 64
         }
65 65
         // if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
66 66
         //add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
      */
81 81
     public static function show_db_name()
82 82
     {
83
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
83
+        if ( ! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
84 84
             echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
85 85
                  . DB_NAME
86 86
                  . '</p>';
@@ -131,11 +131,11 @@  discard block
 block discarded – undo
131 131
         echo '<br/><br/><br/><h3>Hooked Functions</h3>';
132 132
         if ($tag) {
133 133
             $hook[$tag] = $wp_filter[$tag];
134
-            if (! is_array($hook[$tag])) {
134
+            if ( ! is_array($hook[$tag])) {
135 135
                 trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
136 136
                 return;
137 137
             }
138
-            echo '<h5>For Tag: ' . $tag . '</h5>';
138
+            echo '<h5>For Tag: '.$tag.'</h5>';
139 139
         } else {
140 140
             $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
141 141
             ksort($hook);
@@ -188,17 +188,17 @@  discard block
 block discarded – undo
188 188
     {
189 189
         if (WP_DEBUG) {
190 190
             $activation_errors = ob_get_contents();
191
-            if (! empty($activation_errors)) {
192
-                $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
191
+            if ( ! empty($activation_errors)) {
192
+                $activation_errors = date('Y-m-d H:i:s')."\n".$activation_errors;
193 193
             }
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
194
+            espresso_load_required('EEH_File', EE_HELPERS.'EEH_File.helper.php');
195 195
             if (class_exists('EEH_File')) {
196 196
                 try {
197 197
                     EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html'
198
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html'
199 199
                     );
200 200
                     EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
201
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html',
202 202
                         $activation_errors
203 203
                     );
204 204
                 } catch (EE_Error $e) {
@@ -216,11 +216,11 @@  discard block
 block discarded – undo
216 216
             } else {
217 217
                 // old school attempt
218 218
                 file_put_contents(
219
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html',
219
+                    EVENT_ESPRESSO_UPLOAD_DIR.'logs'.DS.'espresso_plugin_activation_errors.html',
220 220
                     $activation_errors
221 221
                 );
222 222
             }
223
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
223
+            $activation_errors = get_option('ee_plugin_activation_errors', '').$activation_errors;
224 224
             update_option('ee_plugin_activation_errors', $activation_errors);
225 225
         }
226 226
     }
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
         // don't trigger error if doing ajax,
281 281
         // instead we'll add a transient EE_Error notice that in theory should show on the next request.
282 282
         if (defined('DOING_AJAX') && DOING_AJAX) {
283
-            $error_message .= ' ' . esc_html__(
283
+            $error_message .= ' '.esc_html__(
284 284
                     'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
285 285
                     'event_espresso'
286 286
                 );
@@ -324,16 +324,16 @@  discard block
 block discarded – undo
324 324
         $debug_key = 'EE_DEBUG_SPCO'
325 325
     ) {
326 326
         if (WP_DEBUG) {
327
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
327
+            $debug_key = $debug_key.'_'.EE_Session::instance()->id();
328 328
             $debug_data = get_option($debug_key, array());
329 329
             $default_data = array(
330
-                $class => $func . '() : ' . $line,
330
+                $class => $func.'() : '.$line,
331 331
                 'REQ'  => $display_request ? $_REQUEST : '',
332 332
             );
333 333
             // don't serialize objects
334 334
             $info = self::strip_objects($info);
335 335
             $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[$index])) {
336
+            if ( ! isset($debug_data[$index])) {
337 337
                 $debug_data[$index] = array();
338 338
             }
339 339
             $debug_data[$index][microtime()] = array_merge($default_data, $info);
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
                 unset($info[$key]);
370 370
             }
371 371
         }
372
-        return (array)$info;
372
+        return (array) $info;
373 373
     }
374 374
 
375 375
 
@@ -399,8 +399,8 @@  discard block
 block discarded – undo
399 399
         $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
400 400
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
401 401
         $result .= $is_method
402
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
403
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
402
+            ? EEH_Debug_Tools::grey_span('::').EEH_Debug_Tools::orange_span($var.'()')
403
+            : EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span($var);
404 404
         $result .= EEH_Debug_Tools::file_and_line($file, $line);
405 405
         $result .= EEH_Debug_Tools::headingX($heading_tag);
406 406
         if ($die) {
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
             return "\n{$var_name}";
424 424
         }
425 425
         $margin = "25px 0 0 {$margin}";
426
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
426
+        return '<'.$heading_tag.' style="color:#2EA2CC; margin:'.$margin.';"><b>'.$var_name.'</b>';
427 427
     }
428 428
 
429 429
 
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
         if (defined('EE_TESTS_DIR')) {
438 438
             return '';
439 439
         }
440
-        return '</' . $heading_tag . '>';
440
+        return '</'.$heading_tag.'>';
441 441
     }
442 442
 
443 443
 
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
         if (defined('EE_TESTS_DIR')) {
452 452
             return $content;
453 453
         }
454
-        return '<span style="color:#999">' . $content . '</span>';
454
+        return '<span style="color:#999">'.$content.'</span>';
455 455
     }
456 456
 
457 457
 
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
             return '';
468 468
         }
469 469
         if (defined('EE_TESTS_DIR')) {
470
-            return "\n\t(" . $file . ' line no: ' . $line . ' ) ';
470
+            return "\n\t(".$file.' line no: '.$line.' ) ';
471 471
         }
472 472
         return '<br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
473 473
                . $file
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
         if (defined('EE_TESTS_DIR')) {
488 488
             return $content;
489 489
         }
490
-        return '<span style="color:#E76700">' . $content . '</span>';
490
+        return '<span style="color:#E76700">'.$content.'</span>';
491 491
     }
492 492
 
493 493
 
@@ -502,9 +502,9 @@  discard block
 block discarded – undo
502 502
         var_dump($var);
503 503
         $var = ob_get_clean();
504 504
         if (defined('EE_TESTS_DIR')) {
505
-            return "\n" . $var;
505
+            return "\n".$var;
506 506
         }
507
-        return '<pre style="color:#999; padding:1em; background: #fff">' . $var . '</pre>';
507
+        return '<pre style="color:#999; padding:1em; background: #fff">'.$var.'</pre>';
508 508
     }
509 509
 
510 510
 
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
         $var_name = ucwords(str_replace(array('$', '_'), array('', ' '), $var_name));
548 548
         $heading_tag = is_int($heading_tag) ? "h{$heading_tag}" : 'h5';
549 549
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin);
550
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
550
+        $result .= EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span(
551 551
                 EEH_Debug_Tools::pre_span($var)
552 552
             );
553 553
         $result .= EEH_Debug_Tools::file_and_line($file, $line);
Please login to merge, or discard this patch.