Completed
Branch barista (01af75)
by
unknown
60:31 queued 51:15
created
core/db_models/EEM_Country.model.php 2 patches
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -11,112 +11,112 @@
 block discarded – undo
11 11
 class EEM_Country extends EEM_Base
12 12
 {
13 13
 
14
-    // private instance of the Attendee object
15
-    protected static $_instance = null;
16
-    // array of all countries
17
-    private static $_all_countries = false;
18
-    // array of all active countries
19
-    private static $_active_countries = false;
14
+	// private instance of the Attendee object
15
+	protected static $_instance = null;
16
+	// array of all countries
17
+	private static $_all_countries = false;
18
+	// array of all active countries
19
+	private static $_active_countries = false;
20 20
 
21 21
 
22 22
 
23
-    /**
24
-     * Resets the country
25
-     * @return EEM_Country
26
-     */
27
-    public static function reset($timezone = null)
28
-    {
29
-        self::$_active_countries = null;
30
-        self::$_all_countries = null;
31
-        return parent::reset($timezone);
32
-    }
23
+	/**
24
+	 * Resets the country
25
+	 * @return EEM_Country
26
+	 */
27
+	public static function reset($timezone = null)
28
+	{
29
+		self::$_active_countries = null;
30
+		self::$_all_countries = null;
31
+		return parent::reset($timezone);
32
+	}
33 33
 
34
-    protected function __construct($timezone = null)
35
-    {
36
-        $this->singular_item = esc_html__('Country', 'event_espresso');
37
-        $this->plural_item = esc_html__('Countries', 'event_espresso');
34
+	protected function __construct($timezone = null)
35
+	{
36
+		$this->singular_item = esc_html__('Country', 'event_espresso');
37
+		$this->plural_item = esc_html__('Countries', 'event_espresso');
38 38
 
39 39
 
40
-        $this->_tables = array(
41
-            'Country'=> new EE_Primary_Table('esp_country', 'CNT_ISO')
42
-        );
43
-        $this->_fields = array(
44
-            'Country'=>array(
45
-                'CNT_active' => new EE_Boolean_Field('CNT_active', esc_html__('Country Appears in Dropdown Select Lists', 'event_espresso'), false, true),
46
-                'CNT_ISO'=> new EE_Primary_Key_String_Field('CNT_ISO', esc_html__('Country ISO Code', 'event_espresso')),
47
-                'CNT_ISO3'=>new EE_All_Caps_Text_Field('CNT_ISO3', esc_html__('Country ISO3 Code', 'event_espresso'), false, ''),
48
-                'RGN_ID'=>new EE_Integer_Field('RGN_ID', esc_html__('Region ID', 'event_espresso'), false, 0),// should be a foreign key, but no region table exists yet
49
-                'CNT_name'=>new EE_Plain_Text_Field('CNT_name', esc_html__('Country Name', 'event_espresso'), false, ''),
50
-                'CNT_cur_code'=>new EE_All_Caps_Text_Field('CNT_cur_code', esc_html__('Country Currency Code', 'event_espresso'), false),
51
-                'CNT_cur_single' => new EE_Plain_Text_Field('CNT_cur_single', esc_html__('Currency Name Singular', 'event_espresso'), false),
52
-                'CNT_cur_plural' => new EE_Plain_Text_Field('CNT_cur_plural', esc_html__('Currency Name Plural', 'event_espresso'), false),
53
-                'CNT_cur_sign' => new EE_Plain_Text_Field('CNT_cur_sign', esc_html__('Currency Sign', 'event_espresso'), false),
54
-                'CNT_cur_sign_b4' => new EE_Boolean_Field('CNT_cur_sign_b4', esc_html__('Currency Sign Before Number', 'event_espresso'), false, true),
55
-                'CNT_cur_dec_plc' => new EE_Integer_Field('CNT_cur_dec_plc', esc_html__('Currency Decimal Places', 'event_espresso'), false, 2),
56
-                'CNT_cur_dec_mrk' => new EE_Plain_Text_Field('CNT_cur_dec_mrk', esc_html__('Currency Decimal Mark', 'event_espresso'), false, '.'),
57
-                'CNT_cur_thsnds' => new EE_Plain_Text_Field('CNT_cur_thsnds', esc_html__('Currency Thousands Separator', 'event_espresso'), false, ','),
58
-                'CNT_tel_code' => new EE_Plain_Text_Field('CNT_tel_code', esc_html__('Country Telephone Code', 'event_espresso'), false, ''),
59
-                'CNT_is_EU' => new EE_Boolean_Field('CNT_is_EU', esc_html__('Country is Member of EU', 'event_espresso'), false, false)
60
-            ));
61
-        $this->_model_relations = array(
62
-            'Attendee'=>new EE_Has_Many_Relation(),
63
-            'State'=>new EE_Has_Many_Relation(),
64
-            'Venue'=>new EE_Has_Many_Relation(),
65
-        );
66
-        // only anyone to view, but only those with the default role can do anything
67
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
40
+		$this->_tables = array(
41
+			'Country'=> new EE_Primary_Table('esp_country', 'CNT_ISO')
42
+		);
43
+		$this->_fields = array(
44
+			'Country'=>array(
45
+				'CNT_active' => new EE_Boolean_Field('CNT_active', esc_html__('Country Appears in Dropdown Select Lists', 'event_espresso'), false, true),
46
+				'CNT_ISO'=> new EE_Primary_Key_String_Field('CNT_ISO', esc_html__('Country ISO Code', 'event_espresso')),
47
+				'CNT_ISO3'=>new EE_All_Caps_Text_Field('CNT_ISO3', esc_html__('Country ISO3 Code', 'event_espresso'), false, ''),
48
+				'RGN_ID'=>new EE_Integer_Field('RGN_ID', esc_html__('Region ID', 'event_espresso'), false, 0),// should be a foreign key, but no region table exists yet
49
+				'CNT_name'=>new EE_Plain_Text_Field('CNT_name', esc_html__('Country Name', 'event_espresso'), false, ''),
50
+				'CNT_cur_code'=>new EE_All_Caps_Text_Field('CNT_cur_code', esc_html__('Country Currency Code', 'event_espresso'), false),
51
+				'CNT_cur_single' => new EE_Plain_Text_Field('CNT_cur_single', esc_html__('Currency Name Singular', 'event_espresso'), false),
52
+				'CNT_cur_plural' => new EE_Plain_Text_Field('CNT_cur_plural', esc_html__('Currency Name Plural', 'event_espresso'), false),
53
+				'CNT_cur_sign' => new EE_Plain_Text_Field('CNT_cur_sign', esc_html__('Currency Sign', 'event_espresso'), false),
54
+				'CNT_cur_sign_b4' => new EE_Boolean_Field('CNT_cur_sign_b4', esc_html__('Currency Sign Before Number', 'event_espresso'), false, true),
55
+				'CNT_cur_dec_plc' => new EE_Integer_Field('CNT_cur_dec_plc', esc_html__('Currency Decimal Places', 'event_espresso'), false, 2),
56
+				'CNT_cur_dec_mrk' => new EE_Plain_Text_Field('CNT_cur_dec_mrk', esc_html__('Currency Decimal Mark', 'event_espresso'), false, '.'),
57
+				'CNT_cur_thsnds' => new EE_Plain_Text_Field('CNT_cur_thsnds', esc_html__('Currency Thousands Separator', 'event_espresso'), false, ','),
58
+				'CNT_tel_code' => new EE_Plain_Text_Field('CNT_tel_code', esc_html__('Country Telephone Code', 'event_espresso'), false, ''),
59
+				'CNT_is_EU' => new EE_Boolean_Field('CNT_is_EU', esc_html__('Country is Member of EU', 'event_espresso'), false, false)
60
+			));
61
+		$this->_model_relations = array(
62
+			'Attendee'=>new EE_Has_Many_Relation(),
63
+			'State'=>new EE_Has_Many_Relation(),
64
+			'Venue'=>new EE_Has_Many_Relation(),
65
+		);
66
+		// only anyone to view, but only those with the default role can do anything
67
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
68 68
 
69
-        parent::__construct($timezone);
70
-    }
69
+		parent::__construct($timezone);
70
+	}
71 71
 
72 72
 
73 73
 
74 74
 
75
-    /**
76
-    *       _get_countries
77
-    *
78
-    *       @access     public
79
-    *       @return         array
80
-    */
81
-    public function get_all_countries()
82
-    {
83
-        if (! self::$_all_countries) {
84
-            self::$_all_countries = $this->get_all(array( 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=> array( 0,99999 )));
85
-        }
86
-        return self::$_all_countries;
87
-    }
75
+	/**
76
+	 *       _get_countries
77
+	 *
78
+	 *       @access     public
79
+	 *       @return         array
80
+	 */
81
+	public function get_all_countries()
82
+	{
83
+		if (! self::$_all_countries) {
84
+			self::$_all_countries = $this->get_all(array( 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=> array( 0,99999 )));
85
+		}
86
+		return self::$_all_countries;
87
+	}
88 88
 
89
-    /**
90
-    *       _get_countries
91
-    *       Gets and caches the list of active countries. If you know the list of active countries
92
-    *       has changed during this request, first use EEM_Country::reset() to flush the cache
93
-    *       @access     public
94
-    *       @return         array
95
-    */
96
-    public function get_all_active_countries()
97
-    {
98
-        if (! self::$_active_countries) {
99
-            self::$_active_countries =  $this->get_all(array( array( 'CNT_active' => true ), 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=>array( 0, 99999 )));
100
-        }
101
-        return self::$_active_countries;
102
-    }
89
+	/**
90
+	 *       _get_countries
91
+	 *       Gets and caches the list of active countries. If you know the list of active countries
92
+	 *       has changed during this request, first use EEM_Country::reset() to flush the cache
93
+	 *       @access     public
94
+	 *       @return         array
95
+	 */
96
+	public function get_all_active_countries()
97
+	{
98
+		if (! self::$_active_countries) {
99
+			self::$_active_countries =  $this->get_all(array( array( 'CNT_active' => true ), 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=>array( 0, 99999 )));
100
+		}
101
+		return self::$_active_countries;
102
+	}
103 103
 
104
-    /**
105
-     * Gets the country's name by its ISO
106
-     * @param string $country_ISO
107
-     * @return string
108
-     */
109
-    public function get_country_name_by_ISO($country_ISO)
110
-    {
111
-        if (isset(self::$_all_countries[ $country_ISO ]) &&
112
-                self::$_all_countries[ $country_ISO ] instanceof EE_Country) {
113
-            return self::$_all_countries[ $country_ISO ]->name();
114
-        }
115
-        $names = $this->get_col(array( array( 'CNT_ISO' => $country_ISO ), 'limit' => 1), 'CNT_name');
116
-        if (is_array($names) && ! empty($names)) {
117
-            return reset($names);
118
-        } else {
119
-            return '';
120
-        }
121
-    }
104
+	/**
105
+	 * Gets the country's name by its ISO
106
+	 * @param string $country_ISO
107
+	 * @return string
108
+	 */
109
+	public function get_country_name_by_ISO($country_ISO)
110
+	{
111
+		if (isset(self::$_all_countries[ $country_ISO ]) &&
112
+				self::$_all_countries[ $country_ISO ] instanceof EE_Country) {
113
+			return self::$_all_countries[ $country_ISO ]->name();
114
+		}
115
+		$names = $this->get_col(array( array( 'CNT_ISO' => $country_ISO ), 'limit' => 1), 'CNT_name');
116
+		if (is_array($names) && ! empty($names)) {
117
+			return reset($names);
118
+		} else {
119
+			return '';
120
+		}
121
+	}
122 122
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
                 'CNT_active' => new EE_Boolean_Field('CNT_active', esc_html__('Country Appears in Dropdown Select Lists', 'event_espresso'), false, true),
46 46
                 'CNT_ISO'=> new EE_Primary_Key_String_Field('CNT_ISO', esc_html__('Country ISO Code', 'event_espresso')),
47 47
                 'CNT_ISO3'=>new EE_All_Caps_Text_Field('CNT_ISO3', esc_html__('Country ISO3 Code', 'event_espresso'), false, ''),
48
-                'RGN_ID'=>new EE_Integer_Field('RGN_ID', esc_html__('Region ID', 'event_espresso'), false, 0),// should be a foreign key, but no region table exists yet
48
+                'RGN_ID'=>new EE_Integer_Field('RGN_ID', esc_html__('Region ID', 'event_espresso'), false, 0), // should be a foreign key, but no region table exists yet
49 49
                 'CNT_name'=>new EE_Plain_Text_Field('CNT_name', esc_html__('Country Name', 'event_espresso'), false, ''),
50 50
                 'CNT_cur_code'=>new EE_All_Caps_Text_Field('CNT_cur_code', esc_html__('Country Currency Code', 'event_espresso'), false),
51 51
                 'CNT_cur_single' => new EE_Plain_Text_Field('CNT_cur_single', esc_html__('Currency Name Singular', 'event_espresso'), false),
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
             'Venue'=>new EE_Has_Many_Relation(),
65 65
         );
66 66
         // only anyone to view, but only those with the default role can do anything
67
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
67
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
68 68
 
69 69
         parent::__construct($timezone);
70 70
     }
@@ -80,8 +80,8 @@  discard block
 block discarded – undo
80 80
     */
81 81
     public function get_all_countries()
82 82
     {
83
-        if (! self::$_all_countries) {
84
-            self::$_all_countries = $this->get_all(array( 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=> array( 0,99999 )));
83
+        if ( ! self::$_all_countries) {
84
+            self::$_all_countries = $this->get_all(array('order_by'=>array('CNT_name'=>'ASC'), 'limit'=> array(0, 99999)));
85 85
         }
86 86
         return self::$_all_countries;
87 87
     }
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
     */
96 96
     public function get_all_active_countries()
97 97
     {
98
-        if (! self::$_active_countries) {
99
-            self::$_active_countries =  $this->get_all(array( array( 'CNT_active' => true ), 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=>array( 0, 99999 )));
98
+        if ( ! self::$_active_countries) {
99
+            self::$_active_countries = $this->get_all(array(array('CNT_active' => true), 'order_by'=>array('CNT_name'=>'ASC'), 'limit'=>array(0, 99999)));
100 100
         }
101 101
         return self::$_active_countries;
102 102
     }
@@ -108,11 +108,11 @@  discard block
 block discarded – undo
108 108
      */
109 109
     public function get_country_name_by_ISO($country_ISO)
110 110
     {
111
-        if (isset(self::$_all_countries[ $country_ISO ]) &&
112
-                self::$_all_countries[ $country_ISO ] instanceof EE_Country) {
113
-            return self::$_all_countries[ $country_ISO ]->name();
111
+        if (isset(self::$_all_countries[$country_ISO]) &&
112
+                self::$_all_countries[$country_ISO] instanceof EE_Country) {
113
+            return self::$_all_countries[$country_ISO]->name();
114 114
         }
115
-        $names = $this->get_col(array( array( 'CNT_ISO' => $country_ISO ), 'limit' => 1), 'CNT_name');
115
+        $names = $this->get_col(array(array('CNT_ISO' => $country_ISO), 'limit' => 1), 'CNT_name');
116 116
         if (is_array($names) && ! empty($names)) {
117 117
             return reset($names);
118 118
         } else {
Please login to merge, or discard this patch.
core/db_models/EEM_State.model.php 2 patches
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -11,161 +11,161 @@
 block discarded – undo
11 11
 class EEM_State extends EEM_Base
12 12
 {
13 13
 
14
-    // private instance of the Attendee object
15
-    protected static $_instance = null;
16
-    // array of all states
17
-    private static $_all_states = false;
18
-    // array of all active states
19
-    private static $_active_states = false;
20
-
21
-    protected function __construct($timezone = null)
22
-    {
23
-        $this->singular_item = __('State/Province', 'event_espresso');
24
-        $this->plural_item = __('States/Provinces', 'event_espresso');
25
-
26
-        $this->_tables = array(
27
-            'State'=> new EE_Primary_Table('esp_state', 'STA_ID')
28
-        );
29
-
30
-        $this->_fields = array(
31
-            'State'=>array(
32
-                'STA_ID'=> new EE_Primary_Key_Int_Field('STA_ID', __('State ID', 'event_espresso')),
33
-                'CNT_ISO'=> new EE_Foreign_Key_String_Field('CNT_ISO', __('Country ISO Code', 'event_espresso'), false, null, 'Country'),
34
-                'STA_abbrev' => new EE_Plain_Text_Field('STA_abbrev', __('State Abbreviation', 'event_espresso'), false, ''),
35
-                'STA_name' => new EE_Plain_Text_Field('STA_name', __('State Name', 'event_espresso'), false, ''),
36
-                'STA_active'=> new EE_Boolean_Field('STA_active', __('State Active Flag', 'event_espresso'), false, false)
37
-                ));
38
-        $this->_model_relations = array(
39
-            'Attendee'=>new EE_Has_Many_Relation(),
40
-            'Country' => new EE_Belongs_To_Relation(),
41
-            'Venue'=>new EE_Has_Many_Relation(),
42
-        );
43
-        // this model is generally available for reading
44
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
45
-        // @todo: only show STA_active
46
-        parent::__construct($timezone);
47
-    }
48
-
49
-
50
-
51
-
52
-    /**
53
-    *   reset_cached_states
54
-    *
55
-    *   @access     private
56
-    *   @return         void
57
-    */
58
-    public function reset_cached_states()
59
-    {
60
-        EEM_State::$_active_states = array();
61
-        EEM_State::$_all_states = array();
62
-    }
63
-
64
-
65
-
66
-
67
-    /**
68
-    *       _get_states
69
-    *
70
-    *       @access     private
71
-    *       @return         array
72
-    */
73
-    public function get_all_states()
74
-    {
75
-        if (! self::$_all_states) {
76
-            self::$_all_states = $this->get_all(array( 'order_by'=>array( 'STA_name'=>'ASC' ), 'limit'=> array( 0, 99999 )));
77
-        }
78
-        return self::$_all_states;
79
-    }
80
-
81
-
82
-
83
-    /**
84
-     *        _get_states
85
-     *
86
-     * @access        public
87
-     * @param array $countries
88
-     * @param bool  $flush_cache
89
-     * @return        array
90
-     */
91
-    public function get_all_active_states($countries = array(), $flush_cache = false)
92
-    {
93
-        if (! self::$_active_states || $flush_cache) {
94
-            $countries = is_array($countries) && ! empty($countries) ? $countries : EEM_Country::instance()->get_all_active_countries();
95
-            self::$_active_states =  $this->get_all(array(
96
-                array( 'STA_active' => true, 'CNT_ISO' => array( 'IN', array_keys($countries))),
97
-                'order_by' => array( 'STA_name'=>'ASC' ),
98
-                'limit' => array( 0, 99999 ),
99
-                'force_join' => array( 'Country' )
100
-            ));
101
-        }
102
-        return self::$_active_states;
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     *  get_all_states_of_active_countries
109
-     * @return array
110
-     */
111
-    public function get_all_states_of_active_countries()
112
-    {
113
-        if ($states = $this->get_all(array( array( 'Country.CNT_active' => true, 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
114
-            return $states;
115
-        }
116
-        return false;
117
-    }
118
-
119
-
120
-
121
-    /**
122
-     *  get_all_states_of_active_countries
123
-     * @return array
124
-     */
125
-    public function get_all_active_states_for_these_countries($countries)
126
-    {
127
-        if (! $countries) {
128
-            return false;
129
-        }
130
-        if ($states = $this->get_all(array(  array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries)), 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
131
-            return $states;
132
-        }
133
-        return false;
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     *  get_all_states_of_active_countries
140
-     * @return array
141
-     */
142
-    public function get_all_states_for_these_countries($countries)
143
-    {
144
-        if (! $countries) {
145
-            return false;
146
-        }
147
-        if ($states = $this->get_all(array( array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries))),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
148
-            return $states;
149
-        }
150
-        return false;
151
-    }
152
-
153
-    /**
154
-     * Gets the state's name by its ID
155
-     * @param string $state_ID
156
-     * @return string
157
-     */
158
-    public function get_state_name_by_ID($state_ID)
159
-    {
160
-        if (isset(self::$_all_states[ $state_ID ]) &&
161
-                self::$_all_states[ $state_ID ] instanceof EE_State) {
162
-            return self::$_all_states[ $state_ID ]->name();
163
-        }
164
-        $names = $this->get_col(array( array( 'STA_ID' => $state_ID ), 'limit' => 1), 'STA_name');
165
-        if (is_array($names) && ! empty($names)) {
166
-            return reset($names);
167
-        } else {
168
-            return '';
169
-        }
170
-    }
14
+	// private instance of the Attendee object
15
+	protected static $_instance = null;
16
+	// array of all states
17
+	private static $_all_states = false;
18
+	// array of all active states
19
+	private static $_active_states = false;
20
+
21
+	protected function __construct($timezone = null)
22
+	{
23
+		$this->singular_item = __('State/Province', 'event_espresso');
24
+		$this->plural_item = __('States/Provinces', 'event_espresso');
25
+
26
+		$this->_tables = array(
27
+			'State'=> new EE_Primary_Table('esp_state', 'STA_ID')
28
+		);
29
+
30
+		$this->_fields = array(
31
+			'State'=>array(
32
+				'STA_ID'=> new EE_Primary_Key_Int_Field('STA_ID', __('State ID', 'event_espresso')),
33
+				'CNT_ISO'=> new EE_Foreign_Key_String_Field('CNT_ISO', __('Country ISO Code', 'event_espresso'), false, null, 'Country'),
34
+				'STA_abbrev' => new EE_Plain_Text_Field('STA_abbrev', __('State Abbreviation', 'event_espresso'), false, ''),
35
+				'STA_name' => new EE_Plain_Text_Field('STA_name', __('State Name', 'event_espresso'), false, ''),
36
+				'STA_active'=> new EE_Boolean_Field('STA_active', __('State Active Flag', 'event_espresso'), false, false)
37
+				));
38
+		$this->_model_relations = array(
39
+			'Attendee'=>new EE_Has_Many_Relation(),
40
+			'Country' => new EE_Belongs_To_Relation(),
41
+			'Venue'=>new EE_Has_Many_Relation(),
42
+		);
43
+		// this model is generally available for reading
44
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
45
+		// @todo: only show STA_active
46
+		parent::__construct($timezone);
47
+	}
48
+
49
+
50
+
51
+
52
+	/**
53
+	 *   reset_cached_states
54
+	 *
55
+	 *   @access     private
56
+	 *   @return         void
57
+	 */
58
+	public function reset_cached_states()
59
+	{
60
+		EEM_State::$_active_states = array();
61
+		EEM_State::$_all_states = array();
62
+	}
63
+
64
+
65
+
66
+
67
+	/**
68
+	 *       _get_states
69
+	 *
70
+	 *       @access     private
71
+	 *       @return         array
72
+	 */
73
+	public function get_all_states()
74
+	{
75
+		if (! self::$_all_states) {
76
+			self::$_all_states = $this->get_all(array( 'order_by'=>array( 'STA_name'=>'ASC' ), 'limit'=> array( 0, 99999 )));
77
+		}
78
+		return self::$_all_states;
79
+	}
80
+
81
+
82
+
83
+	/**
84
+	 *        _get_states
85
+	 *
86
+	 * @access        public
87
+	 * @param array $countries
88
+	 * @param bool  $flush_cache
89
+	 * @return        array
90
+	 */
91
+	public function get_all_active_states($countries = array(), $flush_cache = false)
92
+	{
93
+		if (! self::$_active_states || $flush_cache) {
94
+			$countries = is_array($countries) && ! empty($countries) ? $countries : EEM_Country::instance()->get_all_active_countries();
95
+			self::$_active_states =  $this->get_all(array(
96
+				array( 'STA_active' => true, 'CNT_ISO' => array( 'IN', array_keys($countries))),
97
+				'order_by' => array( 'STA_name'=>'ASC' ),
98
+				'limit' => array( 0, 99999 ),
99
+				'force_join' => array( 'Country' )
100
+			));
101
+		}
102
+		return self::$_active_states;
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 *  get_all_states_of_active_countries
109
+	 * @return array
110
+	 */
111
+	public function get_all_states_of_active_countries()
112
+	{
113
+		if ($states = $this->get_all(array( array( 'Country.CNT_active' => true, 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
114
+			return $states;
115
+		}
116
+		return false;
117
+	}
118
+
119
+
120
+
121
+	/**
122
+	 *  get_all_states_of_active_countries
123
+	 * @return array
124
+	 */
125
+	public function get_all_active_states_for_these_countries($countries)
126
+	{
127
+		if (! $countries) {
128
+			return false;
129
+		}
130
+		if ($states = $this->get_all(array(  array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries)), 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
131
+			return $states;
132
+		}
133
+		return false;
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 *  get_all_states_of_active_countries
140
+	 * @return array
141
+	 */
142
+	public function get_all_states_for_these_countries($countries)
143
+	{
144
+		if (! $countries) {
145
+			return false;
146
+		}
147
+		if ($states = $this->get_all(array( array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries))),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
148
+			return $states;
149
+		}
150
+		return false;
151
+	}
152
+
153
+	/**
154
+	 * Gets the state's name by its ID
155
+	 * @param string $state_ID
156
+	 * @return string
157
+	 */
158
+	public function get_state_name_by_ID($state_ID)
159
+	{
160
+		if (isset(self::$_all_states[ $state_ID ]) &&
161
+				self::$_all_states[ $state_ID ] instanceof EE_State) {
162
+			return self::$_all_states[ $state_ID ]->name();
163
+		}
164
+		$names = $this->get_col(array( array( 'STA_ID' => $state_ID ), 'limit' => 1), 'STA_name');
165
+		if (is_array($names) && ! empty($names)) {
166
+			return reset($names);
167
+		} else {
168
+			return '';
169
+		}
170
+	}
171 171
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
             'Venue'=>new EE_Has_Many_Relation(),
42 42
         );
43 43
         // this model is generally available for reading
44
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
44
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
45 45
         // @todo: only show STA_active
46 46
         parent::__construct($timezone);
47 47
     }
@@ -72,8 +72,8 @@  discard block
 block discarded – undo
72 72
     */
73 73
     public function get_all_states()
74 74
     {
75
-        if (! self::$_all_states) {
76
-            self::$_all_states = $this->get_all(array( 'order_by'=>array( 'STA_name'=>'ASC' ), 'limit'=> array( 0, 99999 )));
75
+        if ( ! self::$_all_states) {
76
+            self::$_all_states = $this->get_all(array('order_by'=>array('STA_name'=>'ASC'), 'limit'=> array(0, 99999)));
77 77
         }
78 78
         return self::$_all_states;
79 79
     }
@@ -90,13 +90,13 @@  discard block
 block discarded – undo
90 90
      */
91 91
     public function get_all_active_states($countries = array(), $flush_cache = false)
92 92
     {
93
-        if (! self::$_active_states || $flush_cache) {
93
+        if ( ! self::$_active_states || $flush_cache) {
94 94
             $countries = is_array($countries) && ! empty($countries) ? $countries : EEM_Country::instance()->get_all_active_countries();
95
-            self::$_active_states =  $this->get_all(array(
96
-                array( 'STA_active' => true, 'CNT_ISO' => array( 'IN', array_keys($countries))),
97
-                'order_by' => array( 'STA_name'=>'ASC' ),
98
-                'limit' => array( 0, 99999 ),
99
-                'force_join' => array( 'Country' )
95
+            self::$_active_states = $this->get_all(array(
96
+                array('STA_active' => true, 'CNT_ISO' => array('IN', array_keys($countries))),
97
+                'order_by' => array('STA_name'=>'ASC'),
98
+                'limit' => array(0, 99999),
99
+                'force_join' => array('Country')
100 100
             ));
101 101
         }
102 102
         return self::$_active_states;
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
      */
111 111
     public function get_all_states_of_active_countries()
112 112
     {
113
-        if ($states = $this->get_all(array( array( 'Country.CNT_active' => true, 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
113
+        if ($states = $this->get_all(array(array('Country.CNT_active' => true, 'STA_active' => true), 'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')))) {
114 114
             return $states;
115 115
         }
116 116
         return false;
@@ -124,10 +124,10 @@  discard block
 block discarded – undo
124 124
      */
125 125
     public function get_all_active_states_for_these_countries($countries)
126 126
     {
127
-        if (! $countries) {
127
+        if ( ! $countries) {
128 128
             return false;
129 129
         }
130
-        if ($states = $this->get_all(array(  array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries)), 'STA_active' => true ),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
130
+        if ($states = $this->get_all(array(array('Country.CNT_ISO' => array('IN', array_keys($countries)), 'STA_active' => true), 'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')))) {
131 131
             return $states;
132 132
         }
133 133
         return false;
@@ -141,10 +141,10 @@  discard block
 block discarded – undo
141 141
      */
142 142
     public function get_all_states_for_these_countries($countries)
143 143
     {
144
-        if (! $countries) {
144
+        if ( ! $countries) {
145 145
             return false;
146 146
         }
147
-        if ($states = $this->get_all(array( array( 'Country.CNT_ISO' => array( 'IN', array_keys($countries))),  'order_by' => array( 'Country.CNT_name' => 'ASC', 'STA_name' => 'ASC' )))) {
147
+        if ($states = $this->get_all(array(array('Country.CNT_ISO' => array('IN', array_keys($countries))), 'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')))) {
148 148
             return $states;
149 149
         }
150 150
         return false;
@@ -157,11 +157,11 @@  discard block
 block discarded – undo
157 157
      */
158 158
     public function get_state_name_by_ID($state_ID)
159 159
     {
160
-        if (isset(self::$_all_states[ $state_ID ]) &&
161
-                self::$_all_states[ $state_ID ] instanceof EE_State) {
162
-            return self::$_all_states[ $state_ID ]->name();
160
+        if (isset(self::$_all_states[$state_ID]) &&
161
+                self::$_all_states[$state_ID] instanceof EE_State) {
162
+            return self::$_all_states[$state_ID]->name();
163 163
         }
164
-        $names = $this->get_col(array( array( 'STA_ID' => $state_ID ), 'limit' => 1), 'STA_name');
164
+        $names = $this->get_col(array(array('STA_ID' => $state_ID), 'limit' => 1), 'STA_name');
165 165
         if (is_array($names) && ! empty($names)) {
166 166
             return reset($names);
167 167
         } else {
Please login to merge, or discard this patch.
core/templates/json_linked_data_for_event.template.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -28,8 +28,8 @@  discard block
 block discarded – undo
28 28
   "eventStatus": [ <?php echo $event_status; ?> ],
29 29
   "offers": [
30 30
     <?php
31
-    $i = 0;
32
-    foreach ($event_tickets as $ticket) {?>
31
+	$i = 0;
32
+	foreach ($event_tickets as $ticket) {?>
33 33
     {
34 34
       "@type": "Offer",
35 35
       "url": "<?php echo $event_permalink; ?>",
@@ -38,18 +38,18 @@  discard block
 block discarded – undo
38 38
       "price": "<?php echo $ticket['price']; ?>",
39 39
       "priceCurrency": "<?php echo $currency; ?>"
40 40
         <?php if (isset($ticket['availability'])) {
41
-            ?>,"availability": "http://schema.org/<?php echo $ticket['availability']; ?>"
41
+			?>,"availability": "http://schema.org/<?php echo $ticket['availability']; ?>"
42 42
         <?php } ?>
43 43
     }<?php
44
-    $i++;
45
-    if ($i < count($event_tickets)) {
46
-        echo ',';
47
-    }
48
-    }
49
-    ?>
44
+	$i++;
45
+	if ($i < count($event_tickets)) {
46
+		echo ',';
47
+	}
48
+	}
49
+	?>
50 50
     ]<?php
51
-    if ($venue_name) {
52
-        ?>,
51
+	if ($venue_name) {
52
+		?>,
53 53
   "location": {
54 54
     "@type": "Place",
55 55
     "name": <?php echo wp_json_encode($venue_name); ?>,
@@ -62,13 +62,13 @@  discard block
 block discarded – undo
62 62
     }
63 63
   }
64 64
         <?php
65
-    } ?>
65
+	} ?>
66 66
     <?php
67
-    if ($event_image) {
68
-        ?>,
67
+	if ($event_image) {
68
+		?>,
69 69
   "image": "<?php echo $event_image; ?>"
70 70
         <?php
71
-    } ?>
71
+	} ?>
72 72
     <?php do_action('AHEE__json_linked_data_for_event__template'); ?>
73 73
 }
74 74
 
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 1 patch
Indentation   +1609 added lines, -1609 removed lines patch added patch discarded remove patch
@@ -15,233 +15,233 @@  discard block
 block discarded – undo
15 15
 class EEH_Activation implements ResettableInterface
16 16
 {
17 17
 
18
-    /**
19
-     * constant used to indicate a cron task is no longer in use
20
-     */
21
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
22
-
23
-    /**
24
-     * WP_User->ID
25
-     *
26
-     * @var int
27
-     */
28
-    private static $_default_creator_id;
29
-
30
-    /**
31
-     * indicates whether or not we've already verified core's default data during this request,
32
-     * because after migrations are done, any addons activated while in maintenance mode
33
-     * will want to setup their own default data, and they might hook into core's default data
34
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
-     * This prevents doing that for EVERY single addon.
36
-     *
37
-     * @var boolean
38
-     */
39
-    protected static $_initialized_db_content_already_in_this_request = false;
40
-
41
-    /**
42
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
-     */
44
-    private static $table_analysis;
45
-
46
-    /**
47
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
48
-     */
49
-    private static $table_manager;
50
-
51
-
52
-    /**
53
-     * @return \EventEspresso\core\services\database\TableAnalysis
54
-     */
55
-    public static function getTableAnalysis()
56
-    {
57
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
-        }
60
-        return self::$table_analysis;
61
-    }
62
-
63
-
64
-    /**
65
-     * @return \EventEspresso\core\services\database\TableManager
66
-     */
67
-    public static function getTableManager()
68
-    {
69
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
-        }
72
-        return self::$table_manager;
73
-    }
74
-
75
-
76
-    /**
77
-     *    _ensure_table_name_has_prefix
78
-     *
79
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
-     * @access     public
81
-     * @static
82
-     * @param $table_name
83
-     * @return string
84
-     */
85
-    public static function ensure_table_name_has_prefix($table_name)
86
-    {
87
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
-    }
89
-
90
-
91
-    /**
92
-     *    system_initialization
93
-     *    ensures the EE configuration settings are loaded with at least default options set
94
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
-     *
96
-     * @access public
97
-     * @static
98
-     * @return void
99
-     */
100
-    public static function system_initialization()
101
-    {
102
-        EEH_Activation::reset_and_update_config();
103
-        // which is fired BEFORE activation of plugin anyways
104
-        EEH_Activation::verify_default_pages_exist();
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets the database schema and creates folders. This should
110
-     * be called on plugin activation and reactivation
111
-     *
112
-     * @return boolean success, whether the database and folders are setup properly
113
-     * @throws \EE_Error
114
-     */
115
-    public static function initialize_db_and_folders()
116
-    {
117
-        return EEH_Activation::create_database_tables();
118
-    }
119
-
120
-
121
-    /**
122
-     * assuming we have an up-to-date database schema, this will populate it
123
-     * with default and initial data. This should be called
124
-     * upon activation of a new plugin, reactivation, and at the end
125
-     * of running migration scripts
126
-     *
127
-     * @throws \EE_Error
128
-     */
129
-    public static function initialize_db_content()
130
-    {
131
-        // let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
-            return;
134
-        }
135
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
-
137
-        EEH_Activation::initialize_system_questions();
138
-        EEH_Activation::insert_default_status_codes();
139
-        EEH_Activation::generate_default_message_templates();
140
-        EEH_Activation::create_no_ticket_prices_array();
141
-        EEH_Activation::removeEmailConfirmFromAddressGroup();
142
-
143
-        EEH_Activation::validate_messages_system();
144
-        EEH_Activation::insert_default_payment_methods();
145
-        // in case we've
146
-        EEH_Activation::remove_cron_tasks();
147
-        EEH_Activation::create_cron_tasks();
148
-        // remove all TXN locks since that is being done via extra meta now
149
-        delete_option('ee_locked_transactions');
150
-        // also, check for CAF default db content
151
-        do_action('AHEE__EEH_Activation__initialize_db_content');
152
-        // also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
153
-        // which users really won't care about on initial activation
154
-        EE_Error::overwrite_success();
155
-    }
156
-
157
-
158
-    /**
159
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
160
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
161
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
162
-     * (null)
163
-     *
164
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
165
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
166
-     * @return array
167
-     * @throws \EE_Error
168
-     */
169
-    public static function get_cron_tasks($which_to_include)
170
-    {
171
-        $cron_tasks = apply_filters(
172
-            'FHEE__EEH_Activation__get_cron_tasks',
173
-            array(
174
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
175
-            //              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
176
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
177
-                // 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
178
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
179
-            )
180
-        );
181
-        if ($which_to_include === 'old') {
182
-            $cron_tasks = array_filter(
183
-                $cron_tasks,
184
-                function ($value) {
185
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
186
-                }
187
-            );
188
-        } elseif ($which_to_include === 'current') {
189
-            $cron_tasks = array_filter($cron_tasks);
190
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
191
-            throw new EE_Error(
192
-                sprintf(
193
-                    __(
194
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
195
-                        'event_espresso'
196
-                    ),
197
-                    $which_to_include
198
-                )
199
-            );
200
-        }
201
-        return $cron_tasks;
202
-    }
203
-
204
-
205
-    /**
206
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
207
-     *
208
-     * @throws \EE_Error
209
-     */
210
-    public static function create_cron_tasks()
211
-    {
212
-
213
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
214
-            if (! wp_next_scheduled($hook_name)) {
215
-                /**
216
-                 * This allows client code to define the initial start timestamp for this schedule.
217
-                 */
218
-                if (is_array($frequency)
219
-                    && count($frequency) === 2
220
-                    && isset($frequency[0], $frequency[1])
221
-                ) {
222
-                    $start_timestamp = $frequency[0];
223
-                    $frequency = $frequency[1];
224
-                } else {
225
-                    $start_timestamp = time();
226
-                }
227
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
228
-            }
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * Remove the currently-existing and now-removed cron tasks.
235
-     *
236
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
237
-     * @throws \EE_Error
238
-     */
239
-    public static function remove_cron_tasks($remove_all = true)
240
-    {
241
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
242
-        $crons                = _get_cron_array();
243
-        $crons                = is_array($crons) ? $crons : array();
244
-        /* reminder of what $crons look like:
18
+	/**
19
+	 * constant used to indicate a cron task is no longer in use
20
+	 */
21
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
22
+
23
+	/**
24
+	 * WP_User->ID
25
+	 *
26
+	 * @var int
27
+	 */
28
+	private static $_default_creator_id;
29
+
30
+	/**
31
+	 * indicates whether or not we've already verified core's default data during this request,
32
+	 * because after migrations are done, any addons activated while in maintenance mode
33
+	 * will want to setup their own default data, and they might hook into core's default data
34
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
+	 * This prevents doing that for EVERY single addon.
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	protected static $_initialized_db_content_already_in_this_request = false;
40
+
41
+	/**
42
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
+	 */
44
+	private static $table_analysis;
45
+
46
+	/**
47
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
48
+	 */
49
+	private static $table_manager;
50
+
51
+
52
+	/**
53
+	 * @return \EventEspresso\core\services\database\TableAnalysis
54
+	 */
55
+	public static function getTableAnalysis()
56
+	{
57
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
+		}
60
+		return self::$table_analysis;
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return \EventEspresso\core\services\database\TableManager
66
+	 */
67
+	public static function getTableManager()
68
+	{
69
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
+		}
72
+		return self::$table_manager;
73
+	}
74
+
75
+
76
+	/**
77
+	 *    _ensure_table_name_has_prefix
78
+	 *
79
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
+	 * @access     public
81
+	 * @static
82
+	 * @param $table_name
83
+	 * @return string
84
+	 */
85
+	public static function ensure_table_name_has_prefix($table_name)
86
+	{
87
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
+	}
89
+
90
+
91
+	/**
92
+	 *    system_initialization
93
+	 *    ensures the EE configuration settings are loaded with at least default options set
94
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
+	 *
96
+	 * @access public
97
+	 * @static
98
+	 * @return void
99
+	 */
100
+	public static function system_initialization()
101
+	{
102
+		EEH_Activation::reset_and_update_config();
103
+		// which is fired BEFORE activation of plugin anyways
104
+		EEH_Activation::verify_default_pages_exist();
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets the database schema and creates folders. This should
110
+	 * be called on plugin activation and reactivation
111
+	 *
112
+	 * @return boolean success, whether the database and folders are setup properly
113
+	 * @throws \EE_Error
114
+	 */
115
+	public static function initialize_db_and_folders()
116
+	{
117
+		return EEH_Activation::create_database_tables();
118
+	}
119
+
120
+
121
+	/**
122
+	 * assuming we have an up-to-date database schema, this will populate it
123
+	 * with default and initial data. This should be called
124
+	 * upon activation of a new plugin, reactivation, and at the end
125
+	 * of running migration scripts
126
+	 *
127
+	 * @throws \EE_Error
128
+	 */
129
+	public static function initialize_db_content()
130
+	{
131
+		// let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
+			return;
134
+		}
135
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
+
137
+		EEH_Activation::initialize_system_questions();
138
+		EEH_Activation::insert_default_status_codes();
139
+		EEH_Activation::generate_default_message_templates();
140
+		EEH_Activation::create_no_ticket_prices_array();
141
+		EEH_Activation::removeEmailConfirmFromAddressGroup();
142
+
143
+		EEH_Activation::validate_messages_system();
144
+		EEH_Activation::insert_default_payment_methods();
145
+		// in case we've
146
+		EEH_Activation::remove_cron_tasks();
147
+		EEH_Activation::create_cron_tasks();
148
+		// remove all TXN locks since that is being done via extra meta now
149
+		delete_option('ee_locked_transactions');
150
+		// also, check for CAF default db content
151
+		do_action('AHEE__EEH_Activation__initialize_db_content');
152
+		// also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
153
+		// which users really won't care about on initial activation
154
+		EE_Error::overwrite_success();
155
+	}
156
+
157
+
158
+	/**
159
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
160
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
161
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
162
+	 * (null)
163
+	 *
164
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
165
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
166
+	 * @return array
167
+	 * @throws \EE_Error
168
+	 */
169
+	public static function get_cron_tasks($which_to_include)
170
+	{
171
+		$cron_tasks = apply_filters(
172
+			'FHEE__EEH_Activation__get_cron_tasks',
173
+			array(
174
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
175
+			//              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
176
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
177
+				// 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
178
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
179
+			)
180
+		);
181
+		if ($which_to_include === 'old') {
182
+			$cron_tasks = array_filter(
183
+				$cron_tasks,
184
+				function ($value) {
185
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
186
+				}
187
+			);
188
+		} elseif ($which_to_include === 'current') {
189
+			$cron_tasks = array_filter($cron_tasks);
190
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
191
+			throw new EE_Error(
192
+				sprintf(
193
+					__(
194
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
195
+						'event_espresso'
196
+					),
197
+					$which_to_include
198
+				)
199
+			);
200
+		}
201
+		return $cron_tasks;
202
+	}
203
+
204
+
205
+	/**
206
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
207
+	 *
208
+	 * @throws \EE_Error
209
+	 */
210
+	public static function create_cron_tasks()
211
+	{
212
+
213
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
214
+			if (! wp_next_scheduled($hook_name)) {
215
+				/**
216
+				 * This allows client code to define the initial start timestamp for this schedule.
217
+				 */
218
+				if (is_array($frequency)
219
+					&& count($frequency) === 2
220
+					&& isset($frequency[0], $frequency[1])
221
+				) {
222
+					$start_timestamp = $frequency[0];
223
+					$frequency = $frequency[1];
224
+				} else {
225
+					$start_timestamp = time();
226
+				}
227
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
228
+			}
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * Remove the currently-existing and now-removed cron tasks.
235
+	 *
236
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
237
+	 * @throws \EE_Error
238
+	 */
239
+	public static function remove_cron_tasks($remove_all = true)
240
+	{
241
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
242
+		$crons                = _get_cron_array();
243
+		$crons                = is_array($crons) ? $crons : array();
244
+		/* reminder of what $crons look like:
245 245
          * Top-level keys are timestamps, and their values are arrays.
246 246
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
247 247
          * and their values are arrays.
@@ -258,925 +258,925 @@  discard block
 block discarded – undo
258 258
          *                  ...
259 259
          *      ...
260 260
          */
261
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
262
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
263
-            if (is_array($hooks_to_fire_at_time)) {
264
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
265
-                    if (isset($ee_cron_tasks_to_remove[ $hook_name ])
266
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
267
-                    ) {
268
-                        unset($crons[ $timestamp ][ $hook_name ]);
269
-                    }
270
-                }
271
-                // also take care of any empty cron timestamps.
272
-                if (empty($hooks_to_fire_at_time)) {
273
-                    unset($crons[ $timestamp ]);
274
-                }
275
-            }
276
-        }
277
-        _set_cron_array($crons);
278
-    }
279
-
280
-
281
-    /**
282
-     *    CPT_initialization
283
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
284
-     *
285
-     * @access public
286
-     * @static
287
-     * @return void
288
-     */
289
-    public static function CPT_initialization()
290
-    {
291
-        // register Custom Post Types
292
-        EE_Registry::instance()->load_core('Register_CPTs');
293
-        flush_rewrite_rules();
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     *    reset_and_update_config
300
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
301
-     * If there is old calendar config data saved, then it will get converted on activation.
302
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
303
-     *
304
-     * @access public
305
-     * @static
306
-     * @return void
307
-     */
308
-    public static function reset_and_update_config()
309
-    {
310
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
311
-        add_filter(
312
-            'FHEE__EE_Config___load_core_config__config_settings',
313
-            array('EEH_Activation', 'migrate_old_config_data'),
314
-            10,
315
-            3
316
-        );
317
-        // EE_Config::reset();
318
-        if (! EE_Config::logging_enabled()) {
319
-            delete_option(EE_Config::LOG_NAME);
320
-        }
321
-    }
322
-
323
-
324
-    /**
325
-     *    load_calendar_config
326
-     *
327
-     * @access    public
328
-     * @return    void
329
-     */
330
-    public static function load_calendar_config()
331
-    {
332
-        // grab array of all plugin folders and loop thru it
333
-        $plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
334
-        if (empty($plugins)) {
335
-            return;
336
-        }
337
-        foreach ($plugins as $plugin_path) {
338
-            // grab plugin folder name from path
339
-            $plugin = basename($plugin_path);
340
-            // drill down to Espresso plugins
341
-            // then to calendar related plugins
342
-            if (strpos($plugin, 'espresso') !== false
343
-                || strpos($plugin, 'Espresso') !== false
344
-                || strpos($plugin, 'ee4') !== false
345
-                || strpos($plugin, 'EE4') !== false
346
-                || strpos($plugin, 'calendar') !== false
347
-            ) {
348
-                // this is what we are looking for
349
-                $calendar_config = $plugin_path . '/EE_Calendar_Config.php';
350
-                // does it exist in this folder ?
351
-                if (is_readable($calendar_config)) {
352
-                    // YEAH! let's load it
353
-                    require_once($calendar_config);
354
-                }
355
-            }
356
-        }
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     *    _migrate_old_config_data
363
-     *
364
-     * @access    public
365
-     * @param array|stdClass $settings
366
-     * @param string         $config
367
-     * @param \EE_Config     $EE_Config
368
-     * @return \stdClass
369
-     */
370
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
-    {
372
-        $convert_from_array = array('addons');
373
-        // in case old settings were saved as an array
374
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
375
-            // convert existing settings to an object
376
-            $config_array = $settings;
377
-            $settings = new stdClass();
378
-            foreach ($config_array as $key => $value) {
379
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
-                } else {
382
-                    $settings->{$key} = $value;
383
-                }
384
-            }
385
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
-        }
387
-        return $settings;
388
-    }
389
-
390
-
391
-    /**
392
-     * deactivate_event_espresso
393
-     *
394
-     * @access public
395
-     * @static
396
-     * @return void
397
-     */
398
-    public static function deactivate_event_espresso()
399
-    {
400
-        // check permissions
401
-        if (current_user_can('activate_plugins')) {
402
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
403
-        }
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * verify_default_pages_exist
410
-     *
411
-     * @access public
412
-     * @static
413
-     * @return void
414
-     * @throws InvalidDataTypeException
415
-     */
416
-    public static function verify_default_pages_exist()
417
-    {
418
-        $critical_page_problem = false;
419
-        $critical_pages = array(
420
-            array(
421
-                'id'   => 'reg_page_id',
422
-                'name' => __('Registration Checkout', 'event_espresso'),
423
-                'post' => null,
424
-                'code' => 'ESPRESSO_CHECKOUT',
425
-            ),
426
-            array(
427
-                'id'   => 'txn_page_id',
428
-                'name' => __('Transactions', 'event_espresso'),
429
-                'post' => null,
430
-                'code' => 'ESPRESSO_TXN_PAGE',
431
-            ),
432
-            array(
433
-                'id'   => 'thank_you_page_id',
434
-                'name' => __('Thank You', 'event_espresso'),
435
-                'post' => null,
436
-                'code' => 'ESPRESSO_THANK_YOU',
437
-            ),
438
-            array(
439
-                'id'   => 'cancel_page_id',
440
-                'name' => __('Registration Cancelled', 'event_espresso'),
441
-                'post' => null,
442
-                'code' => 'ESPRESSO_CANCELLED',
443
-            ),
444
-        );
445
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
446
-        foreach ($critical_pages as $critical_page) {
447
-            // is critical page ID set in config ?
448
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
-                // attempt to find post by ID
450
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
-            }
452
-            // no dice?
453
-            if ($critical_page['post'] === null) {
454
-                // attempt to find post by title
455
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
-                // still nothing?
457
-                if ($critical_page['post'] === null) {
458
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
459
-                    // REALLY? Still nothing ??!?!?
460
-                    if ($critical_page['post'] === null) {
461
-                        $msg = __(
462
-                            'The Event Espresso critical page configuration settings could not be updated.',
463
-                            'event_espresso'
464
-                        );
465
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
466
-                        break;
467
-                    }
468
-                }
469
-            }
470
-            // check that Post ID matches critical page ID in config
471
-            if (isset($critical_page['post']->ID)
472
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
473
-            ) {
474
-                // update Config with post ID
475
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
476
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
477
-                    $msg = __(
478
-                        'The Event Espresso critical page configuration settings could not be updated.',
479
-                        'event_espresso'
480
-                    );
481
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
482
-                }
483
-            }
484
-            $critical_page_problem =
485
-                ! isset($critical_page['post']->post_status)
486
-                || $critical_page['post']->post_status !== 'publish'
487
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
488
-                    ? true
489
-                    : $critical_page_problem;
490
-        }
491
-        if ($critical_page_problem) {
492
-            new PersistentAdminNotice(
493
-                'critical_page_problem',
494
-                sprintf(
495
-                    esc_html__(
496
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
497
-                        'event_espresso'
498
-                    ),
499
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
500
-                    . __('Event Espresso Critical Pages Settings', 'event_espresso')
501
-                    . '</a>'
502
-                )
503
-            );
504
-        }
505
-        if (EE_Error::has_notices()) {
506
-            EE_Error::get_notices(false, true, true);
507
-        }
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * Returns the first post which uses the specified shortcode
514
-     *
515
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
516
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
517
-     *                             "[ESPRESSO_THANK_YOU"
518
-     *                             (we don't search for the closing shortcode bracket because they might have added
519
-     *                             parameter to the shortcode
520
-     * @return WP_Post or NULl
521
-     */
522
-    public static function get_page_by_ee_shortcode($ee_shortcode)
523
-    {
524
-        global $wpdb;
525
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
526
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
527
-        if ($post_id) {
528
-            return get_post($post_id);
529
-        } else {
530
-            return null;
531
-        }
532
-    }
533
-
534
-
535
-    /**
536
-     *    This function generates a post for critical espresso pages
537
-     *
538
-     * @access public
539
-     * @static
540
-     * @param array $critical_page
541
-     * @return array
542
-     */
543
-    public static function create_critical_page($critical_page)
544
-    {
545
-
546
-        $post_args = array(
547
-            'post_title'     => $critical_page['name'],
548
-            'post_status'    => 'publish',
549
-            'post_type'      => 'page',
550
-            'comment_status' => 'closed',
551
-            'post_content'   => '[' . $critical_page['code'] . ']',
552
-        );
553
-
554
-        $post_id = wp_insert_post($post_args);
555
-        if (! $post_id) {
556
-            $msg = sprintf(
557
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
558
-                $critical_page['name']
559
-            );
560
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
-            return $critical_page;
562
-        }
563
-        // get newly created post's details
564
-        if (! $critical_page['post'] = get_post($post_id)) {
565
-            $msg = sprintf(
566
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
567
-                $critical_page['name']
568
-            );
569
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
570
-        }
571
-
572
-        return $critical_page;
573
-    }
574
-
575
-
576
-
577
-
578
-    /**
579
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
580
-     * The role being used to check is filterable.
581
-     *
582
-     * @since  4.6.0
583
-     * @global WPDB $wpdb
584
-     * @return mixed null|int WP_user ID or NULL
585
-     */
586
-    public static function get_default_creator_id()
587
-    {
588
-        global $wpdb;
589
-        if (! empty(self::$_default_creator_id)) {
590
-            return self::$_default_creator_id;
591
-        }/**/
592
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
593
-        // 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.
594
-        $pre_filtered_id = apply_filters(
595
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
596
-            false,
597
-            $role_to_check
598
-        );
599
-        if ($pre_filtered_id !== false) {
600
-            return (int) $pre_filtered_id;
601
-        }
602
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
603
-        $query = $wpdb->prepare(
604
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
605
-            '%' . $role_to_check . '%'
606
-        );
607
-        $user_id = $wpdb->get_var($query);
608
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
609
-        if ($user_id && (int) $user_id) {
610
-            self::$_default_creator_id = (int) $user_id;
611
-            return self::$_default_creator_id;
612
-        } else {
613
-            return null;
614
-        }
615
-    }
616
-
617
-
618
-
619
-    /**
620
-     * used by EE and EE addons during plugin activation to create tables.
621
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
622
-     * but includes extra logic regarding activations.
623
-     *
624
-     * @access public
625
-     * @static
626
-     * @param string  $table_name              without the $wpdb->prefix
627
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
628
-     *                                         table query)
629
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
630
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
631
-     *                                         and new once this function is done (ie, you really do want to CREATE a
632
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
633
-     *                                         you just want to verify the table exists and matches this definition
634
-     *                                         (and if it HAS data in it you want to leave it be)
635
-     * @return void
636
-     * @throws EE_Error if there are database errors
637
-     */
638
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
639
-    {
640
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
641
-            return;
642
-        }
643
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
644
-        if (! function_exists('dbDelta')) {
645
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
646
-        }
647
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
648
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
649
-        // do we need to first delete an existing version of this table ?
650
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
651
-            // ok, delete the table... but ONLY if it's empty
652
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
653
-            // table is NOT empty, are you SURE you want to delete this table ???
654
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
655
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
656
-            } elseif (! $deleted_safely) {
657
-                // so we should be more cautious rather than just dropping tables so easily
658
-                error_log(
659
-                    sprintf(
660
-                        __(
661
-                            '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.',
662
-                            'event_espresso'
663
-                        ),
664
-                        $wp_table_name,
665
-                        '<br/>',
666
-                        'espresso_db_update'
667
-                    )
668
-                );
669
-            }
670
-        }
671
-        $engine = str_replace('ENGINE=', '', $engine);
672
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     *    add_column_if_it_doesn't_exist
679
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
680
-     *
681
-     * @access     public
682
-     * @static
683
-     * @deprecated instead use TableManager::addColumn()
684
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
685
-     * @param string $column_name
686
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
687
-     *                            'VARCHAR(10)'
688
-     * @return bool|int
689
-     */
690
-    public static function add_column_if_it_doesnt_exist(
691
-        $table_name,
692
-        $column_name,
693
-        $column_info = 'INT UNSIGNED NOT NULL'
694
-    ) {
695
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
696
-    }
697
-
698
-
699
-    /**
700
-     * get_fields_on_table
701
-     * Gets all the fields on the database table.
702
-     *
703
-     * @access     public
704
-     * @deprecated instead use TableManager::getTableColumns()
705
-     * @static
706
-     * @param string $table_name , without prefixed $wpdb->prefix
707
-     * @return array of database column names
708
-     */
709
-    public static function get_fields_on_table($table_name = null)
710
-    {
711
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
712
-    }
713
-
714
-
715
-    /**
716
-     * db_table_is_empty
717
-     *
718
-     * @access     public\
719
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
720
-     * @static
721
-     * @param string $table_name
722
-     * @return bool
723
-     */
724
-    public static function db_table_is_empty($table_name)
725
-    {
726
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
727
-    }
728
-
729
-
730
-    /**
731
-     * delete_db_table_if_empty
732
-     *
733
-     * @access public
734
-     * @static
735
-     * @param string $table_name
736
-     * @return bool | int
737
-     */
738
-    public static function delete_db_table_if_empty($table_name)
739
-    {
740
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
741
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
742
-        }
743
-        return false;
744
-    }
745
-
746
-
747
-    /**
748
-     * delete_unused_db_table
749
-     *
750
-     * @access     public
751
-     * @static
752
-     * @deprecated instead use TableManager::dropTable()
753
-     * @param string $table_name
754
-     * @return bool | int
755
-     */
756
-    public static function delete_unused_db_table($table_name)
757
-    {
758
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
759
-    }
760
-
761
-
762
-    /**
763
-     * drop_index
764
-     *
765
-     * @access     public
766
-     * @static
767
-     * @deprecated instead use TableManager::dropIndex()
768
-     * @param string $table_name
769
-     * @param string $index_name
770
-     * @return bool | int
771
-     */
772
-    public static function drop_index($table_name, $index_name)
773
-    {
774
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * create_database_tables
781
-     *
782
-     * @access public
783
-     * @static
784
-     * @throws EE_Error
785
-     * @return boolean success (whether database is setup properly or not)
786
-     */
787
-    public static function create_database_tables()
788
-    {
789
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
790
-        // find the migration script that sets the database to be compatible with the code
791
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
792
-        if ($dms_name) {
793
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
794
-            $current_data_migration_script->set_migrating(false);
795
-            $current_data_migration_script->schema_changes_before_migration();
796
-            $current_data_migration_script->schema_changes_after_migration();
797
-            if ($current_data_migration_script->get_errors()) {
798
-                if (WP_DEBUG) {
799
-                    foreach ($current_data_migration_script->get_errors() as $error) {
800
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
801
-                    }
802
-                } else {
803
-                    EE_Error::add_error(
804
-                        __(
805
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
261
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
262
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
263
+			if (is_array($hooks_to_fire_at_time)) {
264
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
265
+					if (isset($ee_cron_tasks_to_remove[ $hook_name ])
266
+						&& is_array($ee_cron_tasks_to_remove[ $hook_name ])
267
+					) {
268
+						unset($crons[ $timestamp ][ $hook_name ]);
269
+					}
270
+				}
271
+				// also take care of any empty cron timestamps.
272
+				if (empty($hooks_to_fire_at_time)) {
273
+					unset($crons[ $timestamp ]);
274
+				}
275
+			}
276
+		}
277
+		_set_cron_array($crons);
278
+	}
279
+
280
+
281
+	/**
282
+	 *    CPT_initialization
283
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
284
+	 *
285
+	 * @access public
286
+	 * @static
287
+	 * @return void
288
+	 */
289
+	public static function CPT_initialization()
290
+	{
291
+		// register Custom Post Types
292
+		EE_Registry::instance()->load_core('Register_CPTs');
293
+		flush_rewrite_rules();
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 *    reset_and_update_config
300
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
301
+	 * If there is old calendar config data saved, then it will get converted on activation.
302
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
303
+	 *
304
+	 * @access public
305
+	 * @static
306
+	 * @return void
307
+	 */
308
+	public static function reset_and_update_config()
309
+	{
310
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
311
+		add_filter(
312
+			'FHEE__EE_Config___load_core_config__config_settings',
313
+			array('EEH_Activation', 'migrate_old_config_data'),
314
+			10,
315
+			3
316
+		);
317
+		// EE_Config::reset();
318
+		if (! EE_Config::logging_enabled()) {
319
+			delete_option(EE_Config::LOG_NAME);
320
+		}
321
+	}
322
+
323
+
324
+	/**
325
+	 *    load_calendar_config
326
+	 *
327
+	 * @access    public
328
+	 * @return    void
329
+	 */
330
+	public static function load_calendar_config()
331
+	{
332
+		// grab array of all plugin folders and loop thru it
333
+		$plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
334
+		if (empty($plugins)) {
335
+			return;
336
+		}
337
+		foreach ($plugins as $plugin_path) {
338
+			// grab plugin folder name from path
339
+			$plugin = basename($plugin_path);
340
+			// drill down to Espresso plugins
341
+			// then to calendar related plugins
342
+			if (strpos($plugin, 'espresso') !== false
343
+				|| strpos($plugin, 'Espresso') !== false
344
+				|| strpos($plugin, 'ee4') !== false
345
+				|| strpos($plugin, 'EE4') !== false
346
+				|| strpos($plugin, 'calendar') !== false
347
+			) {
348
+				// this is what we are looking for
349
+				$calendar_config = $plugin_path . '/EE_Calendar_Config.php';
350
+				// does it exist in this folder ?
351
+				if (is_readable($calendar_config)) {
352
+					// YEAH! let's load it
353
+					require_once($calendar_config);
354
+				}
355
+			}
356
+		}
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 *    _migrate_old_config_data
363
+	 *
364
+	 * @access    public
365
+	 * @param array|stdClass $settings
366
+	 * @param string         $config
367
+	 * @param \EE_Config     $EE_Config
368
+	 * @return \stdClass
369
+	 */
370
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
+	{
372
+		$convert_from_array = array('addons');
373
+		// in case old settings were saved as an array
374
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
375
+			// convert existing settings to an object
376
+			$config_array = $settings;
377
+			$settings = new stdClass();
378
+			foreach ($config_array as $key => $value) {
379
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
+				} else {
382
+					$settings->{$key} = $value;
383
+				}
384
+			}
385
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
+		}
387
+		return $settings;
388
+	}
389
+
390
+
391
+	/**
392
+	 * deactivate_event_espresso
393
+	 *
394
+	 * @access public
395
+	 * @static
396
+	 * @return void
397
+	 */
398
+	public static function deactivate_event_espresso()
399
+	{
400
+		// check permissions
401
+		if (current_user_can('activate_plugins')) {
402
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
403
+		}
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * verify_default_pages_exist
410
+	 *
411
+	 * @access public
412
+	 * @static
413
+	 * @return void
414
+	 * @throws InvalidDataTypeException
415
+	 */
416
+	public static function verify_default_pages_exist()
417
+	{
418
+		$critical_page_problem = false;
419
+		$critical_pages = array(
420
+			array(
421
+				'id'   => 'reg_page_id',
422
+				'name' => __('Registration Checkout', 'event_espresso'),
423
+				'post' => null,
424
+				'code' => 'ESPRESSO_CHECKOUT',
425
+			),
426
+			array(
427
+				'id'   => 'txn_page_id',
428
+				'name' => __('Transactions', 'event_espresso'),
429
+				'post' => null,
430
+				'code' => 'ESPRESSO_TXN_PAGE',
431
+			),
432
+			array(
433
+				'id'   => 'thank_you_page_id',
434
+				'name' => __('Thank You', 'event_espresso'),
435
+				'post' => null,
436
+				'code' => 'ESPRESSO_THANK_YOU',
437
+			),
438
+			array(
439
+				'id'   => 'cancel_page_id',
440
+				'name' => __('Registration Cancelled', 'event_espresso'),
441
+				'post' => null,
442
+				'code' => 'ESPRESSO_CANCELLED',
443
+			),
444
+		);
445
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
446
+		foreach ($critical_pages as $critical_page) {
447
+			// is critical page ID set in config ?
448
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
+				// attempt to find post by ID
450
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
+			}
452
+			// no dice?
453
+			if ($critical_page['post'] === null) {
454
+				// attempt to find post by title
455
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
+				// still nothing?
457
+				if ($critical_page['post'] === null) {
458
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
459
+					// REALLY? Still nothing ??!?!?
460
+					if ($critical_page['post'] === null) {
461
+						$msg = __(
462
+							'The Event Espresso critical page configuration settings could not be updated.',
463
+							'event_espresso'
464
+						);
465
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
466
+						break;
467
+					}
468
+				}
469
+			}
470
+			// check that Post ID matches critical page ID in config
471
+			if (isset($critical_page['post']->ID)
472
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
473
+			) {
474
+				// update Config with post ID
475
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
476
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
477
+					$msg = __(
478
+						'The Event Espresso critical page configuration settings could not be updated.',
479
+						'event_espresso'
480
+					);
481
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
482
+				}
483
+			}
484
+			$critical_page_problem =
485
+				! isset($critical_page['post']->post_status)
486
+				|| $critical_page['post']->post_status !== 'publish'
487
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
488
+					? true
489
+					: $critical_page_problem;
490
+		}
491
+		if ($critical_page_problem) {
492
+			new PersistentAdminNotice(
493
+				'critical_page_problem',
494
+				sprintf(
495
+					esc_html__(
496
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
497
+						'event_espresso'
498
+					),
499
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
500
+					. __('Event Espresso Critical Pages Settings', 'event_espresso')
501
+					. '</a>'
502
+				)
503
+			);
504
+		}
505
+		if (EE_Error::has_notices()) {
506
+			EE_Error::get_notices(false, true, true);
507
+		}
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * Returns the first post which uses the specified shortcode
514
+	 *
515
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
516
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
517
+	 *                             "[ESPRESSO_THANK_YOU"
518
+	 *                             (we don't search for the closing shortcode bracket because they might have added
519
+	 *                             parameter to the shortcode
520
+	 * @return WP_Post or NULl
521
+	 */
522
+	public static function get_page_by_ee_shortcode($ee_shortcode)
523
+	{
524
+		global $wpdb;
525
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
526
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
527
+		if ($post_id) {
528
+			return get_post($post_id);
529
+		} else {
530
+			return null;
531
+		}
532
+	}
533
+
534
+
535
+	/**
536
+	 *    This function generates a post for critical espresso pages
537
+	 *
538
+	 * @access public
539
+	 * @static
540
+	 * @param array $critical_page
541
+	 * @return array
542
+	 */
543
+	public static function create_critical_page($critical_page)
544
+	{
545
+
546
+		$post_args = array(
547
+			'post_title'     => $critical_page['name'],
548
+			'post_status'    => 'publish',
549
+			'post_type'      => 'page',
550
+			'comment_status' => 'closed',
551
+			'post_content'   => '[' . $critical_page['code'] . ']',
552
+		);
553
+
554
+		$post_id = wp_insert_post($post_args);
555
+		if (! $post_id) {
556
+			$msg = sprintf(
557
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
558
+				$critical_page['name']
559
+			);
560
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
+			return $critical_page;
562
+		}
563
+		// get newly created post's details
564
+		if (! $critical_page['post'] = get_post($post_id)) {
565
+			$msg = sprintf(
566
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
567
+				$critical_page['name']
568
+			);
569
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
570
+		}
571
+
572
+		return $critical_page;
573
+	}
574
+
575
+
576
+
577
+
578
+	/**
579
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
580
+	 * The role being used to check is filterable.
581
+	 *
582
+	 * @since  4.6.0
583
+	 * @global WPDB $wpdb
584
+	 * @return mixed null|int WP_user ID or NULL
585
+	 */
586
+	public static function get_default_creator_id()
587
+	{
588
+		global $wpdb;
589
+		if (! empty(self::$_default_creator_id)) {
590
+			return self::$_default_creator_id;
591
+		}/**/
592
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
593
+		// 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.
594
+		$pre_filtered_id = apply_filters(
595
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
596
+			false,
597
+			$role_to_check
598
+		);
599
+		if ($pre_filtered_id !== false) {
600
+			return (int) $pre_filtered_id;
601
+		}
602
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
603
+		$query = $wpdb->prepare(
604
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
605
+			'%' . $role_to_check . '%'
606
+		);
607
+		$user_id = $wpdb->get_var($query);
608
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
609
+		if ($user_id && (int) $user_id) {
610
+			self::$_default_creator_id = (int) $user_id;
611
+			return self::$_default_creator_id;
612
+		} else {
613
+			return null;
614
+		}
615
+	}
616
+
617
+
618
+
619
+	/**
620
+	 * used by EE and EE addons during plugin activation to create tables.
621
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
622
+	 * but includes extra logic regarding activations.
623
+	 *
624
+	 * @access public
625
+	 * @static
626
+	 * @param string  $table_name              without the $wpdb->prefix
627
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
628
+	 *                                         table query)
629
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
630
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
631
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
632
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
633
+	 *                                         you just want to verify the table exists and matches this definition
634
+	 *                                         (and if it HAS data in it you want to leave it be)
635
+	 * @return void
636
+	 * @throws EE_Error if there are database errors
637
+	 */
638
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
639
+	{
640
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
641
+			return;
642
+		}
643
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
644
+		if (! function_exists('dbDelta')) {
645
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
646
+		}
647
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
648
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
649
+		// do we need to first delete an existing version of this table ?
650
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
651
+			// ok, delete the table... but ONLY if it's empty
652
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
653
+			// table is NOT empty, are you SURE you want to delete this table ???
654
+			if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
655
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
656
+			} elseif (! $deleted_safely) {
657
+				// so we should be more cautious rather than just dropping tables so easily
658
+				error_log(
659
+					sprintf(
660
+						__(
661
+							'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.',
662
+							'event_espresso'
663
+						),
664
+						$wp_table_name,
665
+						'<br/>',
666
+						'espresso_db_update'
667
+					)
668
+				);
669
+			}
670
+		}
671
+		$engine = str_replace('ENGINE=', '', $engine);
672
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 *    add_column_if_it_doesn't_exist
679
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
680
+	 *
681
+	 * @access     public
682
+	 * @static
683
+	 * @deprecated instead use TableManager::addColumn()
684
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
685
+	 * @param string $column_name
686
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
687
+	 *                            'VARCHAR(10)'
688
+	 * @return bool|int
689
+	 */
690
+	public static function add_column_if_it_doesnt_exist(
691
+		$table_name,
692
+		$column_name,
693
+		$column_info = 'INT UNSIGNED NOT NULL'
694
+	) {
695
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
696
+	}
697
+
698
+
699
+	/**
700
+	 * get_fields_on_table
701
+	 * Gets all the fields on the database table.
702
+	 *
703
+	 * @access     public
704
+	 * @deprecated instead use TableManager::getTableColumns()
705
+	 * @static
706
+	 * @param string $table_name , without prefixed $wpdb->prefix
707
+	 * @return array of database column names
708
+	 */
709
+	public static function get_fields_on_table($table_name = null)
710
+	{
711
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
712
+	}
713
+
714
+
715
+	/**
716
+	 * db_table_is_empty
717
+	 *
718
+	 * @access     public\
719
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
720
+	 * @static
721
+	 * @param string $table_name
722
+	 * @return bool
723
+	 */
724
+	public static function db_table_is_empty($table_name)
725
+	{
726
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
727
+	}
728
+
729
+
730
+	/**
731
+	 * delete_db_table_if_empty
732
+	 *
733
+	 * @access public
734
+	 * @static
735
+	 * @param string $table_name
736
+	 * @return bool | int
737
+	 */
738
+	public static function delete_db_table_if_empty($table_name)
739
+	{
740
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
741
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
742
+		}
743
+		return false;
744
+	}
745
+
746
+
747
+	/**
748
+	 * delete_unused_db_table
749
+	 *
750
+	 * @access     public
751
+	 * @static
752
+	 * @deprecated instead use TableManager::dropTable()
753
+	 * @param string $table_name
754
+	 * @return bool | int
755
+	 */
756
+	public static function delete_unused_db_table($table_name)
757
+	{
758
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
759
+	}
760
+
761
+
762
+	/**
763
+	 * drop_index
764
+	 *
765
+	 * @access     public
766
+	 * @static
767
+	 * @deprecated instead use TableManager::dropIndex()
768
+	 * @param string $table_name
769
+	 * @param string $index_name
770
+	 * @return bool | int
771
+	 */
772
+	public static function drop_index($table_name, $index_name)
773
+	{
774
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * create_database_tables
781
+	 *
782
+	 * @access public
783
+	 * @static
784
+	 * @throws EE_Error
785
+	 * @return boolean success (whether database is setup properly or not)
786
+	 */
787
+	public static function create_database_tables()
788
+	{
789
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
790
+		// find the migration script that sets the database to be compatible with the code
791
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
792
+		if ($dms_name) {
793
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
794
+			$current_data_migration_script->set_migrating(false);
795
+			$current_data_migration_script->schema_changes_before_migration();
796
+			$current_data_migration_script->schema_changes_after_migration();
797
+			if ($current_data_migration_script->get_errors()) {
798
+				if (WP_DEBUG) {
799
+					foreach ($current_data_migration_script->get_errors() as $error) {
800
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
801
+					}
802
+				} else {
803
+					EE_Error::add_error(
804
+						__(
805
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
806 806
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
807
-                            'event_espresso'
808
-                        )
809
-                    );
810
-                }
811
-                return false;
812
-            }
813
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
814
-        } else {
815
-            EE_Error::add_error(
816
-                __(
817
-                    'Could not determine most up-to-date data migration script from which to pull database schema
807
+							'event_espresso'
808
+						)
809
+					);
810
+				}
811
+				return false;
812
+			}
813
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
814
+		} else {
815
+			EE_Error::add_error(
816
+				__(
817
+					'Could not determine most up-to-date data migration script from which to pull database schema
818 818
                      structure. So database is probably not setup properly',
819
-                    'event_espresso'
820
-                ),
821
-                __FILE__,
822
-                __FUNCTION__,
823
-                __LINE__
824
-            );
825
-            return false;
826
-        }
827
-        return true;
828
-    }
829
-
830
-
831
-
832
-    /**
833
-     * initialize_system_questions
834
-     *
835
-     * @access public
836
-     * @static
837
-     * @return void
838
-     */
839
-    public static function initialize_system_questions()
840
-    {
841
-        // QUESTION GROUPS
842
-        global $wpdb;
843
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
844
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
845
-        // what we have
846
-        $question_groups = $wpdb->get_col($SQL);
847
-        // check the response
848
-        $question_groups = is_array($question_groups) ? $question_groups : array();
849
-        // what we should have
850
-        $QSG_systems = array(1, 2);
851
-        // loop thru what we should have and compare to what we have
852
-        foreach ($QSG_systems as $QSG_system) {
853
-            // reset values array
854
-            $QSG_values = array();
855
-            // 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)
856
-            if (! in_array("$QSG_system", $question_groups)) {
857
-                // add it
858
-                switch ($QSG_system) {
859
-                    case 1:
860
-                        $QSG_values = array(
861
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
862
-                            'QSG_identifier'      => 'personal-information-' . time(),
863
-                            'QSG_desc'            => '',
864
-                            'QSG_order'           => 1,
865
-                            'QSG_show_group_name' => 1,
866
-                            'QSG_show_group_desc' => 1,
867
-                            'QSG_system'          => EEM_Question_Group::system_personal,
868
-                            'QSG_deleted'         => 0,
869
-                        );
870
-                        break;
871
-                    case 2:
872
-                        $QSG_values = array(
873
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
874
-                            'QSG_identifier'      => 'address-information-' . time(),
875
-                            'QSG_desc'            => '',
876
-                            'QSG_order'           => 2,
877
-                            'QSG_show_group_name' => 1,
878
-                            'QSG_show_group_desc' => 1,
879
-                            'QSG_system'          => EEM_Question_Group::system_address,
880
-                            'QSG_deleted'         => 0,
881
-                        );
882
-                        break;
883
-                }
884
-                // make sure we have some values before inserting them
885
-                if (! empty($QSG_values)) {
886
-                    // insert system question
887
-                    $wpdb->insert(
888
-                        $table_name,
889
-                        $QSG_values,
890
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
891
-                    );
892
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
893
-                }
894
-            }
895
-        }
896
-        // QUESTIONS
897
-        global $wpdb;
898
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
899
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
900
-        // what we have
901
-        $questions = $wpdb->get_col($SQL);
902
-        // all system questions
903
-        $personal_system_group_questions = ['fname', 'lname', 'email'];
904
-        $address_system_group_questions = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
905
-        $system_questions_not_in_group = ['email_confirm'];
906
-        // merge all of the system questions we should have
907
-        $QST_systems = array_merge(
908
-            $personal_system_group_questions,
909
-            $address_system_group_questions,
910
-            $system_questions_not_in_group
911
-        );
912
-        $order_for_group_1 = 1;
913
-        $order_for_group_2 = 1;
914
-        // loop thru what we should have and compare to what we have
915
-        foreach ($QST_systems as $QST_system) {
916
-            // reset values array
917
-            $QST_values = array();
918
-            // if we don't have what we should have
919
-            if (! in_array($QST_system, $questions)) {
920
-                // add it
921
-                switch ($QST_system) {
922
-                    case 'fname':
923
-                        $QST_values = array(
924
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
925
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
926
-                            'QST_system'        => 'fname',
927
-                            'QST_type'          => 'TEXT',
928
-                            'QST_required'      => 1,
929
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
930
-                            'QST_order'         => 1,
931
-                            'QST_admin_only'    => 0,
932
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
933
-                            'QST_wp_user'       => self::get_default_creator_id(),
934
-                            'QST_deleted'       => 0,
935
-                        );
936
-                        break;
937
-                    case 'lname':
938
-                        $QST_values = array(
939
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
940
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
941
-                            'QST_system'        => 'lname',
942
-                            'QST_type'          => 'TEXT',
943
-                            'QST_required'      => 1,
944
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
945
-                            'QST_order'         => 2,
946
-                            'QST_admin_only'    => 0,
947
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
948
-                            'QST_wp_user'       => self::get_default_creator_id(),
949
-                            'QST_deleted'       => 0,
950
-                        );
951
-                        break;
952
-                    case 'email':
953
-                        $QST_values = array(
954
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
955
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
956
-                            'QST_system'        => 'email',
957
-                            'QST_type'          => 'EMAIL',
958
-                            'QST_required'      => 1,
959
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
960
-                            'QST_order'         => 3,
961
-                            'QST_admin_only'    => 0,
962
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
963
-                            'QST_wp_user'       => self::get_default_creator_id(),
964
-                            'QST_deleted'       => 0,
965
-                        );
966
-                        break;
967
-                    case 'email_confirm':
968
-                        $QST_values = array(
969
-                            'QST_display_text'  => __('Confirm Email Address', 'event_espresso'),
970
-                            'QST_admin_label'   => __('Confirm Email Address - System Question', 'event_espresso'),
971
-                            'QST_system'        => 'email_confirm',
972
-                            'QST_type'          => 'EMAIL_CONFIRM',
973
-                            'QST_required'      => 1,
974
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
975
-                            'QST_order'         => 4,
976
-                            'QST_admin_only'    => 0,
977
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
978
-                            'QST_wp_user'       => self::get_default_creator_id(),
979
-                            'QST_deleted'       => 0,
980
-                        );
981
-                        break;
982
-                    case 'address':
983
-                        $QST_values = array(
984
-                            'QST_display_text'  => __('Address', 'event_espresso'),
985
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
986
-                            'QST_system'        => 'address',
987
-                            'QST_type'          => 'TEXT',
988
-                            'QST_required'      => 0,
989
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
990
-                            'QST_order'         => 5,
991
-                            'QST_admin_only'    => 0,
992
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
993
-                            'QST_wp_user'       => self::get_default_creator_id(),
994
-                            'QST_deleted'       => 0,
995
-                        );
996
-                        break;
997
-                    case 'address2':
998
-                        $QST_values = array(
999
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1000
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1001
-                            'QST_system'        => 'address2',
1002
-                            'QST_type'          => 'TEXT',
1003
-                            'QST_required'      => 0,
1004
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1005
-                            'QST_order'         => 6,
1006
-                            'QST_admin_only'    => 0,
1007
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1008
-                            'QST_wp_user'       => self::get_default_creator_id(),
1009
-                            'QST_deleted'       => 0,
1010
-                        );
1011
-                        break;
1012
-                    case 'city':
1013
-                        $QST_values = array(
1014
-                            'QST_display_text'  => __('City', 'event_espresso'),
1015
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1016
-                            'QST_system'        => 'city',
1017
-                            'QST_type'          => 'TEXT',
1018
-                            'QST_required'      => 0,
1019
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1020
-                            'QST_order'         => 7,
1021
-                            'QST_admin_only'    => 0,
1022
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1023
-                            'QST_wp_user'       => self::get_default_creator_id(),
1024
-                            'QST_deleted'       => 0,
1025
-                        );
1026
-                        break;
1027
-                    case 'country':
1028
-                        $QST_values = array(
1029
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1030
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1031
-                            'QST_system'        => 'country',
1032
-                            'QST_type'          => 'COUNTRY',
1033
-                            'QST_required'      => 0,
1034
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1035
-                            'QST_order'         => 8,
1036
-                            'QST_admin_only'    => 0,
1037
-                            'QST_wp_user'       => self::get_default_creator_id(),
1038
-                            'QST_deleted'       => 0,
1039
-                        );
1040
-                        break;
1041
-                    case 'state':
1042
-                        $QST_values = array(
1043
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1044
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1045
-                            'QST_system'        => 'state',
1046
-                            'QST_type'          => 'STATE',
1047
-                            'QST_required'      => 0,
1048
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1049
-                            'QST_order'         => 9,
1050
-                            'QST_admin_only'    => 0,
1051
-                            'QST_wp_user'       => self::get_default_creator_id(),
1052
-                            'QST_deleted'       => 0,
1053
-                        );
1054
-                        break;
1055
-                    case 'zip':
1056
-                        $QST_values = array(
1057
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1058
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1059
-                            'QST_system'        => 'zip',
1060
-                            'QST_type'          => 'TEXT',
1061
-                            'QST_required'      => 0,
1062
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1063
-                            'QST_order'         => 10,
1064
-                            'QST_admin_only'    => 0,
1065
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
-                            'QST_wp_user'       => self::get_default_creator_id(),
1067
-                            'QST_deleted'       => 0,
1068
-                        );
1069
-                        break;
1070
-                    case 'phone':
1071
-                        $QST_values = array(
1072
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1073
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1074
-                            'QST_system'        => 'phone',
1075
-                            'QST_type'          => 'TEXT',
1076
-                            'QST_required'      => 0,
1077
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1078
-                            'QST_order'         => 11,
1079
-                            'QST_admin_only'    => 0,
1080
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1081
-                            'QST_wp_user'       => self::get_default_creator_id(),
1082
-                            'QST_deleted'       => 0,
1083
-                        );
1084
-                        break;
1085
-                }
1086
-                if (! empty($QST_values)) {
1087
-                    // insert system question
1088
-                    $wpdb->insert(
1089
-                        $table_name,
1090
-                        $QST_values,
1091
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1092
-                    );
1093
-                    $QST_ID = $wpdb->insert_id;
1094
-
1095
-                    // QUESTION GROUP QUESTIONS
1096
-                    if (in_array($QST_system, $personal_system_group_questions)) {
1097
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1098
-                    } elseif (in_array($QST_system, $address_system_group_questions)) {
1099
-                        $system_question_we_want = EEM_Question_Group::system_address;
1100
-                    } else {
1101
-                        // QST_system should not be assigned to any group
1102
-                        continue;
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
819
+					'event_espresso'
820
+				),
821
+				__FILE__,
822
+				__FUNCTION__,
823
+				__LINE__
824
+			);
825
+			return false;
826
+		}
827
+		return true;
828
+	}
829
+
830
+
831
+
832
+	/**
833
+	 * initialize_system_questions
834
+	 *
835
+	 * @access public
836
+	 * @static
837
+	 * @return void
838
+	 */
839
+	public static function initialize_system_questions()
840
+	{
841
+		// QUESTION GROUPS
842
+		global $wpdb;
843
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
844
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
845
+		// what we have
846
+		$question_groups = $wpdb->get_col($SQL);
847
+		// check the response
848
+		$question_groups = is_array($question_groups) ? $question_groups : array();
849
+		// what we should have
850
+		$QSG_systems = array(1, 2);
851
+		// loop thru what we should have and compare to what we have
852
+		foreach ($QSG_systems as $QSG_system) {
853
+			// reset values array
854
+			$QSG_values = array();
855
+			// 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)
856
+			if (! in_array("$QSG_system", $question_groups)) {
857
+				// add it
858
+				switch ($QSG_system) {
859
+					case 1:
860
+						$QSG_values = array(
861
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
862
+							'QSG_identifier'      => 'personal-information-' . time(),
863
+							'QSG_desc'            => '',
864
+							'QSG_order'           => 1,
865
+							'QSG_show_group_name' => 1,
866
+							'QSG_show_group_desc' => 1,
867
+							'QSG_system'          => EEM_Question_Group::system_personal,
868
+							'QSG_deleted'         => 0,
869
+						);
870
+						break;
871
+					case 2:
872
+						$QSG_values = array(
873
+							'QSG_name'            => __('Address Information', 'event_espresso'),
874
+							'QSG_identifier'      => 'address-information-' . time(),
875
+							'QSG_desc'            => '',
876
+							'QSG_order'           => 2,
877
+							'QSG_show_group_name' => 1,
878
+							'QSG_show_group_desc' => 1,
879
+							'QSG_system'          => EEM_Question_Group::system_address,
880
+							'QSG_deleted'         => 0,
881
+						);
882
+						break;
883
+				}
884
+				// make sure we have some values before inserting them
885
+				if (! empty($QSG_values)) {
886
+					// insert system question
887
+					$wpdb->insert(
888
+						$table_name,
889
+						$QSG_values,
890
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
891
+					);
892
+					$QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
893
+				}
894
+			}
895
+		}
896
+		// QUESTIONS
897
+		global $wpdb;
898
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
899
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
900
+		// what we have
901
+		$questions = $wpdb->get_col($SQL);
902
+		// all system questions
903
+		$personal_system_group_questions = ['fname', 'lname', 'email'];
904
+		$address_system_group_questions = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
905
+		$system_questions_not_in_group = ['email_confirm'];
906
+		// merge all of the system questions we should have
907
+		$QST_systems = array_merge(
908
+			$personal_system_group_questions,
909
+			$address_system_group_questions,
910
+			$system_questions_not_in_group
911
+		);
912
+		$order_for_group_1 = 1;
913
+		$order_for_group_2 = 1;
914
+		// loop thru what we should have and compare to what we have
915
+		foreach ($QST_systems as $QST_system) {
916
+			// reset values array
917
+			$QST_values = array();
918
+			// if we don't have what we should have
919
+			if (! in_array($QST_system, $questions)) {
920
+				// add it
921
+				switch ($QST_system) {
922
+					case 'fname':
923
+						$QST_values = array(
924
+							'QST_display_text'  => __('First Name', 'event_espresso'),
925
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
926
+							'QST_system'        => 'fname',
927
+							'QST_type'          => 'TEXT',
928
+							'QST_required'      => 1,
929
+							'QST_required_text' => __('This field is required', 'event_espresso'),
930
+							'QST_order'         => 1,
931
+							'QST_admin_only'    => 0,
932
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
933
+							'QST_wp_user'       => self::get_default_creator_id(),
934
+							'QST_deleted'       => 0,
935
+						);
936
+						break;
937
+					case 'lname':
938
+						$QST_values = array(
939
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
940
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
941
+							'QST_system'        => 'lname',
942
+							'QST_type'          => 'TEXT',
943
+							'QST_required'      => 1,
944
+							'QST_required_text' => __('This field is required', 'event_espresso'),
945
+							'QST_order'         => 2,
946
+							'QST_admin_only'    => 0,
947
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
948
+							'QST_wp_user'       => self::get_default_creator_id(),
949
+							'QST_deleted'       => 0,
950
+						);
951
+						break;
952
+					case 'email':
953
+						$QST_values = array(
954
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
955
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
956
+							'QST_system'        => 'email',
957
+							'QST_type'          => 'EMAIL',
958
+							'QST_required'      => 1,
959
+							'QST_required_text' => __('This field is required', 'event_espresso'),
960
+							'QST_order'         => 3,
961
+							'QST_admin_only'    => 0,
962
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
963
+							'QST_wp_user'       => self::get_default_creator_id(),
964
+							'QST_deleted'       => 0,
965
+						);
966
+						break;
967
+					case 'email_confirm':
968
+						$QST_values = array(
969
+							'QST_display_text'  => __('Confirm Email Address', 'event_espresso'),
970
+							'QST_admin_label'   => __('Confirm Email Address - System Question', 'event_espresso'),
971
+							'QST_system'        => 'email_confirm',
972
+							'QST_type'          => 'EMAIL_CONFIRM',
973
+							'QST_required'      => 1,
974
+							'QST_required_text' => __('This field is required', 'event_espresso'),
975
+							'QST_order'         => 4,
976
+							'QST_admin_only'    => 0,
977
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
978
+							'QST_wp_user'       => self::get_default_creator_id(),
979
+							'QST_deleted'       => 0,
980
+						);
981
+						break;
982
+					case 'address':
983
+						$QST_values = array(
984
+							'QST_display_text'  => __('Address', 'event_espresso'),
985
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
986
+							'QST_system'        => 'address',
987
+							'QST_type'          => 'TEXT',
988
+							'QST_required'      => 0,
989
+							'QST_required_text' => __('This field is required', 'event_espresso'),
990
+							'QST_order'         => 5,
991
+							'QST_admin_only'    => 0,
992
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
993
+							'QST_wp_user'       => self::get_default_creator_id(),
994
+							'QST_deleted'       => 0,
995
+						);
996
+						break;
997
+					case 'address2':
998
+						$QST_values = array(
999
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1000
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1001
+							'QST_system'        => 'address2',
1002
+							'QST_type'          => 'TEXT',
1003
+							'QST_required'      => 0,
1004
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1005
+							'QST_order'         => 6,
1006
+							'QST_admin_only'    => 0,
1007
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1008
+							'QST_wp_user'       => self::get_default_creator_id(),
1009
+							'QST_deleted'       => 0,
1010
+						);
1011
+						break;
1012
+					case 'city':
1013
+						$QST_values = array(
1014
+							'QST_display_text'  => __('City', 'event_espresso'),
1015
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1016
+							'QST_system'        => 'city',
1017
+							'QST_type'          => 'TEXT',
1018
+							'QST_required'      => 0,
1019
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1020
+							'QST_order'         => 7,
1021
+							'QST_admin_only'    => 0,
1022
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1023
+							'QST_wp_user'       => self::get_default_creator_id(),
1024
+							'QST_deleted'       => 0,
1025
+						);
1026
+						break;
1027
+					case 'country':
1028
+						$QST_values = array(
1029
+							'QST_display_text'  => __('Country', 'event_espresso'),
1030
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1031
+							'QST_system'        => 'country',
1032
+							'QST_type'          => 'COUNTRY',
1033
+							'QST_required'      => 0,
1034
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1035
+							'QST_order'         => 8,
1036
+							'QST_admin_only'    => 0,
1037
+							'QST_wp_user'       => self::get_default_creator_id(),
1038
+							'QST_deleted'       => 0,
1039
+						);
1040
+						break;
1041
+					case 'state':
1042
+						$QST_values = array(
1043
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1044
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1045
+							'QST_system'        => 'state',
1046
+							'QST_type'          => 'STATE',
1047
+							'QST_required'      => 0,
1048
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1049
+							'QST_order'         => 9,
1050
+							'QST_admin_only'    => 0,
1051
+							'QST_wp_user'       => self::get_default_creator_id(),
1052
+							'QST_deleted'       => 0,
1053
+						);
1054
+						break;
1055
+					case 'zip':
1056
+						$QST_values = array(
1057
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1058
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1059
+							'QST_system'        => 'zip',
1060
+							'QST_type'          => 'TEXT',
1061
+							'QST_required'      => 0,
1062
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1063
+							'QST_order'         => 10,
1064
+							'QST_admin_only'    => 0,
1065
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
+							'QST_wp_user'       => self::get_default_creator_id(),
1067
+							'QST_deleted'       => 0,
1068
+						);
1069
+						break;
1070
+					case 'phone':
1071
+						$QST_values = array(
1072
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1073
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1074
+							'QST_system'        => 'phone',
1075
+							'QST_type'          => 'TEXT',
1076
+							'QST_required'      => 0,
1077
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1078
+							'QST_order'         => 11,
1079
+							'QST_admin_only'    => 0,
1080
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1081
+							'QST_wp_user'       => self::get_default_creator_id(),
1082
+							'QST_deleted'       => 0,
1083
+						);
1084
+						break;
1085
+				}
1086
+				if (! empty($QST_values)) {
1087
+					// insert system question
1088
+					$wpdb->insert(
1089
+						$table_name,
1090
+						$QST_values,
1091
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1092
+					);
1093
+					$QST_ID = $wpdb->insert_id;
1094
+
1095
+					// QUESTION GROUP QUESTIONS
1096
+					if (in_array($QST_system, $personal_system_group_questions)) {
1097
+						$system_question_we_want = EEM_Question_Group::system_personal;
1098
+					} elseif (in_array($QST_system, $address_system_group_questions)) {
1099
+						$system_question_we_want = EEM_Question_Group::system_address;
1100
+					} else {
1101
+						// QST_system should not be assigned to any group
1102
+						continue;
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
-                                ),
1124
-                                'error'
1125
-                            );
1126
-                            continue;
1127
-                        }
1128
-                    }
1129
-                    // add system questions to groups
1130
-                    $wpdb->insert(
1131
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1132
-                        array(
1133
-                            'QSG_ID'    => $QSG_ID,
1134
-                            'QST_ID'    => $QST_ID,
1135
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1136
-                        ),
1137
-                        array('%d', '%d', '%d')
1138
-                    );
1139
-                }
1140
-            }
1141
-        }
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * Makes sure the default payment method (Invoice) is active.
1147
-     * This used to be done automatically as part of constructing the old gateways config
1148
-     *
1149
-     * @throws \EE_Error
1150
-     */
1151
-    public static function insert_default_payment_methods()
1152
-    {
1153
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1154
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1155
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1156
-        } else {
1157
-            EEM_Payment_Method::instance()->verify_button_urls();
1158
-        }
1159
-    }
1160
-
1161
-    /**
1162
-     * insert_default_status_codes
1163
-     *
1164
-     * @access public
1165
-     * @static
1166
-     * @return void
1167
-     */
1168
-    public static function insert_default_status_codes()
1169
-    {
1170
-
1171
-        global $wpdb;
1172
-
1173
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1174
-            $table_name = EEM_Status::instance()->table();
1175
-
1176
-            $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' );";
1177
-            $wpdb->query($SQL);
1178
-
1179
-            $SQL = "INSERT INTO $table_name
1120
+										'event_espresso'
1121
+									),
1122
+									$QST_ID
1123
+								),
1124
+								'error'
1125
+							);
1126
+							continue;
1127
+						}
1128
+					}
1129
+					// add system questions to groups
1130
+					$wpdb->insert(
1131
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1132
+						array(
1133
+							'QSG_ID'    => $QSG_ID,
1134
+							'QST_ID'    => $QST_ID,
1135
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1136
+						),
1137
+						array('%d', '%d', '%d')
1138
+					);
1139
+				}
1140
+			}
1141
+		}
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * Makes sure the default payment method (Invoice) is active.
1147
+	 * This used to be done automatically as part of constructing the old gateways config
1148
+	 *
1149
+	 * @throws \EE_Error
1150
+	 */
1151
+	public static function insert_default_payment_methods()
1152
+	{
1153
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1154
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1155
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1156
+		} else {
1157
+			EEM_Payment_Method::instance()->verify_button_urls();
1158
+		}
1159
+	}
1160
+
1161
+	/**
1162
+	 * insert_default_status_codes
1163
+	 *
1164
+	 * @access public
1165
+	 * @static
1166
+	 * @return void
1167
+	 */
1168
+	public static function insert_default_status_codes()
1169
+	{
1170
+
1171
+		global $wpdb;
1172
+
1173
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1174
+			$table_name = EEM_Status::instance()->table();
1175
+
1176
+			$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' );";
1177
+			$wpdb->query($SQL);
1178
+
1179
+			$SQL = "INSERT INTO $table_name
1180 1180
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1181 1181
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1182 1182
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1216,473 +1216,473 @@  discard block
 block discarded – undo
1216 1216
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1217 1217
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1218 1218
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1219
-            $wpdb->query($SQL);
1220
-        }
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * generate_default_message_templates
1226
-     *
1227
-     * @static
1228
-     * @throws EE_Error
1229
-     * @return bool     true means new templates were created.
1230
-     *                  false means no templates were created.
1231
-     *                  This is NOT an error flag. To check for errors you will want
1232
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1233
-     */
1234
-    public static function generate_default_message_templates()
1235
-    {
1236
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1237
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1238
-        /*
1219
+			$wpdb->query($SQL);
1220
+		}
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * generate_default_message_templates
1226
+	 *
1227
+	 * @static
1228
+	 * @throws EE_Error
1229
+	 * @return bool     true means new templates were created.
1230
+	 *                  false means no templates were created.
1231
+	 *                  This is NOT an error flag. To check for errors you will want
1232
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1233
+	 */
1234
+	public static function generate_default_message_templates()
1235
+	{
1236
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1237
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1238
+		/*
1239 1239
          * This first method is taking care of ensuring any default messengers
1240 1240
          * that should be made active and have templates generated are done.
1241 1241
          */
1242
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1243
-            $message_resource_manager
1244
-        );
1245
-        /**
1246
-         * This method is verifying there are no NEW default message types
1247
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1248
-         */
1249
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
-            $message_resource_manager
1251
-        );
1252
-        // after all is done, let's persist these changes to the db.
1253
-        $message_resource_manager->update_has_activated_messengers_option();
1254
-        $message_resource_manager->update_active_messengers_option();
1255
-        // will return true if either of these are true.  Otherwise will return false.
1256
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1263
-     * @return array|bool
1264
-     * @throws \EE_Error
1265
-     */
1266
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1267
-        EE_Message_Resource_Manager $message_resource_manager
1268
-    ) {
1269
-        /** @type EE_messenger[] $active_messengers */
1270
-        $active_messengers = $message_resource_manager->active_messengers();
1271
-        $installed_message_types = $message_resource_manager->installed_message_types();
1272
-        $templates_created = false;
1273
-        foreach ($active_messengers as $active_messenger) {
1274
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1275
-            $default_message_type_names_to_activate = array();
1276
-            // looping through each default message type reported by the messenger
1277
-            // and setup the actual message types to activate.
1278
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1279
-                // if already active or has already been activated before we skip
1280
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1281
-                // we also skip if the message type is not installed.
1282
-                if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1283
-                    $default_message_type_name_for_messenger,
1284
-                    $active_messenger->name
1285
-                )
1286
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1287
-                        $active_messenger->name,
1288
-                        $default_message_type_name_for_messenger
1289
-                    )
1290
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1291
-                ) {
1292
-                    continue;
1293
-                }
1294
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1295
-            }
1296
-            // let's activate!
1297
-            $message_resource_manager->ensure_message_types_are_active(
1298
-                $default_message_type_names_to_activate,
1299
-                $active_messenger->name,
1300
-                false
1301
-            );
1302
-            // activate the templates for these message types
1303
-            if (! empty($default_message_type_names_to_activate)) {
1304
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1305
-                    $active_messenger->name,
1306
-                    $default_message_type_names_for_messenger,
1307
-                    '',
1308
-                    true
1309
-                );
1310
-            }
1311
-        }
1312
-        return $templates_created;
1313
-    }
1314
-
1315
-
1316
-
1317
-    /**
1318
-     * This will activate and generate default messengers and default message types for those messengers.
1319
-     *
1320
-     * @param EE_message_Resource_Manager $message_resource_manager
1321
-     * @return array|bool  True means there were default messengers and message type templates generated.
1322
-     *                     False means that there were no templates generated
1323
-     *                     (which could simply mean there are no default message types for a messenger).
1324
-     * @throws EE_Error
1325
-     */
1326
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1327
-        EE_Message_Resource_Manager $message_resource_manager
1328
-    ) {
1329
-        /** @type EE_messenger[] $messengers_to_generate */
1330
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1331
-        $installed_message_types = $message_resource_manager->installed_message_types();
1332
-        $templates_generated = false;
1333
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1334
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1335
-            // verify the default message types match an installed message type.
1336
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1337
-                if (! isset($installed_message_types[ $name ])
1338
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1339
-                        $name,
1340
-                        $messenger_to_generate->name
1341
-                    )
1342
-                ) {
1343
-                    unset($default_message_type_names_for_messenger[ $key ]);
1344
-                }
1345
-            }
1346
-            // in previous iterations, the active_messengers option in the db
1347
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1348
-            // This comment is left here just in case we discover that we _do_ need to update before
1349
-            // passing off to create templates (after the refactor is done).
1350
-            // @todo remove this comment when determined not necessary.
1351
-            $message_resource_manager->activate_messenger(
1352
-                $messenger_to_generate->name,
1353
-                $default_message_type_names_for_messenger,
1354
-                false
1355
-            );
1356
-            // create any templates needing created (or will reactivate templates already generated as necessary).
1357
-            if (! empty($default_message_type_names_for_messenger)) {
1358
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1359
-                    $messenger_to_generate->name,
1360
-                    $default_message_type_names_for_messenger,
1361
-                    '',
1362
-                    true
1363
-                );
1364
-            }
1365
-        }
1366
-        return $templates_generated;
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * This returns the default messengers to generate templates for on activation of EE.
1372
-     * It considers:
1373
-     * - whether a messenger is already active in the db.
1374
-     * - whether a messenger has been made active at any time in the past.
1375
-     *
1376
-     * @static
1377
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1378
-     * @return EE_messenger[]
1379
-     */
1380
-    protected static function _get_default_messengers_to_generate_on_activation(
1381
-        EE_Message_Resource_Manager $message_resource_manager
1382
-    ) {
1383
-        $active_messengers    = $message_resource_manager->active_messengers();
1384
-        $installed_messengers = $message_resource_manager->installed_messengers();
1385
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1386
-
1387
-        $messengers_to_generate = array();
1388
-        foreach ($installed_messengers as $installed_messenger) {
1389
-            // if installed messenger is a messenger that should be activated on install
1390
-            // and is not already active
1391
-            // and has never been activated
1392
-            if (! $installed_messenger->activate_on_install
1393
-                || isset($active_messengers[ $installed_messenger->name ])
1394
-                || isset($has_activated[ $installed_messenger->name ])
1395
-            ) {
1396
-                continue;
1397
-            }
1398
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1399
-        }
1400
-        return $messengers_to_generate;
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * This simply validates active message types to ensure they actually match installed
1406
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1407
-     * rows are set inactive.
1408
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1409
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1410
-     * are still handled in here.
1411
-     *
1412
-     * @since 4.3.1
1413
-     * @return void
1414
-     */
1415
-    public static function validate_messages_system()
1416
-    {
1417
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1418
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1419
-        $message_resource_manager->validate_active_message_types_are_installed();
1420
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * create_no_ticket_prices_array
1426
-     *
1427
-     * @access public
1428
-     * @static
1429
-     * @return void
1430
-     */
1431
-    public static function create_no_ticket_prices_array()
1432
-    {
1433
-        // this creates an array for tracking events that have no active ticket prices created
1434
-        // this allows us to warn admins of the situation so that it can be corrected
1435
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1436
-        if (! $espresso_no_ticket_prices) {
1437
-            add_option('ee_no_ticket_prices', array(), '', false);
1438
-        }
1439
-    }
1440
-
1441
-
1442
-    /**
1443
-     * plugin_deactivation
1444
-     *
1445
-     * @access public
1446
-     * @static
1447
-     * @return void
1448
-     */
1449
-    public static function plugin_deactivation()
1450
-    {
1451
-    }
1452
-
1453
-
1454
-    /**
1455
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1456
-     * (like post meta or term relations)
1457
-     *
1458
-     * @global wpdb $wpdb
1459
-     * @throws \EE_Error
1460
-     */
1461
-    public static function delete_all_espresso_cpt_data()
1462
-    {
1463
-        global $wpdb;
1464
-        // get all the CPT post_types
1465
-        $ee_post_types = array();
1466
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1467
-            if (method_exists($model_name, 'instance')) {
1468
-                $model_obj = call_user_func(array($model_name, 'instance'));
1469
-                if ($model_obj instanceof EEM_CPT_Base) {
1470
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1471
-                }
1472
-            }
1473
-        }
1474
-        // get all our CPTs
1475
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1476
-        $cpt_ids = $wpdb->get_col($query);
1477
-        // delete each post meta and term relations too
1478
-        foreach ($cpt_ids as $post_id) {
1479
-            wp_delete_post($post_id, true);
1480
-        }
1481
-    }
1482
-
1483
-    /**
1484
-     * Deletes all EE custom tables
1485
-     *
1486
-     * @return array
1487
-     */
1488
-    public static function drop_espresso_tables()
1489
-    {
1490
-        $tables = array();
1491
-        // load registry
1492
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1493
-            if (method_exists($model_name, 'instance')) {
1494
-                $model_obj = call_user_func(array($model_name, 'instance'));
1495
-                if ($model_obj instanceof EEM_Base) {
1496
-                    foreach ($model_obj->get_tables() as $table) {
1497
-                        if (strpos($table->get_table_name(), 'esp_')
1498
-                            &&
1499
-                            (
1500
-                                is_main_site()// main site? nuke them all
1501
-                                || ! $table->is_global()// not main site,but not global either. nuke it
1502
-                            )
1503
-                        ) {
1504
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1505
-                        }
1506
-                    }
1507
-                }
1508
-            }
1509
-        }
1510
-
1511
-        // there are some tables whose models were removed.
1512
-        // they should be removed when removing all EE core's data
1513
-        $tables_without_models = array(
1514
-            'esp_promotion',
1515
-            'esp_promotion_applied',
1516
-            'esp_promotion_object',
1517
-            'esp_promotion_rule',
1518
-            'esp_rule',
1519
-        );
1520
-        foreach ($tables_without_models as $table) {
1521
-            $tables[ $table ] = $table;
1522
-        }
1523
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1524
-    }
1525
-
1526
-
1527
-
1528
-    /**
1529
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1530
-     * each table name provided has a wpdb prefix attached, and that it exists.
1531
-     * Returns the list actually deleted
1532
-     *
1533
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1534
-     * @global WPDB $wpdb
1535
-     * @param array $table_names
1536
-     * @return array of table names which we deleted
1537
-     */
1538
-    public static function drop_tables($table_names)
1539
-    {
1540
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1541
-    }
1542
-
1543
-
1544
-
1545
-    /**
1546
-     * plugin_uninstall
1547
-     *
1548
-     * @access public
1549
-     * @static
1550
-     * @param bool $remove_all
1551
-     * @return void
1552
-     */
1553
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1554
-    {
1555
-        global $wpdb;
1556
-        self::drop_espresso_tables();
1557
-        $wp_options_to_delete = array(
1558
-            'ee_no_ticket_prices'                => true,
1559
-            'ee_active_messengers'               => true,
1560
-            'ee_has_activated_messenger'         => true,
1561
-            RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1562
-            'ee_config'                          => false,
1563
-            'ee_data_migration_current_db_state' => true,
1564
-            'ee_data_migration_mapping_'         => false,
1565
-            'ee_data_migration_script_'          => false,
1566
-            'ee_data_migrations'                 => true,
1567
-            'ee_dms_map'                         => false,
1568
-            'ee_notices'                         => true,
1569
-            'lang_file_check_'                   => false,
1570
-            'ee_maintenance_mode'                => true,
1571
-            'ee_ueip_optin'                      => true,
1572
-            'ee_ueip_has_notified'               => true,
1573
-            'ee_plugin_activation_errors'        => true,
1574
-            'ee_id_mapping_from'                 => false,
1575
-            'espresso_persistent_admin_notices'  => true,
1576
-            'ee_encryption_key'                  => true,
1577
-            'pue_force_upgrade_'                 => false,
1578
-            'pue_json_error_'                    => false,
1579
-            'pue_install_key_'                   => false,
1580
-            'pue_verification_error_'            => false,
1581
-            'pu_dismissed_upgrade_'              => false,
1582
-            'external_updates-'                  => false,
1583
-            'ee_extra_data'                      => true,
1584
-            'ee_ssn_'                            => false,
1585
-            'ee_rss_'                            => false,
1586
-            'ee_rte_n_tx_'                       => false,
1587
-            'ee_pers_admin_notices'              => true,
1588
-            'ee_job_parameters_'                 => false,
1589
-            'ee_upload_directories_incomplete'   => true,
1590
-            'ee_verified_db_collations'          => true,
1591
-        );
1592
-        if (is_main_site()) {
1593
-            $wp_options_to_delete['ee_network_config'] = true;
1594
-        }
1595
-        $undeleted_options = array();
1596
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1597
-            if ($no_wildcard) {
1598
-                if (! delete_option($option_name)) {
1599
-                    $undeleted_options[] = $option_name;
1600
-                }
1601
-            } else {
1602
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1603
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1604
-                    if (! delete_option($option_name_from_wildcard)) {
1605
-                        $undeleted_options[] = $option_name_from_wildcard;
1606
-                    }
1607
-                }
1608
-            }
1609
-        }
1610
-        // also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1611
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1612
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1613
-            $db_update_sans_ee4 = array();
1614
-            foreach ($espresso_db_update as $version => $times_activated) {
1615
-                if ((string) $version[0] === '3') {// if its NON EE4
1616
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1617
-                }
1618
-            }
1619
-            update_option('espresso_db_update', $db_update_sans_ee4);
1620
-        }
1621
-        $errors = '';
1622
-        if (! empty($undeleted_options)) {
1623
-            $errors .= sprintf(
1624
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1625
-                '<br/>',
1626
-                implode(',<br/>', $undeleted_options)
1627
-            );
1628
-        }
1629
-        if (! empty($errors)) {
1630
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1631
-        }
1632
-    }
1633
-
1634
-    /**
1635
-     * Gets the mysql error code from the last used query by wpdb
1636
-     *
1637
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1638
-     */
1639
-    public static function last_wpdb_error_code()
1640
-    {
1641
-        global $wpdb;
1642
-        return $wpdb->use_mysqli ? mysqli_errno($wpdb->dbh) : 0;
1643
-    }
1644
-
1645
-    /**
1646
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1647
-     *
1648
-     * @global wpdb  $wpdb
1649
-     * @deprecated instead use TableAnalysis::tableExists()
1650
-     * @param string $table_name with or without $wpdb->prefix
1651
-     * @return boolean
1652
-     */
1653
-    public static function table_exists($table_name)
1654
-    {
1655
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1656
-    }
1657
-
1658
-    /**
1659
-     * Resets the cache on EEH_Activation
1660
-     */
1661
-    public static function reset()
1662
-    {
1663
-        self::$_default_creator_id                             = null;
1664
-        self::$_initialized_db_content_already_in_this_request = false;
1665
-    }
1666
-
1667
-    /**
1668
-     * Removes 'email_confirm' from the Address info question group on activation
1669
-     * @return void
1670
-     */
1671
-    public static function removeEmailConfirmFromAddressGroup()
1672
-    {
1673
-
1674
-        // Pull the email_confirm question ID.
1675
-        $email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1676
-            EEM_Attendee::system_question_email_confirm
1677
-        );
1678
-        // Remove the email_confirm question group from the address group questions.
1679
-        EEM_Question_Group_Question::instance()->delete(
1680
-            array(
1681
-                array(
1682
-                    'QST_ID' => $email_confirm_question_id,
1683
-                    'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1684
-                ),
1685
-            )
1686
-        );
1687
-    }
1242
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1243
+			$message_resource_manager
1244
+		);
1245
+		/**
1246
+		 * This method is verifying there are no NEW default message types
1247
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1248
+		 */
1249
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
+			$message_resource_manager
1251
+		);
1252
+		// after all is done, let's persist these changes to the db.
1253
+		$message_resource_manager->update_has_activated_messengers_option();
1254
+		$message_resource_manager->update_active_messengers_option();
1255
+		// will return true if either of these are true.  Otherwise will return false.
1256
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1263
+	 * @return array|bool
1264
+	 * @throws \EE_Error
1265
+	 */
1266
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1267
+		EE_Message_Resource_Manager $message_resource_manager
1268
+	) {
1269
+		/** @type EE_messenger[] $active_messengers */
1270
+		$active_messengers = $message_resource_manager->active_messengers();
1271
+		$installed_message_types = $message_resource_manager->installed_message_types();
1272
+		$templates_created = false;
1273
+		foreach ($active_messengers as $active_messenger) {
1274
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1275
+			$default_message_type_names_to_activate = array();
1276
+			// looping through each default message type reported by the messenger
1277
+			// and setup the actual message types to activate.
1278
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1279
+				// if already active or has already been activated before we skip
1280
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1281
+				// we also skip if the message type is not installed.
1282
+				if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1283
+					$default_message_type_name_for_messenger,
1284
+					$active_messenger->name
1285
+				)
1286
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1287
+						$active_messenger->name,
1288
+						$default_message_type_name_for_messenger
1289
+					)
1290
+					|| ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1291
+				) {
1292
+					continue;
1293
+				}
1294
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1295
+			}
1296
+			// let's activate!
1297
+			$message_resource_manager->ensure_message_types_are_active(
1298
+				$default_message_type_names_to_activate,
1299
+				$active_messenger->name,
1300
+				false
1301
+			);
1302
+			// activate the templates for these message types
1303
+			if (! empty($default_message_type_names_to_activate)) {
1304
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1305
+					$active_messenger->name,
1306
+					$default_message_type_names_for_messenger,
1307
+					'',
1308
+					true
1309
+				);
1310
+			}
1311
+		}
1312
+		return $templates_created;
1313
+	}
1314
+
1315
+
1316
+
1317
+	/**
1318
+	 * This will activate and generate default messengers and default message types for those messengers.
1319
+	 *
1320
+	 * @param EE_message_Resource_Manager $message_resource_manager
1321
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1322
+	 *                     False means that there were no templates generated
1323
+	 *                     (which could simply mean there are no default message types for a messenger).
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1327
+		EE_Message_Resource_Manager $message_resource_manager
1328
+	) {
1329
+		/** @type EE_messenger[] $messengers_to_generate */
1330
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1331
+		$installed_message_types = $message_resource_manager->installed_message_types();
1332
+		$templates_generated = false;
1333
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1334
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1335
+			// verify the default message types match an installed message type.
1336
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1337
+				if (! isset($installed_message_types[ $name ])
1338
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1339
+						$name,
1340
+						$messenger_to_generate->name
1341
+					)
1342
+				) {
1343
+					unset($default_message_type_names_for_messenger[ $key ]);
1344
+				}
1345
+			}
1346
+			// in previous iterations, the active_messengers option in the db
1347
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1348
+			// This comment is left here just in case we discover that we _do_ need to update before
1349
+			// passing off to create templates (after the refactor is done).
1350
+			// @todo remove this comment when determined not necessary.
1351
+			$message_resource_manager->activate_messenger(
1352
+				$messenger_to_generate->name,
1353
+				$default_message_type_names_for_messenger,
1354
+				false
1355
+			);
1356
+			// create any templates needing created (or will reactivate templates already generated as necessary).
1357
+			if (! empty($default_message_type_names_for_messenger)) {
1358
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1359
+					$messenger_to_generate->name,
1360
+					$default_message_type_names_for_messenger,
1361
+					'',
1362
+					true
1363
+				);
1364
+			}
1365
+		}
1366
+		return $templates_generated;
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * This returns the default messengers to generate templates for on activation of EE.
1372
+	 * It considers:
1373
+	 * - whether a messenger is already active in the db.
1374
+	 * - whether a messenger has been made active at any time in the past.
1375
+	 *
1376
+	 * @static
1377
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1378
+	 * @return EE_messenger[]
1379
+	 */
1380
+	protected static function _get_default_messengers_to_generate_on_activation(
1381
+		EE_Message_Resource_Manager $message_resource_manager
1382
+	) {
1383
+		$active_messengers    = $message_resource_manager->active_messengers();
1384
+		$installed_messengers = $message_resource_manager->installed_messengers();
1385
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1386
+
1387
+		$messengers_to_generate = array();
1388
+		foreach ($installed_messengers as $installed_messenger) {
1389
+			// if installed messenger is a messenger that should be activated on install
1390
+			// and is not already active
1391
+			// and has never been activated
1392
+			if (! $installed_messenger->activate_on_install
1393
+				|| isset($active_messengers[ $installed_messenger->name ])
1394
+				|| isset($has_activated[ $installed_messenger->name ])
1395
+			) {
1396
+				continue;
1397
+			}
1398
+			$messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1399
+		}
1400
+		return $messengers_to_generate;
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * This simply validates active message types to ensure they actually match installed
1406
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1407
+	 * rows are set inactive.
1408
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1409
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1410
+	 * are still handled in here.
1411
+	 *
1412
+	 * @since 4.3.1
1413
+	 * @return void
1414
+	 */
1415
+	public static function validate_messages_system()
1416
+	{
1417
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1418
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1419
+		$message_resource_manager->validate_active_message_types_are_installed();
1420
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * create_no_ticket_prices_array
1426
+	 *
1427
+	 * @access public
1428
+	 * @static
1429
+	 * @return void
1430
+	 */
1431
+	public static function create_no_ticket_prices_array()
1432
+	{
1433
+		// this creates an array for tracking events that have no active ticket prices created
1434
+		// this allows us to warn admins of the situation so that it can be corrected
1435
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1436
+		if (! $espresso_no_ticket_prices) {
1437
+			add_option('ee_no_ticket_prices', array(), '', false);
1438
+		}
1439
+	}
1440
+
1441
+
1442
+	/**
1443
+	 * plugin_deactivation
1444
+	 *
1445
+	 * @access public
1446
+	 * @static
1447
+	 * @return void
1448
+	 */
1449
+	public static function plugin_deactivation()
1450
+	{
1451
+	}
1452
+
1453
+
1454
+	/**
1455
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1456
+	 * (like post meta or term relations)
1457
+	 *
1458
+	 * @global wpdb $wpdb
1459
+	 * @throws \EE_Error
1460
+	 */
1461
+	public static function delete_all_espresso_cpt_data()
1462
+	{
1463
+		global $wpdb;
1464
+		// get all the CPT post_types
1465
+		$ee_post_types = array();
1466
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1467
+			if (method_exists($model_name, 'instance')) {
1468
+				$model_obj = call_user_func(array($model_name, 'instance'));
1469
+				if ($model_obj instanceof EEM_CPT_Base) {
1470
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1471
+				}
1472
+			}
1473
+		}
1474
+		// get all our CPTs
1475
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1476
+		$cpt_ids = $wpdb->get_col($query);
1477
+		// delete each post meta and term relations too
1478
+		foreach ($cpt_ids as $post_id) {
1479
+			wp_delete_post($post_id, true);
1480
+		}
1481
+	}
1482
+
1483
+	/**
1484
+	 * Deletes all EE custom tables
1485
+	 *
1486
+	 * @return array
1487
+	 */
1488
+	public static function drop_espresso_tables()
1489
+	{
1490
+		$tables = array();
1491
+		// load registry
1492
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1493
+			if (method_exists($model_name, 'instance')) {
1494
+				$model_obj = call_user_func(array($model_name, 'instance'));
1495
+				if ($model_obj instanceof EEM_Base) {
1496
+					foreach ($model_obj->get_tables() as $table) {
1497
+						if (strpos($table->get_table_name(), 'esp_')
1498
+							&&
1499
+							(
1500
+								is_main_site()// main site? nuke them all
1501
+								|| ! $table->is_global()// not main site,but not global either. nuke it
1502
+							)
1503
+						) {
1504
+							$tables[ $table->get_table_name() ] = $table->get_table_name();
1505
+						}
1506
+					}
1507
+				}
1508
+			}
1509
+		}
1510
+
1511
+		// there are some tables whose models were removed.
1512
+		// they should be removed when removing all EE core's data
1513
+		$tables_without_models = array(
1514
+			'esp_promotion',
1515
+			'esp_promotion_applied',
1516
+			'esp_promotion_object',
1517
+			'esp_promotion_rule',
1518
+			'esp_rule',
1519
+		);
1520
+		foreach ($tables_without_models as $table) {
1521
+			$tables[ $table ] = $table;
1522
+		}
1523
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1524
+	}
1525
+
1526
+
1527
+
1528
+	/**
1529
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1530
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1531
+	 * Returns the list actually deleted
1532
+	 *
1533
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1534
+	 * @global WPDB $wpdb
1535
+	 * @param array $table_names
1536
+	 * @return array of table names which we deleted
1537
+	 */
1538
+	public static function drop_tables($table_names)
1539
+	{
1540
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1541
+	}
1542
+
1543
+
1544
+
1545
+	/**
1546
+	 * plugin_uninstall
1547
+	 *
1548
+	 * @access public
1549
+	 * @static
1550
+	 * @param bool $remove_all
1551
+	 * @return void
1552
+	 */
1553
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1554
+	{
1555
+		global $wpdb;
1556
+		self::drop_espresso_tables();
1557
+		$wp_options_to_delete = array(
1558
+			'ee_no_ticket_prices'                => true,
1559
+			'ee_active_messengers'               => true,
1560
+			'ee_has_activated_messenger'         => true,
1561
+			RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1562
+			'ee_config'                          => false,
1563
+			'ee_data_migration_current_db_state' => true,
1564
+			'ee_data_migration_mapping_'         => false,
1565
+			'ee_data_migration_script_'          => false,
1566
+			'ee_data_migrations'                 => true,
1567
+			'ee_dms_map'                         => false,
1568
+			'ee_notices'                         => true,
1569
+			'lang_file_check_'                   => false,
1570
+			'ee_maintenance_mode'                => true,
1571
+			'ee_ueip_optin'                      => true,
1572
+			'ee_ueip_has_notified'               => true,
1573
+			'ee_plugin_activation_errors'        => true,
1574
+			'ee_id_mapping_from'                 => false,
1575
+			'espresso_persistent_admin_notices'  => true,
1576
+			'ee_encryption_key'                  => true,
1577
+			'pue_force_upgrade_'                 => false,
1578
+			'pue_json_error_'                    => false,
1579
+			'pue_install_key_'                   => false,
1580
+			'pue_verification_error_'            => false,
1581
+			'pu_dismissed_upgrade_'              => false,
1582
+			'external_updates-'                  => false,
1583
+			'ee_extra_data'                      => true,
1584
+			'ee_ssn_'                            => false,
1585
+			'ee_rss_'                            => false,
1586
+			'ee_rte_n_tx_'                       => false,
1587
+			'ee_pers_admin_notices'              => true,
1588
+			'ee_job_parameters_'                 => false,
1589
+			'ee_upload_directories_incomplete'   => true,
1590
+			'ee_verified_db_collations'          => true,
1591
+		);
1592
+		if (is_main_site()) {
1593
+			$wp_options_to_delete['ee_network_config'] = true;
1594
+		}
1595
+		$undeleted_options = array();
1596
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1597
+			if ($no_wildcard) {
1598
+				if (! delete_option($option_name)) {
1599
+					$undeleted_options[] = $option_name;
1600
+				}
1601
+			} else {
1602
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1603
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1604
+					if (! delete_option($option_name_from_wildcard)) {
1605
+						$undeleted_options[] = $option_name_from_wildcard;
1606
+					}
1607
+				}
1608
+			}
1609
+		}
1610
+		// also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1611
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1612
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1613
+			$db_update_sans_ee4 = array();
1614
+			foreach ($espresso_db_update as $version => $times_activated) {
1615
+				if ((string) $version[0] === '3') {// if its NON EE4
1616
+					$db_update_sans_ee4[ $version ] = $times_activated;
1617
+				}
1618
+			}
1619
+			update_option('espresso_db_update', $db_update_sans_ee4);
1620
+		}
1621
+		$errors = '';
1622
+		if (! empty($undeleted_options)) {
1623
+			$errors .= sprintf(
1624
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1625
+				'<br/>',
1626
+				implode(',<br/>', $undeleted_options)
1627
+			);
1628
+		}
1629
+		if (! empty($errors)) {
1630
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1631
+		}
1632
+	}
1633
+
1634
+	/**
1635
+	 * Gets the mysql error code from the last used query by wpdb
1636
+	 *
1637
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1638
+	 */
1639
+	public static function last_wpdb_error_code()
1640
+	{
1641
+		global $wpdb;
1642
+		return $wpdb->use_mysqli ? mysqli_errno($wpdb->dbh) : 0;
1643
+	}
1644
+
1645
+	/**
1646
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1647
+	 *
1648
+	 * @global wpdb  $wpdb
1649
+	 * @deprecated instead use TableAnalysis::tableExists()
1650
+	 * @param string $table_name with or without $wpdb->prefix
1651
+	 * @return boolean
1652
+	 */
1653
+	public static function table_exists($table_name)
1654
+	{
1655
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1656
+	}
1657
+
1658
+	/**
1659
+	 * Resets the cache on EEH_Activation
1660
+	 */
1661
+	public static function reset()
1662
+	{
1663
+		self::$_default_creator_id                             = null;
1664
+		self::$_initialized_db_content_already_in_this_request = false;
1665
+	}
1666
+
1667
+	/**
1668
+	 * Removes 'email_confirm' from the Address info question group on activation
1669
+	 * @return void
1670
+	 */
1671
+	public static function removeEmailConfirmFromAddressGroup()
1672
+	{
1673
+
1674
+		// Pull the email_confirm question ID.
1675
+		$email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1676
+			EEM_Attendee::system_question_email_confirm
1677
+		);
1678
+		// Remove the email_confirm question group from the address group questions.
1679
+		EEM_Question_Group_Question::instance()->delete(
1680
+			array(
1681
+				array(
1682
+					'QST_ID' => $email_confirm_question_id,
1683
+					'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1684
+				),
1685
+			)
1686
+		);
1687
+	}
1688 1688
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Inflector.helper.php 2 patches
Indentation   +378 added lines, -378 removed lines patch added patch discarded remove patch
@@ -33,382 +33,382 @@
 block discarded – undo
33 33
  */
34 34
 class EEH_Inflector
35 35
 {
36
-    // ------ CLASS METHODS ------ //
37
-    // ---- Public methods ---- //
38
-    // {{{ pluralize()
39
-
40
-    /**
41
-     * Just calls self::pluralize and strtolower on $word and returns it
42
-     * @param string $word
43
-     * @return string
44
-     */
45
-    public static function pluralize_and_lower($word)
46
-    {
47
-        return strtolower(self::pluralize($word));
48
-    }
49
-
50
-
51
-
52
-    /**
53
-     * @param string $word
54
-     * @return mixed
55
-     */
56
-    public static function singularize_and_upper($word)
57
-    {
58
-        return str_replace(' ', '_', self::humanize(self::singularize($word), 'all'));
59
-    }
60
-
61
-
62
-
63
-    /**
64
-     * Pluralizes English nouns.
65
-     *
66
-     * @access public
67
-     * @static
68
-     * @param    string    $word    English noun to pluralize
69
-     * @return string Plural noun
70
-     */
71
-    public static function pluralize($word)
72
-    {
73
-        $plural = array(
74
-            '/(quiz)$/i'               => '\1zes',
75
-            '/^(ox)$/i'                => '\1en',
76
-            '/([m|l])ouse$/i'          => '\1ice',
77
-            '/(matr|vert|ind)ix|ex$/i' => '\1ices',
78
-            '/(x|ch|ss|sh)$/i'         => '\1es',
79
-            '/([^aeiouy]|qu)ies$/i'    => '\1y',
80
-            '/([^aeiouy]|qu)y$/i'      => '\1ies',
81
-            '/(hive)$/i'               => '\1s',
82
-            '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
83
-            '/sis$/i'                  => 'ses',
84
-            '/([ti])um$/i'             => '\1a',
85
-            '/(buffal|tomat)o$/i'      => '\1oes',
86
-            '/(bu)s$/i'                => '\1ses',
87
-            '/(alias|status)/i'        => '\1es',
88
-            '/(octop|vir)us$/i'        => '\1i',
89
-            '/(ax|test)is$/i'          => '\1es',
90
-            '/s$/i'                    => 's',
91
-            '/$/'                      => 's');
92
-
93
-        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
94
-
95
-        $irregular = array(
96
-            'person' => 'people',
97
-            'man'    => 'men',
98
-            'child'  => 'children',
99
-            'sex'    => 'sexes',
100
-            'move'   => 'moves');
101
-
102
-        $lowercased_word = strtolower($word);
103
-
104
-        foreach ($uncountable as $_uncountable) {
105
-            if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
106
-                    ! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])) {
107
-                return $word;
108
-            }
109
-        }
110
-
111
-        foreach ($irregular as $_plural => $_singular) {
112
-            if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
113
-                return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
114
-            }
115
-        }
116
-
117
-        foreach ($plural as $rule => $replacement) {
118
-            if (preg_match($rule, $word)) {
119
-                return preg_replace($rule, $replacement, $word);
120
-            }
121
-        }
122
-        return false;
123
-    }
124
-
125
-    // }}}
126
-    // {{{ singularize()
127
-
128
-    /**
129
-     * Singularizes English nouns.
130
-     *
131
-     * @access public
132
-     * @static
133
-     * @param    string    $word    English noun to singularize
134
-     * @return string Singular noun.
135
-     */
136
-    public static function singularize($word)
137
-    {
138
-        $singular = array(
139
-            '/(quiz)zes$/i'                                                    => '\1',
140
-            '/(matr)ices$/i'                                                   => '\1ix',
141
-            '/(vert|ind)ices$/i'                                               => '\1ex',
142
-            '/^(ox)en/i'                                                       => '\1',
143
-            '/(alias|status)es$/i'                                             => '\1',
144
-            '/([octop|vir])i$/i'                                               => '\1us',
145
-            '/(cris|ax|test)es$/i'                                             => '\1is',
146
-            '/(shoe)s$/i'                                                      => '\1',
147
-            '/(o)es$/i'                                                        => '\1',
148
-            '/(bus)es$/i'                                                      => '\1',
149
-            '/([m|l])ice$/i'                                                   => '\1ouse',
150
-            '/(x|ch|ss|sh)es$/i'                                               => '\1',
151
-            '/(m)ovies$/i'                                                     => '\1ovie',
152
-            '/(s)eries$/i'                                                     => '\1eries',
153
-            '/([^aeiouy]|qu)ies$/i'                                            => '\1y',
154
-            '/([lr])ves$/i'                                                    => '\1f',
155
-            '/(tive)s$/i'                                                      => '\1',
156
-            '/(hive)s$/i'                                                      => '\1',
157
-            '/([^f])ves$/i'                                                    => '\1fe',
158
-            '/(^analy)ses$/i'                                                  => '\1sis',
159
-            '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
160
-            '/([ti])a$/i'                                                      => '\1um',
161
-            '/(n)ews$/i'                                                       => '\1ews',
162
-            '/s$/i'                                                            => '',
163
-        );
164
-
165
-        $uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
166
-
167
-        $irregular = array(
168
-            'person' => 'people',
169
-            'man'    => 'men',
170
-            'child'  => 'children',
171
-            'sex'    => 'sexes',
172
-            'move'   => 'moves');
173
-
174
-        $lowercased_word = strtolower($word);
175
-        foreach ($uncountable as $_uncountable) {
176
-            if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
177
-                return $word;
178
-            }
179
-        }
180
-
181
-        foreach ($irregular as $_plural => $_singular) {
182
-            if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
183
-                return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
184
-            }
185
-        }
186
-
187
-        foreach ($singular as $rule => $replacement) {
188
-            if (preg_match($rule, $word)) {
189
-                return preg_replace($rule, $replacement, $word);
190
-            }
191
-        }
192
-
193
-        return $word;
194
-    }
195
-
196
-    // }}}
197
-    // {{{ titleize()
198
-
199
-    /**
200
-     * Converts an underscored or CamelCase word into a English
201
-     * sentence.
202
-     *
203
-     * The titleize static function converts text like "WelcomePage",
204
-     * "welcome_page" or  "welcome page" to this "Welcome
205
-     * Page".
206
-     * If second parameter is set to 'first' it will only
207
-     * capitalize the first character of the title.
208
-     *
209
-     * @access public
210
-     * @static
211
-     * @param    string    $word    Word to format as tile
212
-     * @param    string    $uppercase    If set to 'first' it will only uppercase the
213
-     * first character. Otherwise it will uppercase all
214
-     * the words in the title.
215
-     * @return string Text formatted as title
216
-     */
217
-    public static function titleize($word, $uppercase = '')
218
-    {
219
-        $uppercase = $uppercase === 'first' ? 'ucfirst' : 'ucwords';
220
-        return $uppercase(EEH_Inflector::humanize(EEH_Inflector::underscore($word)));
221
-    }
222
-
223
-    // }}}
224
-    // {{{ camelize()
225
-
226
-    /**
227
-     * Returns given word as CamelCased
228
-     *
229
-     * Converts a word like "send_email" to "SendEmail". It
230
-     * will remove non alphanumeric character from the word, so
231
-     * "who's online" will be converted to "WhoSOnline"
232
-     *
233
-     * @access public
234
-     * @static
235
-     * @see variablize
236
-     * @param    string    $word    Word to convert to camel case
237
-     * @return string UpperCamelCasedWord
238
-     */
239
-    public static function camelize($word)
240
-    {
241
-        return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word)));
242
-    }
243
-
244
-
245
-
246
-    /**
247
-     * Camelizes all but the first word. This is handy converting a method which followed EE4 legacy naming convention
248
-     * with the new PSR-based naming conventions
249
-     * @param $word
250
-     * @return string
251
-     */
252
-    public static function camelize_all_but_first($word)
253
-    {
254
-        return lcfirst(EEH_Inflector::camelize($word));
255
-    }
256
-    // }}}
257
-    // {{{ underscore()
258
-
259
-    /**
260
-     * Converts a word "into_it_s_underscored_version"
261
-     *
262
-     * Convert any "CamelCased" or "ordinary Word" into an
263
-     * "underscored_word".
264
-     *
265
-     * This can be really useful for creating friendly URLs.
266
-     *
267
-     * @access public
268
-     * @static
269
-     * @param    string    $word    Word to underscore
270
-     * @return string Underscored word
271
-     */
272
-    public static function underscore($word)
273
-    {
274
-        return strtolower(preg_replace('/[^A-Z^a-z^0-9]+/', '_', preg_replace('/([a-zd])([A-Z])/', '1_2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '1_2', $word))));
275
-    }
276
-
277
-    // }}}
278
-    // {{{ humanize()
279
-
280
-    /**
281
-     * Returns a human-readable string from $word
282
-     *
283
-     * Returns a human-readable string from $word, by replacing
284
-     * underscores with a space, and by upper-casing the initial
285
-     * character by default.
286
-     *
287
-     * If you need to uppercase all the words you just have to
288
-     * pass 'all' as a second parameter.
289
-     *
290
-     * @access public
291
-     * @static
292
-     * @param    string    $word    String to "humanize"
293
-     * @param    string    $uppercase    If set to 'all' it will uppercase all the words
294
-     * instead of just the first one.
295
-     * @return string Human-readable word
296
-     */
297
-    public static function humanize($word, $uppercase = '')
298
-    {
299
-        // make special exceptions for acronyms
300
-        $word = str_replace('wp_', 'WP_', $word);
301
-        $uppercase = $uppercase === 'all' ? 'ucwords' : 'ucfirst';
302
-        return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
303
-    }
304
-
305
-    // }}}
306
-    // {{{ variablize()
307
-
308
-    /**
309
-     * Same as camelize but first char is underscored
310
-     *
311
-     * Converts a word like "send_email" to "sendEmail". It
312
-     * will remove non alphanumeric character from the word, so
313
-     * "who's online" will be converted to "whoSOnline"
314
-     *
315
-     * @access public
316
-     * @static
317
-     * @see camelize
318
-     * @param    string    $word    Word to lowerCamelCase
319
-     * @return string Returns a lowerCamelCasedWord
320
-     */
321
-    public static function variablize($word)
322
-    {
323
-        $word = EEH_Inflector::camelize($word);
324
-        return strtolower($word[0]) . substr($word, 1);
325
-    }
326
-
327
-    // }}}
328
-    // {{{ tableize()
329
-
330
-    /**
331
-     * Converts a class name to its table name according to rails
332
-     * naming conventions.
333
-     *
334
-     * Converts "Person" to "people"
335
-     *
336
-     * @access public
337
-     * @static
338
-     * @see classify
339
-     * @param    string    $class_name    Class name for getting related table_name.
340
-     * @return string plural_table_name
341
-     */
342
-    public static function tableize($class_name)
343
-    {
344
-        return EEH_Inflector::pluralize(EEH_Inflector::underscore($class_name));
345
-    }
346
-
347
-    // }}}
348
-    // {{{ classify()
349
-
350
-    /**
351
-     * Converts a table name to its class name according to rails
352
-     * naming conventions.
353
-     *
354
-     * Converts "people" to "Person"
355
-     *
356
-     * @access public
357
-     * @static
358
-     * @see tableize
359
-     * @param    string    $table_name    Table name for getting related ClassName.
360
-     * @return string SingularClassName
361
-     */
362
-    public static function classify($table_name)
363
-    {
364
-        return EEH_Inflector::camelize(EEH_Inflector::singularize($table_name));
365
-    }
366
-
367
-    // }}}
368
-    // {{{ ordinalize()
369
-
370
-    /**
371
-     * Converts number to its ordinal English form.
372
-     *
373
-     * This method converts 13 to 13th, 2 to 2nd ...
374
-     *
375
-     * @access public
376
-     * @static
377
-     * @param    integer    $number    Number to get its ordinal value
378
-     * @return string Ordinal representation of given string.
379
-     */
380
-    public static function ordinalize($number)
381
-    {
382
-        if (in_array(($number % 100), range(11, 13))) {
383
-            return $number . 'th';
384
-        } else {
385
-            switch (($number % 10)) {
386
-                case 1:
387
-                    return $number . 'st';
388
-                    break;
389
-                case 2:
390
-                    return $number . 'nd';
391
-                    break;
392
-                case 3:
393
-                    return $number . 'rd';
394
-                default:
395
-                    return $number . 'th';
396
-                    break;
397
-            }
398
-        }
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * @param $string
405
-     * @return string
406
-     */
407
-    public static function add_indefinite_article($string)
408
-    {
409
-        if (strtolower($string) === 'null') {
410
-            return $string;
411
-        }
412
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
413
-    }
36
+	// ------ CLASS METHODS ------ //
37
+	// ---- Public methods ---- //
38
+	// {{{ pluralize()
39
+
40
+	/**
41
+	 * Just calls self::pluralize and strtolower on $word and returns it
42
+	 * @param string $word
43
+	 * @return string
44
+	 */
45
+	public static function pluralize_and_lower($word)
46
+	{
47
+		return strtolower(self::pluralize($word));
48
+	}
49
+
50
+
51
+
52
+	/**
53
+	 * @param string $word
54
+	 * @return mixed
55
+	 */
56
+	public static function singularize_and_upper($word)
57
+	{
58
+		return str_replace(' ', '_', self::humanize(self::singularize($word), 'all'));
59
+	}
60
+
61
+
62
+
63
+	/**
64
+	 * Pluralizes English nouns.
65
+	 *
66
+	 * @access public
67
+	 * @static
68
+	 * @param    string    $word    English noun to pluralize
69
+	 * @return string Plural noun
70
+	 */
71
+	public static function pluralize($word)
72
+	{
73
+		$plural = array(
74
+			'/(quiz)$/i'               => '\1zes',
75
+			'/^(ox)$/i'                => '\1en',
76
+			'/([m|l])ouse$/i'          => '\1ice',
77
+			'/(matr|vert|ind)ix|ex$/i' => '\1ices',
78
+			'/(x|ch|ss|sh)$/i'         => '\1es',
79
+			'/([^aeiouy]|qu)ies$/i'    => '\1y',
80
+			'/([^aeiouy]|qu)y$/i'      => '\1ies',
81
+			'/(hive)$/i'               => '\1s',
82
+			'/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
83
+			'/sis$/i'                  => 'ses',
84
+			'/([ti])um$/i'             => '\1a',
85
+			'/(buffal|tomat)o$/i'      => '\1oes',
86
+			'/(bu)s$/i'                => '\1ses',
87
+			'/(alias|status)/i'        => '\1es',
88
+			'/(octop|vir)us$/i'        => '\1i',
89
+			'/(ax|test)is$/i'          => '\1es',
90
+			'/s$/i'                    => 's',
91
+			'/$/'                      => 's');
92
+
93
+		$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
94
+
95
+		$irregular = array(
96
+			'person' => 'people',
97
+			'man'    => 'men',
98
+			'child'  => 'children',
99
+			'sex'    => 'sexes',
100
+			'move'   => 'moves');
101
+
102
+		$lowercased_word = strtolower($word);
103
+
104
+		foreach ($uncountable as $_uncountable) {
105
+			if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
106
+					! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])) {
107
+				return $word;
108
+			}
109
+		}
110
+
111
+		foreach ($irregular as $_plural => $_singular) {
112
+			if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
113
+				return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
114
+			}
115
+		}
116
+
117
+		foreach ($plural as $rule => $replacement) {
118
+			if (preg_match($rule, $word)) {
119
+				return preg_replace($rule, $replacement, $word);
120
+			}
121
+		}
122
+		return false;
123
+	}
124
+
125
+	// }}}
126
+	// {{{ singularize()
127
+
128
+	/**
129
+	 * Singularizes English nouns.
130
+	 *
131
+	 * @access public
132
+	 * @static
133
+	 * @param    string    $word    English noun to singularize
134
+	 * @return string Singular noun.
135
+	 */
136
+	public static function singularize($word)
137
+	{
138
+		$singular = array(
139
+			'/(quiz)zes$/i'                                                    => '\1',
140
+			'/(matr)ices$/i'                                                   => '\1ix',
141
+			'/(vert|ind)ices$/i'                                               => '\1ex',
142
+			'/^(ox)en/i'                                                       => '\1',
143
+			'/(alias|status)es$/i'                                             => '\1',
144
+			'/([octop|vir])i$/i'                                               => '\1us',
145
+			'/(cris|ax|test)es$/i'                                             => '\1is',
146
+			'/(shoe)s$/i'                                                      => '\1',
147
+			'/(o)es$/i'                                                        => '\1',
148
+			'/(bus)es$/i'                                                      => '\1',
149
+			'/([m|l])ice$/i'                                                   => '\1ouse',
150
+			'/(x|ch|ss|sh)es$/i'                                               => '\1',
151
+			'/(m)ovies$/i'                                                     => '\1ovie',
152
+			'/(s)eries$/i'                                                     => '\1eries',
153
+			'/([^aeiouy]|qu)ies$/i'                                            => '\1y',
154
+			'/([lr])ves$/i'                                                    => '\1f',
155
+			'/(tive)s$/i'                                                      => '\1',
156
+			'/(hive)s$/i'                                                      => '\1',
157
+			'/([^f])ves$/i'                                                    => '\1fe',
158
+			'/(^analy)ses$/i'                                                  => '\1sis',
159
+			'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
160
+			'/([ti])a$/i'                                                      => '\1um',
161
+			'/(n)ews$/i'                                                       => '\1ews',
162
+			'/s$/i'                                                            => '',
163
+		);
164
+
165
+		$uncountable = array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep');
166
+
167
+		$irregular = array(
168
+			'person' => 'people',
169
+			'man'    => 'men',
170
+			'child'  => 'children',
171
+			'sex'    => 'sexes',
172
+			'move'   => 'moves');
173
+
174
+		$lowercased_word = strtolower($word);
175
+		foreach ($uncountable as $_uncountable) {
176
+			if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable) {
177
+				return $word;
178
+			}
179
+		}
180
+
181
+		foreach ($irregular as $_plural => $_singular) {
182
+			if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
183
+				return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
184
+			}
185
+		}
186
+
187
+		foreach ($singular as $rule => $replacement) {
188
+			if (preg_match($rule, $word)) {
189
+				return preg_replace($rule, $replacement, $word);
190
+			}
191
+		}
192
+
193
+		return $word;
194
+	}
195
+
196
+	// }}}
197
+	// {{{ titleize()
198
+
199
+	/**
200
+	 * Converts an underscored or CamelCase word into a English
201
+	 * sentence.
202
+	 *
203
+	 * The titleize static function converts text like "WelcomePage",
204
+	 * "welcome_page" or  "welcome page" to this "Welcome
205
+	 * Page".
206
+	 * If second parameter is set to 'first' it will only
207
+	 * capitalize the first character of the title.
208
+	 *
209
+	 * @access public
210
+	 * @static
211
+	 * @param    string    $word    Word to format as tile
212
+	 * @param    string    $uppercase    If set to 'first' it will only uppercase the
213
+	 * first character. Otherwise it will uppercase all
214
+	 * the words in the title.
215
+	 * @return string Text formatted as title
216
+	 */
217
+	public static function titleize($word, $uppercase = '')
218
+	{
219
+		$uppercase = $uppercase === 'first' ? 'ucfirst' : 'ucwords';
220
+		return $uppercase(EEH_Inflector::humanize(EEH_Inflector::underscore($word)));
221
+	}
222
+
223
+	// }}}
224
+	// {{{ camelize()
225
+
226
+	/**
227
+	 * Returns given word as CamelCased
228
+	 *
229
+	 * Converts a word like "send_email" to "SendEmail". It
230
+	 * will remove non alphanumeric character from the word, so
231
+	 * "who's online" will be converted to "WhoSOnline"
232
+	 *
233
+	 * @access public
234
+	 * @static
235
+	 * @see variablize
236
+	 * @param    string    $word    Word to convert to camel case
237
+	 * @return string UpperCamelCasedWord
238
+	 */
239
+	public static function camelize($word)
240
+	{
241
+		return str_replace(' ', '', ucwords(preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $word)));
242
+	}
243
+
244
+
245
+
246
+	/**
247
+	 * Camelizes all but the first word. This is handy converting a method which followed EE4 legacy naming convention
248
+	 * with the new PSR-based naming conventions
249
+	 * @param $word
250
+	 * @return string
251
+	 */
252
+	public static function camelize_all_but_first($word)
253
+	{
254
+		return lcfirst(EEH_Inflector::camelize($word));
255
+	}
256
+	// }}}
257
+	// {{{ underscore()
258
+
259
+	/**
260
+	 * Converts a word "into_it_s_underscored_version"
261
+	 *
262
+	 * Convert any "CamelCased" or "ordinary Word" into an
263
+	 * "underscored_word".
264
+	 *
265
+	 * This can be really useful for creating friendly URLs.
266
+	 *
267
+	 * @access public
268
+	 * @static
269
+	 * @param    string    $word    Word to underscore
270
+	 * @return string Underscored word
271
+	 */
272
+	public static function underscore($word)
273
+	{
274
+		return strtolower(preg_replace('/[^A-Z^a-z^0-9]+/', '_', preg_replace('/([a-zd])([A-Z])/', '1_2', preg_replace('/([A-Z]+)([A-Z][a-z])/', '1_2', $word))));
275
+	}
276
+
277
+	// }}}
278
+	// {{{ humanize()
279
+
280
+	/**
281
+	 * Returns a human-readable string from $word
282
+	 *
283
+	 * Returns a human-readable string from $word, by replacing
284
+	 * underscores with a space, and by upper-casing the initial
285
+	 * character by default.
286
+	 *
287
+	 * If you need to uppercase all the words you just have to
288
+	 * pass 'all' as a second parameter.
289
+	 *
290
+	 * @access public
291
+	 * @static
292
+	 * @param    string    $word    String to "humanize"
293
+	 * @param    string    $uppercase    If set to 'all' it will uppercase all the words
294
+	 * instead of just the first one.
295
+	 * @return string Human-readable word
296
+	 */
297
+	public static function humanize($word, $uppercase = '')
298
+	{
299
+		// make special exceptions for acronyms
300
+		$word = str_replace('wp_', 'WP_', $word);
301
+		$uppercase = $uppercase === 'all' ? 'ucwords' : 'ucfirst';
302
+		return $uppercase(str_replace('_', ' ', preg_replace('/_id$/', '', $word)));
303
+	}
304
+
305
+	// }}}
306
+	// {{{ variablize()
307
+
308
+	/**
309
+	 * Same as camelize but first char is underscored
310
+	 *
311
+	 * Converts a word like "send_email" to "sendEmail". It
312
+	 * will remove non alphanumeric character from the word, so
313
+	 * "who's online" will be converted to "whoSOnline"
314
+	 *
315
+	 * @access public
316
+	 * @static
317
+	 * @see camelize
318
+	 * @param    string    $word    Word to lowerCamelCase
319
+	 * @return string Returns a lowerCamelCasedWord
320
+	 */
321
+	public static function variablize($word)
322
+	{
323
+		$word = EEH_Inflector::camelize($word);
324
+		return strtolower($word[0]) . substr($word, 1);
325
+	}
326
+
327
+	// }}}
328
+	// {{{ tableize()
329
+
330
+	/**
331
+	 * Converts a class name to its table name according to rails
332
+	 * naming conventions.
333
+	 *
334
+	 * Converts "Person" to "people"
335
+	 *
336
+	 * @access public
337
+	 * @static
338
+	 * @see classify
339
+	 * @param    string    $class_name    Class name for getting related table_name.
340
+	 * @return string plural_table_name
341
+	 */
342
+	public static function tableize($class_name)
343
+	{
344
+		return EEH_Inflector::pluralize(EEH_Inflector::underscore($class_name));
345
+	}
346
+
347
+	// }}}
348
+	// {{{ classify()
349
+
350
+	/**
351
+	 * Converts a table name to its class name according to rails
352
+	 * naming conventions.
353
+	 *
354
+	 * Converts "people" to "Person"
355
+	 *
356
+	 * @access public
357
+	 * @static
358
+	 * @see tableize
359
+	 * @param    string    $table_name    Table name for getting related ClassName.
360
+	 * @return string SingularClassName
361
+	 */
362
+	public static function classify($table_name)
363
+	{
364
+		return EEH_Inflector::camelize(EEH_Inflector::singularize($table_name));
365
+	}
366
+
367
+	// }}}
368
+	// {{{ ordinalize()
369
+
370
+	/**
371
+	 * Converts number to its ordinal English form.
372
+	 *
373
+	 * This method converts 13 to 13th, 2 to 2nd ...
374
+	 *
375
+	 * @access public
376
+	 * @static
377
+	 * @param    integer    $number    Number to get its ordinal value
378
+	 * @return string Ordinal representation of given string.
379
+	 */
380
+	public static function ordinalize($number)
381
+	{
382
+		if (in_array(($number % 100), range(11, 13))) {
383
+			return $number . 'th';
384
+		} else {
385
+			switch (($number % 10)) {
386
+				case 1:
387
+					return $number . 'st';
388
+					break;
389
+				case 2:
390
+					return $number . 'nd';
391
+					break;
392
+				case 3:
393
+					return $number . 'rd';
394
+				default:
395
+					return $number . 'th';
396
+					break;
397
+			}
398
+		}
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * @param $string
405
+	 * @return string
406
+	 */
407
+	public static function add_indefinite_article($string)
408
+	{
409
+		if (strtolower($string) === 'null') {
410
+			return $string;
411
+		}
412
+		return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
413
+	}
414 414
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -103,14 +103,14 @@  discard block
 block discarded – undo
103 103
 
104 104
         foreach ($uncountable as $_uncountable) {
105 105
             if (substr($lowercased_word, (-1 * strlen($_uncountable))) == $_uncountable && // even though the word "price" ends in "rice", it can be pluralized, so check the previous character isnt a letter
106
-                    ! ctype_alpha($lowercased_word[ strlen($lowercased_word) - strlen($_uncountable) ])) {
106
+                    ! ctype_alpha($lowercased_word[strlen($lowercased_word) - strlen($_uncountable)])) {
107 107
                 return $word;
108 108
             }
109 109
         }
110 110
 
111 111
         foreach ($irregular as $_plural => $_singular) {
112
-            if (preg_match('/(' . $_plural . ')$/i', $word, $arr)) {
113
-                return preg_replace('/(' . $_plural . ')$/i', substr($arr[0], 0, 1) . substr($_singular, 1), $word);
112
+            if (preg_match('/('.$_plural.')$/i', $word, $arr)) {
113
+                return preg_replace('/('.$_plural.')$/i', substr($arr[0], 0, 1).substr($_singular, 1), $word);
114 114
             }
115 115
         }
116 116
 
@@ -179,8 +179,8 @@  discard block
 block discarded – undo
179 179
         }
180 180
 
181 181
         foreach ($irregular as $_plural => $_singular) {
182
-            if (preg_match('/(' . $_singular . ')$/i', $word, $arr)) {
183
-                return preg_replace('/(' . $_singular . ')$/i', substr($arr[0], 0, 1) . substr($_plural, 1), $word);
182
+            if (preg_match('/('.$_singular.')$/i', $word, $arr)) {
183
+                return preg_replace('/('.$_singular.')$/i', substr($arr[0], 0, 1).substr($_plural, 1), $word);
184 184
             }
185 185
         }
186 186
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
     public static function variablize($word)
322 322
     {
323 323
         $word = EEH_Inflector::camelize($word);
324
-        return strtolower($word[0]) . substr($word, 1);
324
+        return strtolower($word[0]).substr($word, 1);
325 325
     }
326 326
 
327 327
     // }}}
@@ -380,19 +380,19 @@  discard block
 block discarded – undo
380 380
     public static function ordinalize($number)
381 381
     {
382 382
         if (in_array(($number % 100), range(11, 13))) {
383
-            return $number . 'th';
383
+            return $number.'th';
384 384
         } else {
385 385
             switch (($number % 10)) {
386 386
                 case 1:
387
-                    return $number . 'st';
387
+                    return $number.'st';
388 388
                     break;
389 389
                 case 2:
390
-                    return $number . 'nd';
390
+                    return $number.'nd';
391 391
                     break;
392 392
                 case 3:
393
-                    return $number . 'rd';
393
+                    return $number.'rd';
394 394
                 default:
395
-                    return $number . 'th';
395
+                    return $number.'th';
396 396
                     break;
397 397
             }
398 398
         }
@@ -409,6 +409,6 @@  discard block
 block discarded – undo
409 409
         if (strtolower($string) === 'null') {
410 410
             return $string;
411 411
         }
412
-        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ') . $string;
412
+        return (stripos('aeiou', $string[0]) !== false ? 'an ' : 'a ').$string;
413 413
     }
414 414
 }
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 2 patches
Indentation   +1227 added lines, -1227 removed lines patch added patch discarded remove patch
@@ -14,1231 +14,1231 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * Holds a collection of EE_Message_Template_Pack objects.
19
-     * @type EE_Messages_Template_Pack_Collection
20
-     */
21
-    protected static $_template_pack_collection;
22
-
23
-
24
-
25
-
26
-    private static function _set_autoloader()
27
-    {
28
-        EED_Messages::set_autoloaders();
29
-    }
30
-
31
-
32
-    /**
33
-     * generate_new_templates
34
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will automatically create the defaults for the event.  The user would then be redirected to edit the default context for the event.
35
-     *
36
-     * @access protected
37
-     * @param  string $messenger     the messenger we are generating templates for
38
-     * @param array   $message_types array of message types that the templates are generated for.
39
-     * @param int     $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID to use as the base for the new generated template.
40
-     * @param bool    $global        true indicates generating templates on messenger activation. false requires GRP_ID for event specific template generation.
41
-     * @throws \EE_Error
42
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array for templates
43
-     *                that are generated.  If this is an empty array then it means no templates were generated which usually
44
-     *                means there was an error.  Anything in the array with an empty value for `MTP_context` means that it
45
-     *                was not a new generated template but just reactivated (which only happens for global templates that
46
-     *                already exist in the database.
47
-     */
48
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
49
-    {
50
-        // make sure message_type is an array.
51
-        $message_types = (array) $message_types;
52
-        $templates = array();
53
-
54
-        if (empty($messenger)) {
55
-            throw new EE_Error(__('We need a messenger to generate templates!', 'event_espresso'));
56
-        }
57
-
58
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
59
-        if (empty($message_types)) {
60
-            throw new EE_Error(__('We need at least one message type to generate templates!', 'event_espresso'));
61
-        }
62
-
63
-        EEH_MSG_Template::_set_autoloader();
64
-        foreach ($message_types as $message_type) {
65
-            // if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
66
-            if ($global && empty($GRP_ID)) {
67
-                $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
68
-                    array(
69
-                        array(
70
-                            'MTP_messenger'    => $messenger,
71
-                            'MTP_message_type' => $message_type,
72
-                            'MTP_is_global'    => true,
73
-                        ),
74
-                    )
75
-                );
76
-                $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
77
-            }
78
-            // if this is global template generation.
79
-            // First let's determine if we already HAVE global templates for this messenger and message_type combination.
80
-            //  If we do then NO generation!!
81
-            if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
82
-                $templates[] = array(
83
-                    'GRP_ID' => $GRP_ID,
84
-                    'MTP_context' => '',
85
-                );
86
-                // we already have generated templates for this so let's go to the next message type.
87
-                continue;
88
-            }
89
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90
-
91
-            if (! $new_message_template_group) {
92
-                continue;
93
-            }
94
-            $templates[] = $new_message_template_group;
95
-        }
96
-
97
-        return $templates;
98
-    }
99
-
100
-
101
-    /**
102
-     * The purpose of this method is to determine if there are already generated templates in the database for the given variables.
103
-     * @param  string $messenger     messenger
104
-     * @param  string $message_type message type
105
-     * @param  int $GRP_ID        GRP ID ( if a custom template) (if not provided then we're just doing global template check)
106
-     * @return bool                true = generated, false = hasn't been generated.
107
-     */
108
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
109
-    {
110
-        EEH_MSG_Template::_set_autoloader();
111
-        // what method we use depends on whether we have an GRP_ID or not
112
-        $count = empty($GRP_ID)
113
-            ? EEM_Message_Template::instance()->count(
114
-                array(
115
-                    array(
116
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
117
-                        'Message_Template_Group.MTP_message_type' => $message_type,
118
-                        'Message_Template_Group.MTP_is_global'    => true
119
-                    )
120
-                )
121
-            )
122
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
123
-
124
-        return $count > 0;
125
-    }
126
-
127
-
128
-
129
-
130
-    /**
131
-     * Updates all message templates matching the incoming messengers and message types to active status.
132
-     *
133
-     * @static
134
-     * @param  array  $messenger_names     Messenger slug
135
-     * @param  array  $message_type_names  Message type slug
136
-     * @return  int                         count of updated records.
137
-     */
138
-    public static function update_to_active($messenger_names, $message_type_names)
139
-    {
140
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
142
-        return EEM_Message_Template_Group::instance()->update(
143
-            array( 'MTP_is_active' => 1 ),
144
-            array(
145
-                array(
146
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
147
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
148
-                )
149
-            )
150
-        );
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Updates all message template groups matching the incoming arguments to inactive status.
157
-     *
158
-     * @static
159
-     * @param array $messenger_names    The messenger slugs.
160
-     *                              If empty then all templates matching the message types are marked inactive.
161
-     *                              Otherwise only templates matching the messengers and message types.
162
-     * @param array $message_type_names     The message type slugs.
163
-     *                              If empty then all templates matching the messengers are marked inactive.
164
-     *                              Otherwise only templates matching the messengers and message types.
165
-     *
166
-     * @return int  count of updated records.
167
-     */
168
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
169
-    {
170
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
171
-            $messenger_names,
172
-            $message_type_names
173
-        );
174
-    }
175
-
176
-
177
-    /**
178
-     * The purpose of this function is to return all installed message objects
179
-     * (messengers and message type regardless of whether they are ACTIVE or not)
180
-     *
181
-     * @deprecated 4.9.0
182
-     * @static
183
-     * @param string $type
184
-     * @return array array consisting of installed messenger objects and installed message type objects.
185
-     */
186
-    public static function get_installed_message_objects($type = 'all')
187
-    {
188
-        self::_set_autoloader();
189
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
190
-        return array(
191
-            'messenger' => $message_resource_manager->installed_messengers(),
192
-            'message_type' => $message_resource_manager->installed_message_types()
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * This will return an array of shortcodes => labels from the
199
-     * messenger and message_type objects associated with this
200
-     * template.
201
-     *
202
-     * @since 4.3.0
203
-     *
204
-     * @param string $message_type
205
-     * @param string $messenger
206
-     * @param array  $fields    What fields we're returning valid shortcodes for.
207
-     *                          If empty then we assume all fields are to be returned. Optional.
208
-     * @param string $context   What context we're going to return shortcodes for. Optional.
209
-     * @param bool $merged      If TRUE then we don't return shortcodes indexed by field,
210
-     *                          but instead an array of the unique shortcodes for all the given ( or all) fields.
211
-     *                          Optional.
212
-     * @throws \EE_Error
213
-     * @return mixed (array|bool) an array of shortcodes in the format
214
-     *                                              array( '[shortcode] => 'label')
215
-     *                                              OR
216
-     *                                              FALSE if no shortcodes found.
217
-     */
218
-    public static function get_shortcodes(
219
-        $message_type,
220
-        $messenger,
221
-        $fields = array(),
222
-        $context = 'admin',
223
-        $merged = false
224
-    ) {
225
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
226
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
227
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
228
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
229
-        // convert slug to object
230
-        $messenger = $message_resource_manager->get_messenger($messenger);
231
-
232
-        // if messenger isn't a EE_messenger resource then bail.
233
-        if (! $messenger instanceof EE_messenger) {
234
-            return array();
235
-        }
236
-
237
-        // validate class for getting our list of shortcodes
238
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
-        if (! class_exists($classname)) {
240
-            $msg[] = __('The Validator class was unable to load', 'event_espresso');
241
-            $msg[] = sprintf(
242
-                __('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
243
-                $classname
244
-            );
245
-            throw new EE_Error(implode('||', $msg));
246
-        }
247
-
248
-        /** @type EE_Messages_Validator $_VLD */
249
-        $_VLD = new $classname(array(), $context);
250
-        $valid_shortcodes = $_VLD->get_validators();
251
-
252
-        // let's make sure we're only getting the shortcode part of the validators
253
-        $shortcodes = array();
254
-        foreach ($valid_shortcodes as $field => $validators) {
255
-            $shortcodes[ $field ] = $validators['shortcodes'];
256
-        }
257
-        $valid_shortcodes = $shortcodes;
258
-
259
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
-        if (! empty($fields)) {
261
-            $specified_shortcodes = array();
262
-            foreach ($fields as $field) {
263
-                if (isset($valid_shortcodes[ $field ])) {
264
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
265
-                }
266
-            }
267
-            $valid_shortcodes = $specified_shortcodes;
268
-        }
269
-
270
-        // if not merged then let's replace the fields with the localized fields
271
-        if (! $merged) {
272
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273
-            $field_settings = $messenger->get_template_fields();
274
-            $localized = array();
275
-            foreach ($valid_shortcodes as $field => $shortcodes) {
276
-                // get localized field label
277
-                if (isset($field_settings[ $field ])) {
278
-                    // possible that this is used as a main field.
279
-                    if (empty($field_settings[ $field ])) {
280
-                        if (isset($field_settings['extra'][ $field ])) {
281
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
282
-                        } else {
283
-                            $_field = $field;
284
-                        }
285
-                    } else {
286
-                        $_field = $field_settings[ $field ]['label'];
287
-                    }
288
-                } elseif (isset($field_settings['extra'])) {
289
-                    // loop through extra "main fields" and see if any of their children have our field
290
-                    foreach ($field_settings['extra'] as $main_field => $fields) {
291
-                        if (isset($fields[ $field ])) {
292
-                            $_field = $fields[ $field ]['label'];
293
-                        } else {
294
-                            $_field = $field;
295
-                        }
296
-                    }
297
-                } else {
298
-                    $_field = $field;
299
-                }
300
-                if (isset($_field)) {
301
-                    $localized[ (string) $_field ] = $shortcodes;
302
-                }
303
-            }
304
-            $valid_shortcodes = $localized;
305
-        }
306
-
307
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
308
-        if ($merged) {
309
-            $merged_codes = array();
310
-            foreach ($valid_shortcodes as $field => $shortcode) {
311
-                foreach ($shortcode as $code => $label) {
312
-                    if (isset($merged_codes[ $code ])) {
313
-                        continue;
314
-                    } else {
315
-                        $merged_codes[ $code ] = $label;
316
-                    }
317
-                }
318
-            }
319
-            $valid_shortcodes = $merged_codes;
320
-        }
321
-
322
-        return $valid_shortcodes;
323
-    }
324
-
325
-
326
-    /**
327
-     * Get Messenger object.
328
-     *
329
-     * @since 4.3.0
330
-     * @deprecated 4.9.0
331
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
332
-     * @throws \EE_Error
333
-     * @return EE_messenger
334
-     */
335
-    public static function messenger_obj($messenger)
336
-    {
337
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
338
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
339
-        return $Message_Resource_Manager->get_messenger($messenger);
340
-    }
341
-
342
-
343
-    /**
344
-     * get Message type object
345
-     *
346
-     * @since 4.3.0
347
-     * @deprecated 4.9.0
348
-     * @param string $message_type the slug for the message type object to retrieve
349
-     * @throws \EE_Error
350
-     * @return EE_message_type
351
-     */
352
-    public static function message_type_obj($message_type)
353
-    {
354
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
355
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
356
-        return $Message_Resource_Manager->get_message_type($message_type);
357
-    }
358
-
359
-
360
-
361
-
362
-
363
-    /**
364
-     * Given a message_type slug, will return whether that message type is active in the system or not.
365
-     *
366
-     * @since    4.3.0
367
-     * @param  string   $message_type message type to check for.
368
-     * @return boolean
369
-     */
370
-    public static function is_mt_active($message_type)
371
-    {
372
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
373
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
374
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
375
-        return in_array($message_type, $active_mts);
376
-    }
377
-
378
-
379
-
380
-    /**
381
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
382
-     *
383
-     * @since    4.3.0
384
-     *
385
-     * @param  string  $messenger slug for messenger to check.
386
-     * @return boolean
387
-     */
388
-    public static function is_messenger_active($messenger)
389
-    {
390
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
391
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
392
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
393
-        return $active_messenger instanceof EE_messenger ? true : false;
394
-    }
395
-
396
-
397
-
398
-    /**
399
-     * Used to return active messengers array stored in the wp options table.
400
-     * If no value is present in the option then an empty array is returned.
401
-     *
402
-     * @deprecated 4.9
403
-     * @since 4.3.1
404
-     *
405
-     * @return array
406
-     */
407
-    public static function get_active_messengers_in_db()
408
-    {
409
-        EE_Error::doing_it_wrong(
410
-            __METHOD__,
411
-            __('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
412
-            '4.9.0'
413
-        );
414
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
415
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
416
-        return $Message_Resource_Manager->get_active_messengers_option();
417
-    }
418
-
419
-
420
-
421
-
422
-    /**
423
-     * Used to update the active messengers array stored in the wp options table.
424
-     *
425
-     * @since 4.3.1
426
-     * @deprecated 4.9.0
427
-     *
428
-     * @param array $data_to_save Incoming data to save.
429
-     *
430
-     * @return bool FALSE if not updated, TRUE if updated.
431
-     */
432
-    public static function update_active_messengers_in_db($data_to_save)
433
-    {
434
-        EE_Error::doing_it_wrong(
435
-            __METHOD__,
436
-            __('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
437
-            '4.9.0'
438
-        );
439
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
440
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
441
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
442
-    }
443
-
444
-
445
-    /**
446
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
447
-     * appropriate url trigger
448
-     *
449
-     * @param EE_message_type $message_type
450
-     * @param EE_Message $message
451
-     * @param EE_Registration | null $registration  The registration object must be included if this
452
-     *                                              is going to be a registration trigger url.
453
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
454
-     *
455
-     * @return string
456
-     * @throws EE_Error
457
-     */
458
-    public static function get_url_trigger(
459
-        EE_message_type $message_type,
460
-        EE_Message $message,
461
-        $registration = null,
462
-        $sending_messenger = ''
463
-    ) {
464
-        // first determine if the url can be to the EE_Message object.
465
-        if (! $message_type->always_generate()) {
466
-            return EEH_MSG_Template::generate_browser_trigger($message);
467
-        }
468
-
469
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
470
-        if (! $registration instanceof EE_Registration) {
471
-            throw new EE_Error(
472
-                __('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473
-            );
474
-        }
475
-
476
-        // validate given context
477
-        $contexts = $message_type->get_contexts();
478
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
479
-            throw new EE_Error(
480
-                sprintf(
481
-                    __('The context %s is not a valid context for %s.', 'event_espresso'),
482
-                    $message->context(),
483
-                    get_class($message_type)
484
-                )
485
-            );
486
-        }
487
-
488
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
-        if (! empty($sending_messenger)) {
490
-            $with_messengers = $message_type->with_messengers();
491
-            if (! isset($with_messengers[ $message->messenger() ])
492
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])) {
493
-                throw new EE_Error(
494
-                    sprintf(
495
-                        __(
496
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
497
-                            'event_espresso'
498
-                        ),
499
-                        $sending_messenger,
500
-                        get_class($message_type)
501
-                    )
502
-                );
503
-            }
504
-        } else {
505
-            $sending_messenger = $message->messenger();
506
-        }
507
-        return EEH_MSG_Template::generate_url_trigger(
508
-            $sending_messenger,
509
-            $message->messenger(),
510
-            $message->context(),
511
-            $message->message_type(),
512
-            $registration,
513
-            $message->GRP_ID()
514
-        );
515
-    }
516
-
517
-
518
-    /**
519
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
520
-     * @param EE_Message $message
521
-     * @return string.
522
-     */
523
-    public static function generate_browser_trigger(EE_Message $message)
524
-    {
525
-        $query_args = array(
526
-            'ee' => 'msg_browser_trigger',
527
-            'token' => $message->MSG_token()
528
-        );
529
-        return apply_filters(
530
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
531
-            add_query_arg($query_args, site_url()),
532
-            $message
533
-        );
534
-    }
535
-
536
-
537
-
538
-
539
-
540
-
541
-    /**
542
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
543
-     * @param EE_Message $message
544
-     * @return string
545
-     */
546
-    public static function generate_error_display_trigger(EE_Message $message)
547
-    {
548
-        return apply_filters(
549
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
550
-            add_query_arg(
551
-                array(
552
-                    'ee' => 'msg_browser_error_trigger',
553
-                    'token' => $message->MSG_token()
554
-                ),
555
-                site_url()
556
-            ),
557
-            $message
558
-        );
559
-    }
560
-
561
-
562
-
563
-
564
-
565
-
566
-    /**
567
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
568
-     *
569
-     * @param string          $sending_messenger    The sending messenger slug.
570
-     * @param string          $generating_messenger The generating messenger slug.
571
-     * @param string          $context              The context for the template.
572
-     * @param string          $message_type         The message type slug
573
-     * @param EE_Registration $registration
574
-     * @param integer          $message_template_group id   The EE_Message_Template_Group ID for the template.
575
-     * @param integer          $data_id     The id to the EE_Base_Class for getting the data used by the trigger.
576
-     * @return string          The generated url.
577
-     */
578
-    public static function generate_url_trigger(
579
-        $sending_messenger,
580
-        $generating_messenger,
581
-        $context,
582
-        $message_type,
583
-        EE_Registration $registration,
584
-        $message_template_group,
585
-        $data_id = 0
586
-    ) {
587
-        $query_args = array(
588
-            'ee' => 'msg_url_trigger',
589
-            'snd_msgr' => $sending_messenger,
590
-            'gen_msgr' => $generating_messenger,
591
-            'message_type' => $message_type,
592
-            'context' => $context,
593
-            'token' => $registration->reg_url_link(),
594
-            'GRP_ID' => $message_template_group,
595
-            'id' => $data_id
596
-            );
597
-        $url = add_query_arg($query_args, get_home_url());
598
-
599
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
600
-        $url = apply_filters(
601
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
602
-            $url,
603
-            $sending_messenger,
604
-            $generating_messenger,
605
-            $context,
606
-            $message_type,
607
-            $registration,
608
-            $message_template_group,
609
-            $data_id
610
-        );
611
-        return $url;
612
-    }
613
-
614
-
615
-
616
-
617
-    /**
618
-     * Return the specific css for the action icon given.
619
-     *
620
-     * @since 4.9.0
621
-     *
622
-     * @param string $type  What action to return.
623
-     * @return string
624
-     */
625
-    public static function get_message_action_icon($type)
626
-    {
627
-        $action_icons = self::get_message_action_icons();
628
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
629
-    }
630
-
631
-
632
-    /**
633
-     * This is used for retrieving the css classes used for the icons representing message actions.
634
-     *
635
-     * @since 4.9.0
636
-     *
637
-     * @return array
638
-     */
639
-    public static function get_message_action_icons()
640
-    {
641
-        return apply_filters(
642
-            'FHEE__EEH_MSG_Template__message_action_icons',
643
-            array(
644
-                'view' => array(
645
-                    'label' => __('View Message', 'event_espresso'),
646
-                    'css_class' => 'dashicons dashicons-welcome-view-site',
647
-                ),
648
-                'error' => array(
649
-                    'label' => __('View Error Message', 'event_espresso'),
650
-                    'css_class' => 'dashicons dashicons-info',
651
-                ),
652
-                'see_notifications_for' => array(
653
-                    'label' => __('View Related Messages', 'event_espresso'),
654
-                    'css_class' => 'dashicons dashicons-megaphone',
655
-                ),
656
-                'generate_now' => array(
657
-                    'label' => __('Generate the message now.', 'event_espresso'),
658
-                    'css_class' => 'dashicons dashicons-admin-tools',
659
-                ),
660
-                'send_now' => array(
661
-                    'label' => __('Send Immediately', 'event_espresso'),
662
-                    'css_class' => 'dashicons dashicons-controls-forward',
663
-                ),
664
-                'queue_for_resending' => array(
665
-                    'label' => __('Queue for Resending', 'event_espresso'),
666
-                    'css_class' => 'dashicons dashicons-controls-repeat',
667
-                ),
668
-                'view_transaction' => array(
669
-                    'label' => __('View related Transaction', 'event_espresso'),
670
-                    'css_class' => 'dashicons dashicons-cart',
671
-                )
672
-            )
673
-        );
674
-    }
675
-
676
-
677
-    /**
678
-     * This returns the url for a given action related to EE_Message.
679
-     *
680
-     * @since 4.9.0
681
-     *
682
-     * @param string $type  What type of action to return the url for.
683
-     * @param EE_Message $message   Required for generating the correct url for some types.
684
-     * @param array  $query_params   Any additional query params to be included with the generated url.
685
-     *
686
-     * @return string
687
-     */
688
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689
-    {
690
-        $action_urls = self::get_message_action_urls($message, $query_params);
691
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
692
-    }
693
-
694
-
695
-
696
-    /**
697
-     * This returns all the current urls for EE_Message actions.
698
-     *
699
-     * @since 4.9.0
700
-     *
701
-     * @param  EE_Message   $message    The EE_Message object required to generate correct urls for some types.
702
-     * @param  array    $query_params   Any additional query_params to be included with the generated url.
703
-     *
704
-     * @return array
705
-     */
706
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
707
-    {
708
-        EE_Registry::instance()->load_helper('URL');
709
-        // if $message is not an instance of EE_Message then let's just do a dummy.
710
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
711
-        $action_urls =  apply_filters(
712
-            'FHEE__EEH_MSG_Template__get_message_action_url',
713
-            array(
714
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
715
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
716
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
717
-                    array_merge(
718
-                        array(
719
-                            'page' => 'espresso_messages',
720
-                            'action' => 'default',
721
-                            'filterby' => 1,
722
-                        ),
723
-                        $query_params
724
-                    ),
725
-                    admin_url('admin.php')
726
-                ),
727
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
728
-                    array(
729
-                        'page' => 'espresso_messages',
730
-                        'action' => 'generate_now',
731
-                        'MSG_ID' => $message->ID()
732
-                    ),
733
-                    admin_url('admin.php')
734
-                ),
735
-                'send_now' => EEH_URL::add_query_args_and_nonce(
736
-                    array(
737
-                        'page' => 'espresso_messages',
738
-                        'action' => 'send_now',
739
-                        'MSG_ID' => $message->ID()
740
-                    ),
741
-                    admin_url('admin.php')
742
-                ),
743
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
744
-                    array(
745
-                        'page' => 'espresso_messages',
746
-                        'action' => 'queue_for_resending',
747
-                        'MSG_ID' => $message->ID()
748
-                    ),
749
-                    admin_url('admin.php')
750
-                ),
751
-            )
752
-        );
753
-        if ($message->TXN_ID() > 0
754
-            && EE_Registry::instance()->CAP->current_user_can(
755
-                'ee_read_transaction',
756
-                'espresso_transactions_default',
757
-                $message->TXN_ID()
758
-            )
759
-        ) {
760
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
761
-                array(
762
-                    'page' => 'espresso_transactions',
763
-                    'action' => 'view_transaction',
764
-                    'TXN_ID' => $message->TXN_ID()
765
-                ),
766
-                admin_url('admin.php')
767
-            );
768
-        } else {
769
-            $action_urls['view_transaction'] = '';
770
-        }
771
-        return $action_urls;
772
-    }
773
-
774
-
775
-    /**
776
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
777
-     *
778
-     * @since 4.9.0
779
-     *
780
-     * @param string $type What type of action the link is for (if invalid type is passed in then an
781
-     *                     empty string is returned)
782
-     * @param EE_Message|null $message  The EE_Message object (required for some actions to generate correctly)
783
-     * @param array           $query_params Any extra query params to include in the generated link.
784
-     *
785
-     * @return string
786
-     */
787
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
788
-    {
789
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
792
-
793
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794
-            return '';
795
-        }
796
-
797
-        $icon_css['css_class'] .= esc_attr(
798
-            apply_filters(
799
-                'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
801
-                $type,
802
-                $message,
803
-                $query_params
804
-            )
805
-        );
806
-
807
-        return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
808
-    }
809
-
810
-
811
-
812
-
813
-
814
-    /**
815
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
816
-     *
817
-     * @since 4.9.0
818
-     * @return array
819
-     */
820
-    public static function reg_status_to_message_type_array()
821
-    {
822
-        return (array) apply_filters(
823
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
824
-            array(
825
-                EEM_Registration::status_id_approved => 'registration',
826
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
827
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
828
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
829
-                EEM_Registration::status_id_declined => 'declined_registration'
830
-            )
831
-        );
832
-    }
833
-
834
-
835
-
836
-
837
-    /**
838
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
839
-     * match, then returns an empty string.
840
-     *
841
-     * @since 4.9.0
842
-     * @param $reg_status
843
-     * @return string
844
-     */
845
-    public static function convert_reg_status_to_message_type($reg_status)
846
-    {
847
-        $reg_status_array = self::reg_status_to_message_type_array();
848
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
849
-    }
850
-
851
-
852
-    /**
853
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
854
-     *
855
-     * @since 4.9.0
856
-     * @return array
857
-     */
858
-    public static function payment_status_to_message_type_array()
859
-    {
860
-        return (array) apply_filters(
861
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
862
-            array(
863
-                EEM_Payment::status_id_approved => 'payment',
864
-                EEM_Payment::status_id_pending => 'payment_pending',
865
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
866
-                EEM_Payment::status_id_declined => 'payment_declined',
867
-                EEM_Payment::status_id_failed => 'payment_failed'
868
-            )
869
-        );
870
-    }
871
-
872
-
873
-
874
-
875
-    /**
876
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
877
-     * an empty string is returned
878
-     *
879
-     * @since 4.9.0
880
-     * @param $payment_status
881
-     * @return string
882
-     */
883
-    public static function convert_payment_status_to_message_type($payment_status)
884
-    {
885
-        $payment_status_array = self::payment_status_to_message_type_array();
886
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
887
-    }
888
-
889
-
890
-    /**
891
-     * This is used to retrieve the template pack for the given name.
892
-     *
893
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
894
-     *
895
-     * @return EE_Messages_Template_Pack
896
-     */
897
-    public static function get_template_pack($template_pack_name)
898
-    {
899
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
900
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901
-        }
902
-
903
-        // first see if in collection already
904
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
905
-
906
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
907
-            return $template_pack;
908
-        }
909
-
910
-        // nope...let's get it.
911
-        // not set yet so let's attempt to get it.
912
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
913
-            ' ',
914
-            '_',
915
-            ucwords(
916
-                str_replace('_', ' ', $template_pack_name)
917
-            )
918
-        );
919
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920
-            return self::get_template_pack('default');
921
-        } else {
922
-            $template_pack = new $pack_class_name;
923
-            self::$_template_pack_collection->add($template_pack);
924
-            return $template_pack;
925
-        }
926
-    }
927
-
928
-
929
-
930
-
931
-    /**
932
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
933
-     * in it.
934
-     *
935
-     * @since 4.9.0
936
-     *
937
-     * @return EE_Messages_Template_Pack_Collection
938
-     */
939
-    public static function get_template_pack_collection()
940
-    {
941
-        $new_collection = false;
942
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944
-            $new_collection = true;
945
-        }
946
-
947
-        // glob the defaults directory for messages
948
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
949
-        foreach ($templates as $template_path) {
950
-            // grab folder name
951
-            $template = basename($template_path);
952
-
953
-            if (! $new_collection) {
954
-                // already have it?
955
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956
-                    continue;
957
-                }
958
-            }
959
-
960
-            // setup classname.
961
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
962
-                ' ',
963
-                '_',
964
-                ucwords(
965
-                    str_replace(
966
-                        '_',
967
-                        ' ',
968
-                        $template
969
-                    )
970
-                )
971
-            );
972
-            if (! class_exists($template_pack_class_name)) {
973
-                continue;
974
-            }
975
-            self::$_template_pack_collection->add(new $template_pack_class_name);
976
-        }
977
-
978
-        /**
979
-         * Filter for plugins to add in any additional template packs
980
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
981
-         */
982
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
983
-        foreach ((array) $additional_template_packs as $template_pack) {
984
-            if (self::$_template_pack_collection->get_by_name(
985
-                $template_pack->dbref
986
-            ) instanceof EE_Messages_Template_Pack
987
-            ) {
988
-                continue;
989
-            }
990
-            self::$_template_pack_collection->add($template_pack);
991
-        }
992
-        return self::$_template_pack_collection;
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * This is a wrapper for the protected _create_new_templates function
999
-     *
1000
-     * @param string $messenger_name
1001
-     * @param string $message_type_name message type that the templates are being created for
1002
-     * @param int    $GRP_ID
1003
-     * @param bool   $global
1004
-     * @return array
1005
-     * @throws \EE_Error
1006
-     */
1007
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1008
-    {
1009
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1010
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014
-            return array();
1015
-        }
1016
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1017
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1018
-    }
1019
-
1020
-
1021
-
1022
-    /**
1023
-     * @param \EE_messenger    $messenger
1024
-     * @param \EE_message_type $message_type
1025
-     * @param                  $GRP_ID
1026
-     * @param                  $global
1027
-     * @return array|mixed
1028
-     */
1029
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030
-    {
1031
-        // if we're creating a custom template then we don't need to use the defaults class
1032
-        if (! $global) {
1033
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034
-        }
1035
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036
-        $Message_Template_Defaults = EE_Registry::factory(
1037
-            'EE_Messages_Template_Defaults',
1038
-            array( $messenger, $message_type, $GRP_ID )
1039
-        );
1040
-        // generate templates
1041
-        $success = $Message_Template_Defaults->create_new_templates();
1042
-
1043
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045
-        // attempts.
1046
-        if (! $success) {
1047
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1048
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1050
-        }
1051
-
1052
-        /**
1053
-         * $success is in an array in the following format
1054
-         * array(
1055
-         *    'GRP_ID' => $new_grp_id,
1056
-         *    'MTP_context' => $first_context_in_new_templates,
1057
-         * )
1058
-         */
1059
-        return $success;
1060
-    }
1061
-
1062
-
1063
-
1064
-    /**
1065
-     * This creates a custom template using the incoming GRP_ID
1066
-     *
1067
-     * @param \EE_messenger    $messenger
1068
-     * @param \EE_message_type $message_type
1069
-     * @param  int             $GRP_ID      GRP_ID for the template_group being used as the base
1070
-     * @return  array $success              This will be an array in the format:
1071
-     *                                      array(
1072
-     *                                          'GRP_ID' => $new_grp_id,
1073
-     *                                          'MTP_context' => $first_context_in_created_template
1074
-     *                                      )
1075
-     * @access private
1076
-     */
1077
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078
-    {
1079
-        // defaults
1080
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1081
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082
-        $Message_Template_Group = empty($GRP_ID)
1083
-            ? EEM_Message_Template_Group::instance()->get_one(
1084
-                array(
1085
-                    array(
1086
-                        'MTP_messenger'    => $messenger->name,
1087
-                        'MTP_message_type' => $message_type->name,
1088
-                        'MTP_is_global'    => true
1089
-                    )
1090
-                )
1091
-            )
1092
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093
-        // if we don't have a mtg at this point then we need to bail.
1094
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095
-            EE_Error::add_error(
1096
-                sprintf(
1097
-                    __(
1098
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1099
-                        'event_espresso'
1100
-                    ),
1101
-                    $GRP_ID
1102
-                ),
1103
-                __FILE__,
1104
-                __FUNCTION__,
1105
-                __LINE__
1106
-            );
1107
-            return $success;
1108
-        }
1109
-        // let's get all the related message_template objects for this group.
1110
-        $message_templates = $Message_Template_Group->message_templates();
1111
-        // now we have what we need to setup the new template
1112
-        $new_mtg = clone $Message_Template_Group;
1113
-        $new_mtg->set('GRP_ID', 0);
1114
-        $new_mtg->set('MTP_is_global', false);
1115
-        $template_name = defined('DOING_AJAX') && ! empty($_POST['templateName'])
1116
-            ? $_POST['templateName']
1117
-            : __(
1118
-                'New Custom Template',
1119
-                'event_espresso'
1120
-            );
1121
-        $template_description = defined("DOING_AJAX") && ! empty($_POST['templateDescription'])
1122
-            ? $_POST['templateDescription']
1123
-            : sprintf(
1124
-                __(
1125
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1126
-                    'event_espresso'
1127
-                ),
1128
-                $new_mtg->messenger_obj()->label['singular'],
1129
-                $new_mtg->message_type_obj()->label['singular']
1130
-            );
1131
-        $new_mtg->set('MTP_name', $template_name);
1132
-        $new_mtg->set('MTP_description', $template_description);
1133
-        // remove ALL relations on this template group so they don't get saved!
1134
-        $new_mtg->_remove_relations('Message_Template');
1135
-        $new_mtg->save();
1136
-        $success['GRP_ID'] = $new_mtg->ID();
1137
-        $success['template_name'] = $template_name;
1138
-        // add new message templates and add relation to.
1139
-        foreach ($message_templates as $message_template) {
1140
-            if (! $message_template instanceof EE_Message_Template) {
1141
-                continue;
1142
-            }
1143
-            $new_message_template = clone $message_template;
1144
-            $new_message_template->set('MTP_ID', 0);
1145
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1146
-            $new_message_template->save();
1147
-            if (empty($success['MTP_context'])) {
1148
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1149
-            }
1150
-        }
1151
-        return $success;
1152
-    }
1153
-
1154
-
1155
-
1156
-    /**
1157
-     * message_type_has_active_templates_for_messenger
1158
-     *
1159
-     * @param \EE_messenger    $messenger
1160
-     * @param \EE_message_type $message_type
1161
-     * @param bool             $global
1162
-     * @return bool
1163
-     */
1164
-    public static function message_type_has_active_templates_for_messenger(
1165
-        EE_messenger $messenger,
1166
-        EE_message_type $message_type,
1167
-        $global = false
1168
-    ) {
1169
-        // is given message_type valid for given messenger (if this is not a global save)
1170
-        if ($global) {
1171
-            return true;
1172
-        }
1173
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1174
-            array(
1175
-                array(
1176
-                    'MTP_is_active'    => true,
1177
-                    'MTP_messenger'    => $messenger->name,
1178
-                    'MTP_message_type' => $message_type->name
1179
-                )
1180
-            )
1181
-        );
1182
-        if ($active_templates > 0) {
1183
-            return true;
1184
-        }
1185
-        EE_Error::add_error(
1186
-            sprintf(
1187
-                __(
1188
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1189
-                    'event_espresso'
1190
-                ),
1191
-                $message_type->name,
1192
-                $messenger->name
1193
-            ),
1194
-            __FILE__,
1195
-            __FUNCTION__,
1196
-            __LINE__
1197
-        );
1198
-        return false;
1199
-    }
1200
-
1201
-
1202
-
1203
-    /**
1204
-     * get_fields
1205
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1206
-     *
1207
-     * @param  string $messenger_name    name of EE_messenger
1208
-     * @param  string $message_type_name name of EE_message_type
1209
-     * @return array
1210
-     */
1211
-    public static function get_fields($messenger_name, $message_type_name)
1212
-    {
1213
-        $template_fields = array();
1214
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1215
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219
-            return array();
1220
-        }
1221
-
1222
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1223
-
1224
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1225
-        foreach ($message_type->get_contexts() as $context => $details) {
1226
-            foreach ($messenger->get_template_fields() as $field => $value) {
1227
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1228
-                    continue;
1229
-                }
1230
-                $template_fields[ $context ][ $field ] = $value;
1231
-            }
1232
-        }
1233
-        if (empty($template_fields)) {
1234
-            EE_Error::add_error(
1235
-                __('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1236
-                __FILE__,
1237
-                __FUNCTION__,
1238
-                __LINE__
1239
-            );
1240
-            return array();
1241
-        }
1242
-        return $template_fields;
1243
-    }
17
+	/**
18
+	 * Holds a collection of EE_Message_Template_Pack objects.
19
+	 * @type EE_Messages_Template_Pack_Collection
20
+	 */
21
+	protected static $_template_pack_collection;
22
+
23
+
24
+
25
+
26
+	private static function _set_autoloader()
27
+	{
28
+		EED_Messages::set_autoloaders();
29
+	}
30
+
31
+
32
+	/**
33
+	 * generate_new_templates
34
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will automatically create the defaults for the event.  The user would then be redirected to edit the default context for the event.
35
+	 *
36
+	 * @access protected
37
+	 * @param  string $messenger     the messenger we are generating templates for
38
+	 * @param array   $message_types array of message types that the templates are generated for.
39
+	 * @param int     $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID to use as the base for the new generated template.
40
+	 * @param bool    $global        true indicates generating templates on messenger activation. false requires GRP_ID for event specific template generation.
41
+	 * @throws \EE_Error
42
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array for templates
43
+	 *                that are generated.  If this is an empty array then it means no templates were generated which usually
44
+	 *                means there was an error.  Anything in the array with an empty value for `MTP_context` means that it
45
+	 *                was not a new generated template but just reactivated (which only happens for global templates that
46
+	 *                already exist in the database.
47
+	 */
48
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
49
+	{
50
+		// make sure message_type is an array.
51
+		$message_types = (array) $message_types;
52
+		$templates = array();
53
+
54
+		if (empty($messenger)) {
55
+			throw new EE_Error(__('We need a messenger to generate templates!', 'event_espresso'));
56
+		}
57
+
58
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
59
+		if (empty($message_types)) {
60
+			throw new EE_Error(__('We need at least one message type to generate templates!', 'event_espresso'));
61
+		}
62
+
63
+		EEH_MSG_Template::_set_autoloader();
64
+		foreach ($message_types as $message_type) {
65
+			// if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
66
+			if ($global && empty($GRP_ID)) {
67
+				$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
68
+					array(
69
+						array(
70
+							'MTP_messenger'    => $messenger,
71
+							'MTP_message_type' => $message_type,
72
+							'MTP_is_global'    => true,
73
+						),
74
+					)
75
+				);
76
+				$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
77
+			}
78
+			// if this is global template generation.
79
+			// First let's determine if we already HAVE global templates for this messenger and message_type combination.
80
+			//  If we do then NO generation!!
81
+			if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
82
+				$templates[] = array(
83
+					'GRP_ID' => $GRP_ID,
84
+					'MTP_context' => '',
85
+				);
86
+				// we already have generated templates for this so let's go to the next message type.
87
+				continue;
88
+			}
89
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90
+
91
+			if (! $new_message_template_group) {
92
+				continue;
93
+			}
94
+			$templates[] = $new_message_template_group;
95
+		}
96
+
97
+		return $templates;
98
+	}
99
+
100
+
101
+	/**
102
+	 * The purpose of this method is to determine if there are already generated templates in the database for the given variables.
103
+	 * @param  string $messenger     messenger
104
+	 * @param  string $message_type message type
105
+	 * @param  int $GRP_ID        GRP ID ( if a custom template) (if not provided then we're just doing global template check)
106
+	 * @return bool                true = generated, false = hasn't been generated.
107
+	 */
108
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
109
+	{
110
+		EEH_MSG_Template::_set_autoloader();
111
+		// what method we use depends on whether we have an GRP_ID or not
112
+		$count = empty($GRP_ID)
113
+			? EEM_Message_Template::instance()->count(
114
+				array(
115
+					array(
116
+						'Message_Template_Group.MTP_messenger'    => $messenger,
117
+						'Message_Template_Group.MTP_message_type' => $message_type,
118
+						'Message_Template_Group.MTP_is_global'    => true
119
+					)
120
+				)
121
+			)
122
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
123
+
124
+		return $count > 0;
125
+	}
126
+
127
+
128
+
129
+
130
+	/**
131
+	 * Updates all message templates matching the incoming messengers and message types to active status.
132
+	 *
133
+	 * @static
134
+	 * @param  array  $messenger_names     Messenger slug
135
+	 * @param  array  $message_type_names  Message type slug
136
+	 * @return  int                         count of updated records.
137
+	 */
138
+	public static function update_to_active($messenger_names, $message_type_names)
139
+	{
140
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
142
+		return EEM_Message_Template_Group::instance()->update(
143
+			array( 'MTP_is_active' => 1 ),
144
+			array(
145
+				array(
146
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
147
+					'MTP_message_type'  => array( 'IN', $message_type_names )
148
+				)
149
+			)
150
+		);
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Updates all message template groups matching the incoming arguments to inactive status.
157
+	 *
158
+	 * @static
159
+	 * @param array $messenger_names    The messenger slugs.
160
+	 *                              If empty then all templates matching the message types are marked inactive.
161
+	 *                              Otherwise only templates matching the messengers and message types.
162
+	 * @param array $message_type_names     The message type slugs.
163
+	 *                              If empty then all templates matching the messengers are marked inactive.
164
+	 *                              Otherwise only templates matching the messengers and message types.
165
+	 *
166
+	 * @return int  count of updated records.
167
+	 */
168
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
169
+	{
170
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
171
+			$messenger_names,
172
+			$message_type_names
173
+		);
174
+	}
175
+
176
+
177
+	/**
178
+	 * The purpose of this function is to return all installed message objects
179
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
180
+	 *
181
+	 * @deprecated 4.9.0
182
+	 * @static
183
+	 * @param string $type
184
+	 * @return array array consisting of installed messenger objects and installed message type objects.
185
+	 */
186
+	public static function get_installed_message_objects($type = 'all')
187
+	{
188
+		self::_set_autoloader();
189
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
190
+		return array(
191
+			'messenger' => $message_resource_manager->installed_messengers(),
192
+			'message_type' => $message_resource_manager->installed_message_types()
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * This will return an array of shortcodes => labels from the
199
+	 * messenger and message_type objects associated with this
200
+	 * template.
201
+	 *
202
+	 * @since 4.3.0
203
+	 *
204
+	 * @param string $message_type
205
+	 * @param string $messenger
206
+	 * @param array  $fields    What fields we're returning valid shortcodes for.
207
+	 *                          If empty then we assume all fields are to be returned. Optional.
208
+	 * @param string $context   What context we're going to return shortcodes for. Optional.
209
+	 * @param bool $merged      If TRUE then we don't return shortcodes indexed by field,
210
+	 *                          but instead an array of the unique shortcodes for all the given ( or all) fields.
211
+	 *                          Optional.
212
+	 * @throws \EE_Error
213
+	 * @return mixed (array|bool) an array of shortcodes in the format
214
+	 *                                              array( '[shortcode] => 'label')
215
+	 *                                              OR
216
+	 *                                              FALSE if no shortcodes found.
217
+	 */
218
+	public static function get_shortcodes(
219
+		$message_type,
220
+		$messenger,
221
+		$fields = array(),
222
+		$context = 'admin',
223
+		$merged = false
224
+	) {
225
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
226
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
227
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
228
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
229
+		// convert slug to object
230
+		$messenger = $message_resource_manager->get_messenger($messenger);
231
+
232
+		// if messenger isn't a EE_messenger resource then bail.
233
+		if (! $messenger instanceof EE_messenger) {
234
+			return array();
235
+		}
236
+
237
+		// validate class for getting our list of shortcodes
238
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
+		if (! class_exists($classname)) {
240
+			$msg[] = __('The Validator class was unable to load', 'event_espresso');
241
+			$msg[] = sprintf(
242
+				__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
243
+				$classname
244
+			);
245
+			throw new EE_Error(implode('||', $msg));
246
+		}
247
+
248
+		/** @type EE_Messages_Validator $_VLD */
249
+		$_VLD = new $classname(array(), $context);
250
+		$valid_shortcodes = $_VLD->get_validators();
251
+
252
+		// let's make sure we're only getting the shortcode part of the validators
253
+		$shortcodes = array();
254
+		foreach ($valid_shortcodes as $field => $validators) {
255
+			$shortcodes[ $field ] = $validators['shortcodes'];
256
+		}
257
+		$valid_shortcodes = $shortcodes;
258
+
259
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
+		if (! empty($fields)) {
261
+			$specified_shortcodes = array();
262
+			foreach ($fields as $field) {
263
+				if (isset($valid_shortcodes[ $field ])) {
264
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
265
+				}
266
+			}
267
+			$valid_shortcodes = $specified_shortcodes;
268
+		}
269
+
270
+		// if not merged then let's replace the fields with the localized fields
271
+		if (! $merged) {
272
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273
+			$field_settings = $messenger->get_template_fields();
274
+			$localized = array();
275
+			foreach ($valid_shortcodes as $field => $shortcodes) {
276
+				// get localized field label
277
+				if (isset($field_settings[ $field ])) {
278
+					// possible that this is used as a main field.
279
+					if (empty($field_settings[ $field ])) {
280
+						if (isset($field_settings['extra'][ $field ])) {
281
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
282
+						} else {
283
+							$_field = $field;
284
+						}
285
+					} else {
286
+						$_field = $field_settings[ $field ]['label'];
287
+					}
288
+				} elseif (isset($field_settings['extra'])) {
289
+					// loop through extra "main fields" and see if any of their children have our field
290
+					foreach ($field_settings['extra'] as $main_field => $fields) {
291
+						if (isset($fields[ $field ])) {
292
+							$_field = $fields[ $field ]['label'];
293
+						} else {
294
+							$_field = $field;
295
+						}
296
+					}
297
+				} else {
298
+					$_field = $field;
299
+				}
300
+				if (isset($_field)) {
301
+					$localized[ (string) $_field ] = $shortcodes;
302
+				}
303
+			}
304
+			$valid_shortcodes = $localized;
305
+		}
306
+
307
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
308
+		if ($merged) {
309
+			$merged_codes = array();
310
+			foreach ($valid_shortcodes as $field => $shortcode) {
311
+				foreach ($shortcode as $code => $label) {
312
+					if (isset($merged_codes[ $code ])) {
313
+						continue;
314
+					} else {
315
+						$merged_codes[ $code ] = $label;
316
+					}
317
+				}
318
+			}
319
+			$valid_shortcodes = $merged_codes;
320
+		}
321
+
322
+		return $valid_shortcodes;
323
+	}
324
+
325
+
326
+	/**
327
+	 * Get Messenger object.
328
+	 *
329
+	 * @since 4.3.0
330
+	 * @deprecated 4.9.0
331
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
332
+	 * @throws \EE_Error
333
+	 * @return EE_messenger
334
+	 */
335
+	public static function messenger_obj($messenger)
336
+	{
337
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
338
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
339
+		return $Message_Resource_Manager->get_messenger($messenger);
340
+	}
341
+
342
+
343
+	/**
344
+	 * get Message type object
345
+	 *
346
+	 * @since 4.3.0
347
+	 * @deprecated 4.9.0
348
+	 * @param string $message_type the slug for the message type object to retrieve
349
+	 * @throws \EE_Error
350
+	 * @return EE_message_type
351
+	 */
352
+	public static function message_type_obj($message_type)
353
+	{
354
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
355
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
356
+		return $Message_Resource_Manager->get_message_type($message_type);
357
+	}
358
+
359
+
360
+
361
+
362
+
363
+	/**
364
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
365
+	 *
366
+	 * @since    4.3.0
367
+	 * @param  string   $message_type message type to check for.
368
+	 * @return boolean
369
+	 */
370
+	public static function is_mt_active($message_type)
371
+	{
372
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
373
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
374
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
375
+		return in_array($message_type, $active_mts);
376
+	}
377
+
378
+
379
+
380
+	/**
381
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
382
+	 *
383
+	 * @since    4.3.0
384
+	 *
385
+	 * @param  string  $messenger slug for messenger to check.
386
+	 * @return boolean
387
+	 */
388
+	public static function is_messenger_active($messenger)
389
+	{
390
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
391
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
392
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
393
+		return $active_messenger instanceof EE_messenger ? true : false;
394
+	}
395
+
396
+
397
+
398
+	/**
399
+	 * Used to return active messengers array stored in the wp options table.
400
+	 * If no value is present in the option then an empty array is returned.
401
+	 *
402
+	 * @deprecated 4.9
403
+	 * @since 4.3.1
404
+	 *
405
+	 * @return array
406
+	 */
407
+	public static function get_active_messengers_in_db()
408
+	{
409
+		EE_Error::doing_it_wrong(
410
+			__METHOD__,
411
+			__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
412
+			'4.9.0'
413
+		);
414
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
415
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
416
+		return $Message_Resource_Manager->get_active_messengers_option();
417
+	}
418
+
419
+
420
+
421
+
422
+	/**
423
+	 * Used to update the active messengers array stored in the wp options table.
424
+	 *
425
+	 * @since 4.3.1
426
+	 * @deprecated 4.9.0
427
+	 *
428
+	 * @param array $data_to_save Incoming data to save.
429
+	 *
430
+	 * @return bool FALSE if not updated, TRUE if updated.
431
+	 */
432
+	public static function update_active_messengers_in_db($data_to_save)
433
+	{
434
+		EE_Error::doing_it_wrong(
435
+			__METHOD__,
436
+			__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
437
+			'4.9.0'
438
+		);
439
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
440
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
441
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
442
+	}
443
+
444
+
445
+	/**
446
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
447
+	 * appropriate url trigger
448
+	 *
449
+	 * @param EE_message_type $message_type
450
+	 * @param EE_Message $message
451
+	 * @param EE_Registration | null $registration  The registration object must be included if this
452
+	 *                                              is going to be a registration trigger url.
453
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
454
+	 *
455
+	 * @return string
456
+	 * @throws EE_Error
457
+	 */
458
+	public static function get_url_trigger(
459
+		EE_message_type $message_type,
460
+		EE_Message $message,
461
+		$registration = null,
462
+		$sending_messenger = ''
463
+	) {
464
+		// first determine if the url can be to the EE_Message object.
465
+		if (! $message_type->always_generate()) {
466
+			return EEH_MSG_Template::generate_browser_trigger($message);
467
+		}
468
+
469
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
470
+		if (! $registration instanceof EE_Registration) {
471
+			throw new EE_Error(
472
+				__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473
+			);
474
+		}
475
+
476
+		// validate given context
477
+		$contexts = $message_type->get_contexts();
478
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
479
+			throw new EE_Error(
480
+				sprintf(
481
+					__('The context %s is not a valid context for %s.', 'event_espresso'),
482
+					$message->context(),
483
+					get_class($message_type)
484
+				)
485
+			);
486
+		}
487
+
488
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
+		if (! empty($sending_messenger)) {
490
+			$with_messengers = $message_type->with_messengers();
491
+			if (! isset($with_messengers[ $message->messenger() ])
492
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])) {
493
+				throw new EE_Error(
494
+					sprintf(
495
+						__(
496
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
497
+							'event_espresso'
498
+						),
499
+						$sending_messenger,
500
+						get_class($message_type)
501
+					)
502
+				);
503
+			}
504
+		} else {
505
+			$sending_messenger = $message->messenger();
506
+		}
507
+		return EEH_MSG_Template::generate_url_trigger(
508
+			$sending_messenger,
509
+			$message->messenger(),
510
+			$message->context(),
511
+			$message->message_type(),
512
+			$registration,
513
+			$message->GRP_ID()
514
+		);
515
+	}
516
+
517
+
518
+	/**
519
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
520
+	 * @param EE_Message $message
521
+	 * @return string.
522
+	 */
523
+	public static function generate_browser_trigger(EE_Message $message)
524
+	{
525
+		$query_args = array(
526
+			'ee' => 'msg_browser_trigger',
527
+			'token' => $message->MSG_token()
528
+		);
529
+		return apply_filters(
530
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
531
+			add_query_arg($query_args, site_url()),
532
+			$message
533
+		);
534
+	}
535
+
536
+
537
+
538
+
539
+
540
+
541
+	/**
542
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
543
+	 * @param EE_Message $message
544
+	 * @return string
545
+	 */
546
+	public static function generate_error_display_trigger(EE_Message $message)
547
+	{
548
+		return apply_filters(
549
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
550
+			add_query_arg(
551
+				array(
552
+					'ee' => 'msg_browser_error_trigger',
553
+					'token' => $message->MSG_token()
554
+				),
555
+				site_url()
556
+			),
557
+			$message
558
+		);
559
+	}
560
+
561
+
562
+
563
+
564
+
565
+
566
+	/**
567
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
568
+	 *
569
+	 * @param string          $sending_messenger    The sending messenger slug.
570
+	 * @param string          $generating_messenger The generating messenger slug.
571
+	 * @param string          $context              The context for the template.
572
+	 * @param string          $message_type         The message type slug
573
+	 * @param EE_Registration $registration
574
+	 * @param integer          $message_template_group id   The EE_Message_Template_Group ID for the template.
575
+	 * @param integer          $data_id     The id to the EE_Base_Class for getting the data used by the trigger.
576
+	 * @return string          The generated url.
577
+	 */
578
+	public static function generate_url_trigger(
579
+		$sending_messenger,
580
+		$generating_messenger,
581
+		$context,
582
+		$message_type,
583
+		EE_Registration $registration,
584
+		$message_template_group,
585
+		$data_id = 0
586
+	) {
587
+		$query_args = array(
588
+			'ee' => 'msg_url_trigger',
589
+			'snd_msgr' => $sending_messenger,
590
+			'gen_msgr' => $generating_messenger,
591
+			'message_type' => $message_type,
592
+			'context' => $context,
593
+			'token' => $registration->reg_url_link(),
594
+			'GRP_ID' => $message_template_group,
595
+			'id' => $data_id
596
+			);
597
+		$url = add_query_arg($query_args, get_home_url());
598
+
599
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
600
+		$url = apply_filters(
601
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
602
+			$url,
603
+			$sending_messenger,
604
+			$generating_messenger,
605
+			$context,
606
+			$message_type,
607
+			$registration,
608
+			$message_template_group,
609
+			$data_id
610
+		);
611
+		return $url;
612
+	}
613
+
614
+
615
+
616
+
617
+	/**
618
+	 * Return the specific css for the action icon given.
619
+	 *
620
+	 * @since 4.9.0
621
+	 *
622
+	 * @param string $type  What action to return.
623
+	 * @return string
624
+	 */
625
+	public static function get_message_action_icon($type)
626
+	{
627
+		$action_icons = self::get_message_action_icons();
628
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
629
+	}
630
+
631
+
632
+	/**
633
+	 * This is used for retrieving the css classes used for the icons representing message actions.
634
+	 *
635
+	 * @since 4.9.0
636
+	 *
637
+	 * @return array
638
+	 */
639
+	public static function get_message_action_icons()
640
+	{
641
+		return apply_filters(
642
+			'FHEE__EEH_MSG_Template__message_action_icons',
643
+			array(
644
+				'view' => array(
645
+					'label' => __('View Message', 'event_espresso'),
646
+					'css_class' => 'dashicons dashicons-welcome-view-site',
647
+				),
648
+				'error' => array(
649
+					'label' => __('View Error Message', 'event_espresso'),
650
+					'css_class' => 'dashicons dashicons-info',
651
+				),
652
+				'see_notifications_for' => array(
653
+					'label' => __('View Related Messages', 'event_espresso'),
654
+					'css_class' => 'dashicons dashicons-megaphone',
655
+				),
656
+				'generate_now' => array(
657
+					'label' => __('Generate the message now.', 'event_espresso'),
658
+					'css_class' => 'dashicons dashicons-admin-tools',
659
+				),
660
+				'send_now' => array(
661
+					'label' => __('Send Immediately', 'event_espresso'),
662
+					'css_class' => 'dashicons dashicons-controls-forward',
663
+				),
664
+				'queue_for_resending' => array(
665
+					'label' => __('Queue for Resending', 'event_espresso'),
666
+					'css_class' => 'dashicons dashicons-controls-repeat',
667
+				),
668
+				'view_transaction' => array(
669
+					'label' => __('View related Transaction', 'event_espresso'),
670
+					'css_class' => 'dashicons dashicons-cart',
671
+				)
672
+			)
673
+		);
674
+	}
675
+
676
+
677
+	/**
678
+	 * This returns the url for a given action related to EE_Message.
679
+	 *
680
+	 * @since 4.9.0
681
+	 *
682
+	 * @param string $type  What type of action to return the url for.
683
+	 * @param EE_Message $message   Required for generating the correct url for some types.
684
+	 * @param array  $query_params   Any additional query params to be included with the generated url.
685
+	 *
686
+	 * @return string
687
+	 */
688
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689
+	{
690
+		$action_urls = self::get_message_action_urls($message, $query_params);
691
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
692
+	}
693
+
694
+
695
+
696
+	/**
697
+	 * This returns all the current urls for EE_Message actions.
698
+	 *
699
+	 * @since 4.9.0
700
+	 *
701
+	 * @param  EE_Message   $message    The EE_Message object required to generate correct urls for some types.
702
+	 * @param  array    $query_params   Any additional query_params to be included with the generated url.
703
+	 *
704
+	 * @return array
705
+	 */
706
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
707
+	{
708
+		EE_Registry::instance()->load_helper('URL');
709
+		// if $message is not an instance of EE_Message then let's just do a dummy.
710
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
711
+		$action_urls =  apply_filters(
712
+			'FHEE__EEH_MSG_Template__get_message_action_url',
713
+			array(
714
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
715
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
716
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
717
+					array_merge(
718
+						array(
719
+							'page' => 'espresso_messages',
720
+							'action' => 'default',
721
+							'filterby' => 1,
722
+						),
723
+						$query_params
724
+					),
725
+					admin_url('admin.php')
726
+				),
727
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
728
+					array(
729
+						'page' => 'espresso_messages',
730
+						'action' => 'generate_now',
731
+						'MSG_ID' => $message->ID()
732
+					),
733
+					admin_url('admin.php')
734
+				),
735
+				'send_now' => EEH_URL::add_query_args_and_nonce(
736
+					array(
737
+						'page' => 'espresso_messages',
738
+						'action' => 'send_now',
739
+						'MSG_ID' => $message->ID()
740
+					),
741
+					admin_url('admin.php')
742
+				),
743
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
744
+					array(
745
+						'page' => 'espresso_messages',
746
+						'action' => 'queue_for_resending',
747
+						'MSG_ID' => $message->ID()
748
+					),
749
+					admin_url('admin.php')
750
+				),
751
+			)
752
+		);
753
+		if ($message->TXN_ID() > 0
754
+			&& EE_Registry::instance()->CAP->current_user_can(
755
+				'ee_read_transaction',
756
+				'espresso_transactions_default',
757
+				$message->TXN_ID()
758
+			)
759
+		) {
760
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
761
+				array(
762
+					'page' => 'espresso_transactions',
763
+					'action' => 'view_transaction',
764
+					'TXN_ID' => $message->TXN_ID()
765
+				),
766
+				admin_url('admin.php')
767
+			);
768
+		} else {
769
+			$action_urls['view_transaction'] = '';
770
+		}
771
+		return $action_urls;
772
+	}
773
+
774
+
775
+	/**
776
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
777
+	 *
778
+	 * @since 4.9.0
779
+	 *
780
+	 * @param string $type What type of action the link is for (if invalid type is passed in then an
781
+	 *                     empty string is returned)
782
+	 * @param EE_Message|null $message  The EE_Message object (required for some actions to generate correctly)
783
+	 * @param array           $query_params Any extra query params to include in the generated link.
784
+	 *
785
+	 * @return string
786
+	 */
787
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
788
+	{
789
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
+		$title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
792
+
793
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794
+			return '';
795
+		}
796
+
797
+		$icon_css['css_class'] .= esc_attr(
798
+			apply_filters(
799
+				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
+				' js-ee-message-action-link ee-message-action-link-' . $type,
801
+				$type,
802
+				$message,
803
+				$query_params
804
+			)
805
+		);
806
+
807
+		return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
808
+	}
809
+
810
+
811
+
812
+
813
+
814
+	/**
815
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
816
+	 *
817
+	 * @since 4.9.0
818
+	 * @return array
819
+	 */
820
+	public static function reg_status_to_message_type_array()
821
+	{
822
+		return (array) apply_filters(
823
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
824
+			array(
825
+				EEM_Registration::status_id_approved => 'registration',
826
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
827
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
828
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
829
+				EEM_Registration::status_id_declined => 'declined_registration'
830
+			)
831
+		);
832
+	}
833
+
834
+
835
+
836
+
837
+	/**
838
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
839
+	 * match, then returns an empty string.
840
+	 *
841
+	 * @since 4.9.0
842
+	 * @param $reg_status
843
+	 * @return string
844
+	 */
845
+	public static function convert_reg_status_to_message_type($reg_status)
846
+	{
847
+		$reg_status_array = self::reg_status_to_message_type_array();
848
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
849
+	}
850
+
851
+
852
+	/**
853
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
854
+	 *
855
+	 * @since 4.9.0
856
+	 * @return array
857
+	 */
858
+	public static function payment_status_to_message_type_array()
859
+	{
860
+		return (array) apply_filters(
861
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
862
+			array(
863
+				EEM_Payment::status_id_approved => 'payment',
864
+				EEM_Payment::status_id_pending => 'payment_pending',
865
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
866
+				EEM_Payment::status_id_declined => 'payment_declined',
867
+				EEM_Payment::status_id_failed => 'payment_failed'
868
+			)
869
+		);
870
+	}
871
+
872
+
873
+
874
+
875
+	/**
876
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
877
+	 * an empty string is returned
878
+	 *
879
+	 * @since 4.9.0
880
+	 * @param $payment_status
881
+	 * @return string
882
+	 */
883
+	public static function convert_payment_status_to_message_type($payment_status)
884
+	{
885
+		$payment_status_array = self::payment_status_to_message_type_array();
886
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
887
+	}
888
+
889
+
890
+	/**
891
+	 * This is used to retrieve the template pack for the given name.
892
+	 *
893
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
894
+	 *
895
+	 * @return EE_Messages_Template_Pack
896
+	 */
897
+	public static function get_template_pack($template_pack_name)
898
+	{
899
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
900
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901
+		}
902
+
903
+		// first see if in collection already
904
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
905
+
906
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
907
+			return $template_pack;
908
+		}
909
+
910
+		// nope...let's get it.
911
+		// not set yet so let's attempt to get it.
912
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
913
+			' ',
914
+			'_',
915
+			ucwords(
916
+				str_replace('_', ' ', $template_pack_name)
917
+			)
918
+		);
919
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920
+			return self::get_template_pack('default');
921
+		} else {
922
+			$template_pack = new $pack_class_name;
923
+			self::$_template_pack_collection->add($template_pack);
924
+			return $template_pack;
925
+		}
926
+	}
927
+
928
+
929
+
930
+
931
+	/**
932
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
933
+	 * in it.
934
+	 *
935
+	 * @since 4.9.0
936
+	 *
937
+	 * @return EE_Messages_Template_Pack_Collection
938
+	 */
939
+	public static function get_template_pack_collection()
940
+	{
941
+		$new_collection = false;
942
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944
+			$new_collection = true;
945
+		}
946
+
947
+		// glob the defaults directory for messages
948
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
949
+		foreach ($templates as $template_path) {
950
+			// grab folder name
951
+			$template = basename($template_path);
952
+
953
+			if (! $new_collection) {
954
+				// already have it?
955
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956
+					continue;
957
+				}
958
+			}
959
+
960
+			// setup classname.
961
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
962
+				' ',
963
+				'_',
964
+				ucwords(
965
+					str_replace(
966
+						'_',
967
+						' ',
968
+						$template
969
+					)
970
+				)
971
+			);
972
+			if (! class_exists($template_pack_class_name)) {
973
+				continue;
974
+			}
975
+			self::$_template_pack_collection->add(new $template_pack_class_name);
976
+		}
977
+
978
+		/**
979
+		 * Filter for plugins to add in any additional template packs
980
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
981
+		 */
982
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
983
+		foreach ((array) $additional_template_packs as $template_pack) {
984
+			if (self::$_template_pack_collection->get_by_name(
985
+				$template_pack->dbref
986
+			) instanceof EE_Messages_Template_Pack
987
+			) {
988
+				continue;
989
+			}
990
+			self::$_template_pack_collection->add($template_pack);
991
+		}
992
+		return self::$_template_pack_collection;
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * This is a wrapper for the protected _create_new_templates function
999
+	 *
1000
+	 * @param string $messenger_name
1001
+	 * @param string $message_type_name message type that the templates are being created for
1002
+	 * @param int    $GRP_ID
1003
+	 * @param bool   $global
1004
+	 * @return array
1005
+	 * @throws \EE_Error
1006
+	 */
1007
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1008
+	{
1009
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1010
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014
+			return array();
1015
+		}
1016
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1017
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1018
+	}
1019
+
1020
+
1021
+
1022
+	/**
1023
+	 * @param \EE_messenger    $messenger
1024
+	 * @param \EE_message_type $message_type
1025
+	 * @param                  $GRP_ID
1026
+	 * @param                  $global
1027
+	 * @return array|mixed
1028
+	 */
1029
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030
+	{
1031
+		// if we're creating a custom template then we don't need to use the defaults class
1032
+		if (! $global) {
1033
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034
+		}
1035
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036
+		$Message_Template_Defaults = EE_Registry::factory(
1037
+			'EE_Messages_Template_Defaults',
1038
+			array( $messenger, $message_type, $GRP_ID )
1039
+		);
1040
+		// generate templates
1041
+		$success = $Message_Template_Defaults->create_new_templates();
1042
+
1043
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045
+		// attempts.
1046
+		if (! $success) {
1047
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1048
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1050
+		}
1051
+
1052
+		/**
1053
+		 * $success is in an array in the following format
1054
+		 * array(
1055
+		 *    'GRP_ID' => $new_grp_id,
1056
+		 *    'MTP_context' => $first_context_in_new_templates,
1057
+		 * )
1058
+		 */
1059
+		return $success;
1060
+	}
1061
+
1062
+
1063
+
1064
+	/**
1065
+	 * This creates a custom template using the incoming GRP_ID
1066
+	 *
1067
+	 * @param \EE_messenger    $messenger
1068
+	 * @param \EE_message_type $message_type
1069
+	 * @param  int             $GRP_ID      GRP_ID for the template_group being used as the base
1070
+	 * @return  array $success              This will be an array in the format:
1071
+	 *                                      array(
1072
+	 *                                          'GRP_ID' => $new_grp_id,
1073
+	 *                                          'MTP_context' => $first_context_in_created_template
1074
+	 *                                      )
1075
+	 * @access private
1076
+	 */
1077
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078
+	{
1079
+		// defaults
1080
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1081
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082
+		$Message_Template_Group = empty($GRP_ID)
1083
+			? EEM_Message_Template_Group::instance()->get_one(
1084
+				array(
1085
+					array(
1086
+						'MTP_messenger'    => $messenger->name,
1087
+						'MTP_message_type' => $message_type->name,
1088
+						'MTP_is_global'    => true
1089
+					)
1090
+				)
1091
+			)
1092
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093
+		// if we don't have a mtg at this point then we need to bail.
1094
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095
+			EE_Error::add_error(
1096
+				sprintf(
1097
+					__(
1098
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1099
+						'event_espresso'
1100
+					),
1101
+					$GRP_ID
1102
+				),
1103
+				__FILE__,
1104
+				__FUNCTION__,
1105
+				__LINE__
1106
+			);
1107
+			return $success;
1108
+		}
1109
+		// let's get all the related message_template objects for this group.
1110
+		$message_templates = $Message_Template_Group->message_templates();
1111
+		// now we have what we need to setup the new template
1112
+		$new_mtg = clone $Message_Template_Group;
1113
+		$new_mtg->set('GRP_ID', 0);
1114
+		$new_mtg->set('MTP_is_global', false);
1115
+		$template_name = defined('DOING_AJAX') && ! empty($_POST['templateName'])
1116
+			? $_POST['templateName']
1117
+			: __(
1118
+				'New Custom Template',
1119
+				'event_espresso'
1120
+			);
1121
+		$template_description = defined("DOING_AJAX") && ! empty($_POST['templateDescription'])
1122
+			? $_POST['templateDescription']
1123
+			: sprintf(
1124
+				__(
1125
+					'This is a custom template that was created for the %s messenger and %s message type.',
1126
+					'event_espresso'
1127
+				),
1128
+				$new_mtg->messenger_obj()->label['singular'],
1129
+				$new_mtg->message_type_obj()->label['singular']
1130
+			);
1131
+		$new_mtg->set('MTP_name', $template_name);
1132
+		$new_mtg->set('MTP_description', $template_description);
1133
+		// remove ALL relations on this template group so they don't get saved!
1134
+		$new_mtg->_remove_relations('Message_Template');
1135
+		$new_mtg->save();
1136
+		$success['GRP_ID'] = $new_mtg->ID();
1137
+		$success['template_name'] = $template_name;
1138
+		// add new message templates and add relation to.
1139
+		foreach ($message_templates as $message_template) {
1140
+			if (! $message_template instanceof EE_Message_Template) {
1141
+				continue;
1142
+			}
1143
+			$new_message_template = clone $message_template;
1144
+			$new_message_template->set('MTP_ID', 0);
1145
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1146
+			$new_message_template->save();
1147
+			if (empty($success['MTP_context'])) {
1148
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1149
+			}
1150
+		}
1151
+		return $success;
1152
+	}
1153
+
1154
+
1155
+
1156
+	/**
1157
+	 * message_type_has_active_templates_for_messenger
1158
+	 *
1159
+	 * @param \EE_messenger    $messenger
1160
+	 * @param \EE_message_type $message_type
1161
+	 * @param bool             $global
1162
+	 * @return bool
1163
+	 */
1164
+	public static function message_type_has_active_templates_for_messenger(
1165
+		EE_messenger $messenger,
1166
+		EE_message_type $message_type,
1167
+		$global = false
1168
+	) {
1169
+		// is given message_type valid for given messenger (if this is not a global save)
1170
+		if ($global) {
1171
+			return true;
1172
+		}
1173
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1174
+			array(
1175
+				array(
1176
+					'MTP_is_active'    => true,
1177
+					'MTP_messenger'    => $messenger->name,
1178
+					'MTP_message_type' => $message_type->name
1179
+				)
1180
+			)
1181
+		);
1182
+		if ($active_templates > 0) {
1183
+			return true;
1184
+		}
1185
+		EE_Error::add_error(
1186
+			sprintf(
1187
+				__(
1188
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1189
+					'event_espresso'
1190
+				),
1191
+				$message_type->name,
1192
+				$messenger->name
1193
+			),
1194
+			__FILE__,
1195
+			__FUNCTION__,
1196
+			__LINE__
1197
+		);
1198
+		return false;
1199
+	}
1200
+
1201
+
1202
+
1203
+	/**
1204
+	 * get_fields
1205
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1206
+	 *
1207
+	 * @param  string $messenger_name    name of EE_messenger
1208
+	 * @param  string $message_type_name name of EE_message_type
1209
+	 * @return array
1210
+	 */
1211
+	public static function get_fields($messenger_name, $message_type_name)
1212
+	{
1213
+		$template_fields = array();
1214
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1215
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219
+			return array();
1220
+		}
1221
+
1222
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1223
+
1224
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1225
+		foreach ($message_type->get_contexts() as $context => $details) {
1226
+			foreach ($messenger->get_template_fields() as $field => $value) {
1227
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1228
+					continue;
1229
+				}
1230
+				$template_fields[ $context ][ $field ] = $value;
1231
+			}
1232
+		}
1233
+		if (empty($template_fields)) {
1234
+			EE_Error::add_error(
1235
+				__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1236
+				__FILE__,
1237
+				__FUNCTION__,
1238
+				__LINE__
1239
+			);
1240
+			return array();
1241
+		}
1242
+		return $template_fields;
1243
+	}
1244 1244
 }
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
             }
89 89
             $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90 90
 
91
-            if (! $new_message_template_group) {
91
+            if ( ! $new_message_template_group) {
92 92
                 continue;
93 93
             }
94 94
             $templates[] = $new_message_template_group;
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
                     )
120 120
                 )
121 121
             )
122
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
122
+            : EEM_Message_Template::instance()->count(array(array('GRP_ID' => $GRP_ID)));
123 123
 
124 124
         return $count > 0;
125 125
     }
@@ -137,14 +137,14 @@  discard block
 block discarded – undo
137 137
      */
138 138
     public static function update_to_active($messenger_names, $message_type_names)
139 139
     {
140
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
140
+        $messenger_names = is_array($messenger_names) ? $messenger_names : array($messenger_names);
141
+        $message_type_names = is_array($message_type_names) ? $message_type_names : array($message_type_names);
142 142
         return EEM_Message_Template_Group::instance()->update(
143
-            array( 'MTP_is_active' => 1 ),
143
+            array('MTP_is_active' => 1),
144 144
             array(
145 145
                 array(
146
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
147
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
146
+                    'MTP_messenger'     => array('IN', $messenger_names),
147
+                    'MTP_message_type'  => array('IN', $message_type_names)
148 148
                 )
149 149
             )
150 150
         );
@@ -230,13 +230,13 @@  discard block
 block discarded – undo
230 230
         $messenger = $message_resource_manager->get_messenger($messenger);
231 231
 
232 232
         // if messenger isn't a EE_messenger resource then bail.
233
-        if (! $messenger instanceof EE_messenger) {
233
+        if ( ! $messenger instanceof EE_messenger) {
234 234
             return array();
235 235
         }
236 236
 
237 237
         // validate class for getting our list of shortcodes
238
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
-        if (! class_exists($classname)) {
238
+        $classname = 'EE_Messages_'.$messenger_name.'_'.$mt_name.'_Validator';
239
+        if ( ! class_exists($classname)) {
240 240
             $msg[] = __('The Validator class was unable to load', 'event_espresso');
241 241
             $msg[] = sprintf(
242 242
                 __('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
@@ -252,44 +252,44 @@  discard block
 block discarded – undo
252 252
         // let's make sure we're only getting the shortcode part of the validators
253 253
         $shortcodes = array();
254 254
         foreach ($valid_shortcodes as $field => $validators) {
255
-            $shortcodes[ $field ] = $validators['shortcodes'];
255
+            $shortcodes[$field] = $validators['shortcodes'];
256 256
         }
257 257
         $valid_shortcodes = $shortcodes;
258 258
 
259 259
         // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
-        if (! empty($fields)) {
260
+        if ( ! empty($fields)) {
261 261
             $specified_shortcodes = array();
262 262
             foreach ($fields as $field) {
263
-                if (isset($valid_shortcodes[ $field ])) {
264
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
263
+                if (isset($valid_shortcodes[$field])) {
264
+                    $specified_shortcodes[$field] = $valid_shortcodes[$field];
265 265
                 }
266 266
             }
267 267
             $valid_shortcodes = $specified_shortcodes;
268 268
         }
269 269
 
270 270
         // if not merged then let's replace the fields with the localized fields
271
-        if (! $merged) {
271
+        if ( ! $merged) {
272 272
             // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273 273
             $field_settings = $messenger->get_template_fields();
274 274
             $localized = array();
275 275
             foreach ($valid_shortcodes as $field => $shortcodes) {
276 276
                 // get localized field label
277
-                if (isset($field_settings[ $field ])) {
277
+                if (isset($field_settings[$field])) {
278 278
                     // possible that this is used as a main field.
279
-                    if (empty($field_settings[ $field ])) {
280
-                        if (isset($field_settings['extra'][ $field ])) {
281
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
279
+                    if (empty($field_settings[$field])) {
280
+                        if (isset($field_settings['extra'][$field])) {
281
+                            $_field = $field_settings['extra'][$field]['main']['label'];
282 282
                         } else {
283 283
                             $_field = $field;
284 284
                         }
285 285
                     } else {
286
-                        $_field = $field_settings[ $field ]['label'];
286
+                        $_field = $field_settings[$field]['label'];
287 287
                     }
288 288
                 } elseif (isset($field_settings['extra'])) {
289 289
                     // loop through extra "main fields" and see if any of their children have our field
290 290
                     foreach ($field_settings['extra'] as $main_field => $fields) {
291
-                        if (isset($fields[ $field ])) {
292
-                            $_field = $fields[ $field ]['label'];
291
+                        if (isset($fields[$field])) {
292
+                            $_field = $fields[$field]['label'];
293 293
                         } else {
294 294
                             $_field = $field;
295 295
                         }
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
                     $_field = $field;
299 299
                 }
300 300
                 if (isset($_field)) {
301
-                    $localized[ (string) $_field ] = $shortcodes;
301
+                    $localized[(string) $_field] = $shortcodes;
302 302
                 }
303 303
             }
304 304
             $valid_shortcodes = $localized;
@@ -309,10 +309,10 @@  discard block
 block discarded – undo
309 309
             $merged_codes = array();
310 310
             foreach ($valid_shortcodes as $field => $shortcode) {
311 311
                 foreach ($shortcode as $code => $label) {
312
-                    if (isset($merged_codes[ $code ])) {
312
+                    if (isset($merged_codes[$code])) {
313 313
                         continue;
314 314
                     } else {
315
-                        $merged_codes[ $code ] = $label;
315
+                        $merged_codes[$code] = $label;
316 316
                     }
317 317
                 }
318 318
             }
@@ -462,12 +462,12 @@  discard block
 block discarded – undo
462 462
         $sending_messenger = ''
463 463
     ) {
464 464
         // first determine if the url can be to the EE_Message object.
465
-        if (! $message_type->always_generate()) {
465
+        if ( ! $message_type->always_generate()) {
466 466
             return EEH_MSG_Template::generate_browser_trigger($message);
467 467
         }
468 468
 
469 469
         // if $registration object is not valid then exit early because there's nothing that can be generated.
470
-        if (! $registration instanceof EE_Registration) {
470
+        if ( ! $registration instanceof EE_Registration) {
471 471
             throw new EE_Error(
472 472
                 __('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473 473
             );
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 
476 476
         // validate given context
477 477
         $contexts = $message_type->get_contexts();
478
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
478
+        if ($message->context() !== '' && ! isset($contexts[$message->context()])) {
479 479
             throw new EE_Error(
480 480
                 sprintf(
481 481
                     __('The context %s is not a valid context for %s.', 'event_espresso'),
@@ -486,10 +486,10 @@  discard block
 block discarded – undo
486 486
         }
487 487
 
488 488
         // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
-        if (! empty($sending_messenger)) {
489
+        if ( ! empty($sending_messenger)) {
490 490
             $with_messengers = $message_type->with_messengers();
491
-            if (! isset($with_messengers[ $message->messenger() ])
492
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])) {
491
+            if ( ! isset($with_messengers[$message->messenger()])
492
+                 || ! in_array($sending_messenger, $with_messengers[$message->messenger()])) {
493 493
                 throw new EE_Error(
494 494
                     sprintf(
495 495
                         __(
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
     public static function get_message_action_icon($type)
626 626
     {
627 627
         $action_icons = self::get_message_action_icons();
628
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
628
+        return isset($action_icons[$type]) ? $action_icons[$type] : '';
629 629
     }
630 630
 
631 631
 
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
     public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689 689
     {
690 690
         $action_urls = self::get_message_action_urls($message, $query_params);
691
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
691
+        return isset($action_urls[$type]) ? $action_urls[$type] : '';
692 692
     }
693 693
 
694 694
 
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
         EE_Registry::instance()->load_helper('URL');
709 709
         // if $message is not an instance of EE_Message then let's just do a dummy.
710 710
         $message = empty($message) ? EE_Message_Factory::create() : $message;
711
-        $action_urls =  apply_filters(
711
+        $action_urls = apply_filters(
712 712
             'FHEE__EEH_MSG_Template__get_message_action_url',
713 713
             array(
714 714
                 'view' => EEH_MSG_Template::generate_browser_trigger($message),
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     {
789 789
         $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790 790
         $icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
791
+        $title = isset($icon_css['label']) ? 'title="'.$icon_css['label'].'"' : '';
792 792
 
793 793
         if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794 794
             return '';
@@ -797,14 +797,14 @@  discard block
 block discarded – undo
797 797
         $icon_css['css_class'] .= esc_attr(
798 798
             apply_filters(
799 799
                 'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
800
+                ' js-ee-message-action-link ee-message-action-link-'.$type,
801 801
                 $type,
802 802
                 $message,
803 803
                 $query_params
804 804
             )
805 805
         );
806 806
 
807
-        return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
807
+        return '<a href="'.$url.'"'.$title.'><span class="'.esc_attr($icon_css['css_class']).'"></span></a>';
808 808
     }
809 809
 
810 810
 
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
     public static function convert_reg_status_to_message_type($reg_status)
846 846
     {
847 847
         $reg_status_array = self::reg_status_to_message_type_array();
848
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
848
+        return isset($reg_status_array[$reg_status]) ? $reg_status_array[$reg_status] : '';
849 849
     }
850 850
 
851 851
 
@@ -883,7 +883,7 @@  discard block
 block discarded – undo
883 883
     public static function convert_payment_status_to_message_type($payment_status)
884 884
     {
885 885
         $payment_status_array = self::payment_status_to_message_type_array();
886
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
886
+        return isset($payment_status_array[$payment_status]) ? $payment_status_array[$payment_status] : '';
887 887
     }
888 888
 
889 889
 
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
      */
897 897
     public static function get_template_pack($template_pack_name)
898 898
     {
899
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
899
+        if ( ! self::$_template_pack_collection instanceof EE_Object_Collection) {
900 900
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901 901
         }
902 902
 
@@ -909,14 +909,14 @@  discard block
 block discarded – undo
909 909
 
910 910
         // nope...let's get it.
911 911
         // not set yet so let's attempt to get it.
912
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
912
+        $pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
913 913
             ' ',
914 914
             '_',
915 915
             ucwords(
916 916
                 str_replace('_', ' ', $template_pack_name)
917 917
             )
918 918
         );
919
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
919
+        if ( ! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920 920
             return self::get_template_pack('default');
921 921
         } else {
922 922
             $template_pack = new $pack_class_name;
@@ -939,18 +939,18 @@  discard block
 block discarded – undo
939 939
     public static function get_template_pack_collection()
940 940
     {
941 941
         $new_collection = false;
942
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
942
+        if ( ! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943 943
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944 944
             $new_collection = true;
945 945
         }
946 946
 
947 947
         // glob the defaults directory for messages
948
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
948
+        $templates = glob(EE_LIBRARIES.'messages/defaults/*', GLOB_ONLYDIR);
949 949
         foreach ($templates as $template_path) {
950 950
             // grab folder name
951 951
             $template = basename($template_path);
952 952
 
953
-            if (! $new_collection) {
953
+            if ( ! $new_collection) {
954 954
                 // already have it?
955 955
                 if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956 956
                     continue;
@@ -958,7 +958,7 @@  discard block
 block discarded – undo
958 958
             }
959 959
 
960 960
             // setup classname.
961
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
961
+            $template_pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
962 962
                 ' ',
963 963
                 '_',
964 964
                 ucwords(
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
                     )
970 970
                 )
971 971
             );
972
-            if (! class_exists($template_pack_class_name)) {
972
+            if ( ! class_exists($template_pack_class_name)) {
973 973
                 continue;
974 974
             }
975 975
             self::$_template_pack_collection->add(new $template_pack_class_name);
@@ -1010,7 +1010,7 @@  discard block
 block discarded – undo
1010 1010
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011 1011
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012 1012
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1013
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014 1014
             return array();
1015 1015
         }
1016 1016
         // whew made it this far!  Okay, let's go ahead and create the templates then
@@ -1029,13 +1029,13 @@  discard block
 block discarded – undo
1029 1029
     protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030 1030
     {
1031 1031
         // if we're creating a custom template then we don't need to use the defaults class
1032
-        if (! $global) {
1032
+        if ( ! $global) {
1033 1033
             return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034 1034
         }
1035 1035
         /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036 1036
         $Message_Template_Defaults = EE_Registry::factory(
1037 1037
             'EE_Messages_Template_Defaults',
1038
-            array( $messenger, $message_type, $GRP_ID )
1038
+            array($messenger, $message_type, $GRP_ID)
1039 1039
         );
1040 1040
         // generate templates
1041 1041
         $success = $Message_Template_Defaults->create_new_templates();
@@ -1043,7 +1043,7 @@  discard block
 block discarded – undo
1043 1043
         // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044 1044
         // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045 1045
         // attempts.
1046
-        if (! $success) {
1046
+        if ( ! $success) {
1047 1047
             /** @var EE_Message_Resource_Manager $message_resource_manager */
1048 1048
             $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049 1049
             $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
     private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078 1078
     {
1079 1079
         // defaults
1080
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1080
+        $success = array('GRP_ID' => null, 'MTP_context' => '');
1081 1081
         // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082 1082
         $Message_Template_Group = empty($GRP_ID)
1083 1083
             ? EEM_Message_Template_Group::instance()->get_one(
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
             )
1092 1092
             : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093 1093
         // if we don't have a mtg at this point then we need to bail.
1094
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1094
+        if ( ! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095 1095
             EE_Error::add_error(
1096 1096
                 sprintf(
1097 1097
                     __(
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
         $success['template_name'] = $template_name;
1138 1138
         // add new message templates and add relation to.
1139 1139
         foreach ($message_templates as $message_template) {
1140
-            if (! $message_template instanceof EE_Message_Template) {
1140
+            if ( ! $message_template instanceof EE_Message_Template) {
1141 1141
                 continue;
1142 1142
             }
1143 1143
             $new_message_template = clone $message_template;
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216 1216
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217 1217
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1218
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219 1219
             return array();
1220 1220
         }
1221 1221
 
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
                 if (in_array($field, $excluded_fields_for_messenger, true)) {
1228 1228
                     continue;
1229 1229
                 }
1230
-                $template_fields[ $context ][ $field ] = $value;
1230
+                $template_fields[$context][$field] = $value;
1231 1231
             }
1232 1232
         }
1233 1233
         if (empty($template_fields)) {
Please login to merge, or discard this patch.
core/helpers/EEH_Event_View.helper.php 2 patches
Indentation   +569 added lines, -569 removed lines patch added patch discarded remove patch
@@ -11,578 +11,578 @@
 block discarded – undo
11 11
 class EEH_Event_View extends EEH_Base
12 12
 {
13 13
 
14
-    /**
15
-     * @var EE_Event $_event
16
-     */
17
-    private static $_event = null;
18
-
19
-
20
-
21
-    /**
22
-     * get_event
23
-     * attempts to retrieve an EE_Event object any way it can
24
-     *
25
-     * @param int|WP_Post $EVT_ID
26
-     * @return EE_Event|null
27
-     * @throws \EE_Error
28
-     */
29
-    public static function get_event($EVT_ID = 0)
30
-    {
31
-        // international newspaper?
32
-        global $post;
33
-        $EVT_ID = $EVT_ID instanceof WP_Post && $EVT_ID->post_type === 'espresso_events'
34
-            ? $EVT_ID->ID
35
-            : absint($EVT_ID);
36
-        // do we already have the Event  you are looking for?
37
-        if (EEH_Event_View::$_event instanceof EE_Event && $EVT_ID && EEH_Event_View::$_event->ID() === $EVT_ID) {
38
-            return EEH_Event_View::$_event;
39
-        }
40
-        // reset property so that the new event is cached.
41
-        EEH_Event_View::$_event = null;
42
-        if (! $EVT_ID && $post instanceof EE_Event) {
43
-            EEH_Event_View::$_event = $post;
44
-            return EEH_Event_View::$_event;
45
-        }
46
-        // if the post type is for an event and it has a cached event and we don't have a different incoming $EVT_ID
47
-        // then let's just use that cached event on the $post object.
48
-        if ($post instanceof WP_Post
49
-            && $post->post_type === 'espresso_events'
50
-            && isset($post->EE_Event)
51
-            && (
52
-                $EVT_ID === 0
53
-                || $EVT_ID === $post->ID
54
-            )
55
-        ) {
56
-            EEH_Event_View::$_event = $post->EE_Event;
57
-            return EEH_Event_View::$_event;
58
-        }
59
-        // If the event we have isn't an event but we do have an EVT_ID, let's try getting the event using the ID.
60
-        if (! EEH_Event_View::$_event instanceof EE_Event && $EVT_ID) {
61
-            EEH_Event_View::$_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
62
-        }
63
-        return EEH_Event_View::$_event;
64
-    }
65
-
66
-
67
-
68
-    /**
69
-     *    display_ticket_selector
70
-     *
71
-     * @access    public
72
-     * @param    int $EVT_ID
73
-     * @return    boolean
74
-     */
75
-    public static function display_ticket_selector($EVT_ID = 0)
76
-    {
77
-        $event = EEH_Event_View::get_event($EVT_ID);
78
-        return $event instanceof EE_Event ? $event->display_ticket_selector() : false;
79
-    }
80
-
81
-
82
-
83
-    /**
84
-     *    event_status
85
-     *
86
-     * @access    public
87
-     * @param    int $EVT_ID
88
-     * @return    string
89
-     */
90
-    public static function event_status($EVT_ID = 0)
91
-    {
92
-        $event = EEH_Event_View::get_event($EVT_ID);
93
-        return $event instanceof EE_Event ? $event->pretty_active_status(false) : '';
94
-    }
95
-
96
-
97
-
98
-    /**
99
-     *  event_active_status
100
-     *
101
-     *  @access     public
102
-     * @param    int $EVT_ID
103
-     *  @return     string
104
-     */
105
-    public static function event_active_status($EVT_ID = 0, $echo = true)
106
-    {
107
-        $event = EEH_Event_View::get_event($EVT_ID);
108
-        return $event instanceof EE_Event ? $event->pretty_active_status($echo) : 'inactive';
109
-    }
110
-
111
-
112
-
113
-    /**
114
-     *  event_has_content_or_excerpt
115
-     *
116
-     *  @access     public
117
-     * @param    int $EVT_ID
118
-     *  @return     string
119
-     */
120
-    public static function event_has_content_or_excerpt($EVT_ID = 0)
121
-    {
122
-        $event = EEH_Event_View::get_event($EVT_ID);
123
-        $has_content_or_excerpt = false;
124
-        if ($event instanceof EE_Event) {
125
-            $has_content_or_excerpt = $event->description() != '' || $event->short_description(null, null, true) != '' ? true : false;
126
-        }
127
-        if (is_archive() && ! ( espresso_display_full_description_in_event_list() || espresso_display_excerpt_in_event_list() )) {
128
-            $has_content_or_excerpt = false;
129
-        }
130
-        return $has_content_or_excerpt;
131
-    }
132
-
133
-
134
-
135
-    /**
136
-     *    event_active_status
137
-     *
138
-     * @access    public
139
-     * @param null $num_words
140
-     * @param null $more
141
-     * @return    string
142
-     */
143
-    public static function event_content_or_excerpt($num_words = null, $more = null)
144
-    {
145
-        global $post;
146
-        ob_start();
147
-        if (( is_single() ) || ( is_archive() && espresso_display_full_description_in_event_list() )) {
148
-            // admin has chosen "full description"
149
-            // for the "Event Espresso - Events > Templates > Display Description" option
150
-            the_content();
151
-        } elseif (( is_archive() && espresso_display_excerpt_in_event_list() )) {
152
-            if (has_excerpt($post->ID)) {
153
-                // admin has chosen "excerpt (short desc)"
154
-                // for the "Event Espresso - Events > Templates > Display Description" option
155
-                // AND an excerpt actually exists
156
-                the_excerpt();
157
-            } else {
158
-                // admin has chosen "excerpt (short desc)"
159
-                // for the "Event Espresso - Events > Templates > Display Description" option
160
-                // but NO excerpt actually exists, so we need to create one
161
-                if (! empty($num_words)) {
162
-                    if (empty($more)) {
163
-                        $more_link_text = __('(more&hellip;)', 'event_espresso');
164
-                        $more = ' <a href="' . get_permalink() . '"';
165
-                        $more .= ' class="more-link"';
166
-                        $more .= \EED_Events_Archive::link_target();
167
-                        $more .= '>' . $more_link_text . '</a>';
168
-                        $more = apply_filters('the_content_more_link', $more, $more_link_text);
169
-                    }
170
-                    $content = str_replace('NOMORELINK', '', get_the_content('NOMORELINK'));
171
-
172
-                    $content =  wp_trim_words($content, $num_words, ' ') . $more;
173
-                } else {
174
-                    $content =  get_the_content();
175
-                }
176
-                global $allowedtags;
177
-                // make sure links are allowed
178
-                $allowedtags['a'] = isset($allowedtags['a'])
179
-                    ? $allowedtags['a']
180
-                    : array();
181
-                // as well as target attribute
182
-                $allowedtags['a']['target'] = isset($allowedtags['a']['target'])
183
-                    ? $allowedtags['a']['target']
184
-                    : false;
185
-                // but get previous value so we can reset it
186
-                $prev_value = $allowedtags['a']['target'];
187
-                $allowedtags['a']['target'] = true;
188
-                $content = wp_kses($content, $allowedtags);
189
-                $content = strip_shortcodes($content);
190
-                echo apply_filters('the_content', $content);
191
-                $allowedtags['a']['target'] = $prev_value;
192
-            }
193
-        } else {
194
-            // admin has chosen "none"
195
-            // for the "Event Espresso - Events > Templates > Display Description" option
196
-            echo apply_filters('the_content', '');
197
-        }
198
-        return ob_get_clean();
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     *  event_tickets_available
205
-     *
206
-     *  @access     public
207
-     * @param    int $EVT_ID
208
-     *  @return     EE_Ticket[]
209
-     */
210
-    public static function event_tickets_available($EVT_ID = 0)
211
-    {
212
-        $event = EEH_Event_View::get_event($EVT_ID);
213
-        $tickets_available_for_purchase = array();
214
-        if ($event instanceof EE_Event) {
215
-            $datetimes = EEH_Event_View::get_all_date_obj($EVT_ID, false);
216
-            foreach ($datetimes as $datetime) {
217
-                $tickets_available_for_purchase = array_merge($tickets_available_for_purchase, $datetime->ticket_types_available_for_purchase());
218
-            }
219
-        }
220
-        return $tickets_available_for_purchase;
221
-    }
222
-
223
-
224
-
225
-    /**
226
-     *    the_event_date
227
-     *
228
-     * @access    public
229
-     * @param    int $EVT_ID
230
-     * @param     bool   $hide_uncategorized
231
-     * @return    string
232
-     */
233
-    public static function event_categories($EVT_ID = 0, $hide_uncategorized = true)
234
-    {
235
-        $category_links = array();
236
-        $event = EEH_Event_View::get_event($EVT_ID);
237
-        if ($event instanceof EE_Event) {
238
-            $event_categories = get_the_terms($event->ID(), 'espresso_event_categories');
239
-            if ($event_categories) {
240
-                // loop thru terms and create links
241
-                foreach ($event_categories as $term) {
242
-                    $url = get_term_link($term, 'espresso_venue_categories');
243
-                    if (! is_wp_error($url) && (( $hide_uncategorized && strtolower($term->name) != __('uncategorized', 'event_espresso')) || ! $hide_uncategorized )) {
244
-                        $category_links[] = '<a href="' . esc_url($url)
245
-                                            . '" rel="tag"'
246
-                                            . \EED_Events_Archive::link_target()
247
-                                            .'>'
248
-                                            . $term->name
249
-                                            . '</a>';
250
-                    }
251
-                }
252
-            }
253
-        }
254
-        return implode(', ', $category_links);
255
-    }
256
-
257
-
258
-
259
-    /**
260
-     *    the_event_date - first date by date order
261
-     *
262
-     * @access    public
263
-     * @param string $dt_frmt
264
-     * @param string $tm_frmt
265
-     * @param int    $EVT_ID
266
-     * @return    string
267
-     */
268
-    public static function the_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
269
-    {
270
-        $datetime = EEH_Event_View::get_primary_date_obj($EVT_ID);
271
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
272
-        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_start', $format) :  '';
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     *    the_event_end_date - last date by date order
279
-     *
280
-     * @access    public
281
-     * @param string $dt_frmt
282
-     * @param string $tm_frmt
283
-     * @param int    $EVT_ID
284
-     * @return    string
285
-     */
286
-    public static function the_event_end_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
287
-    {
288
-        $datetime = EEH_Event_View::get_last_date_obj($EVT_ID);
289
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
290
-        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     *    the_earliest_event_date - first date chronologically
297
-     *
298
-     * @access    public
299
-     * @param string $dt_frmt
300
-     * @param string $tm_frmt
301
-     * @param int    $EVT_ID
302
-     * @return    string
303
-     */
304
-    public static function the_earliest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
305
-    {
306
-        $datetime = EEH_Event_View::get_earliest_date_obj($EVT_ID);
307
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
308
-        return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_start', $format) : '';
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     *    the_latest_event_date - latest date chronologically
315
-     *
316
-     * @access    public
317
-     * @param string $dt_frmt
318
-     * @param string $tm_frmt
319
-     * @param int    $EVT_ID
320
-     * @return    string
321
-     */
322
-    public static function the_latest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
323
-    {
324
-        $datetime = EEH_Event_View::get_latest_date_obj($EVT_ID);
325
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
326
-        return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
327
-    }
328
-
329
-
330
-
331
-    /**
332
-     *    event_date_as_calendar_page
333
-     *
334
-     * @access    public
335
-     * @param int $EVT_ID
336
-     * @return    string
337
-     */
338
-    public static function event_date_as_calendar_page($EVT_ID = 0)
339
-    {
340
-        $datetime = EEH_Event_View::get_primary_date_obj($EVT_ID);
341
-        if ($datetime instanceof EE_Datetime) {
342
-            ?>
14
+	/**
15
+	 * @var EE_Event $_event
16
+	 */
17
+	private static $_event = null;
18
+
19
+
20
+
21
+	/**
22
+	 * get_event
23
+	 * attempts to retrieve an EE_Event object any way it can
24
+	 *
25
+	 * @param int|WP_Post $EVT_ID
26
+	 * @return EE_Event|null
27
+	 * @throws \EE_Error
28
+	 */
29
+	public static function get_event($EVT_ID = 0)
30
+	{
31
+		// international newspaper?
32
+		global $post;
33
+		$EVT_ID = $EVT_ID instanceof WP_Post && $EVT_ID->post_type === 'espresso_events'
34
+			? $EVT_ID->ID
35
+			: absint($EVT_ID);
36
+		// do we already have the Event  you are looking for?
37
+		if (EEH_Event_View::$_event instanceof EE_Event && $EVT_ID && EEH_Event_View::$_event->ID() === $EVT_ID) {
38
+			return EEH_Event_View::$_event;
39
+		}
40
+		// reset property so that the new event is cached.
41
+		EEH_Event_View::$_event = null;
42
+		if (! $EVT_ID && $post instanceof EE_Event) {
43
+			EEH_Event_View::$_event = $post;
44
+			return EEH_Event_View::$_event;
45
+		}
46
+		// if the post type is for an event and it has a cached event and we don't have a different incoming $EVT_ID
47
+		// then let's just use that cached event on the $post object.
48
+		if ($post instanceof WP_Post
49
+			&& $post->post_type === 'espresso_events'
50
+			&& isset($post->EE_Event)
51
+			&& (
52
+				$EVT_ID === 0
53
+				|| $EVT_ID === $post->ID
54
+			)
55
+		) {
56
+			EEH_Event_View::$_event = $post->EE_Event;
57
+			return EEH_Event_View::$_event;
58
+		}
59
+		// If the event we have isn't an event but we do have an EVT_ID, let's try getting the event using the ID.
60
+		if (! EEH_Event_View::$_event instanceof EE_Event && $EVT_ID) {
61
+			EEH_Event_View::$_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
62
+		}
63
+		return EEH_Event_View::$_event;
64
+	}
65
+
66
+
67
+
68
+	/**
69
+	 *    display_ticket_selector
70
+	 *
71
+	 * @access    public
72
+	 * @param    int $EVT_ID
73
+	 * @return    boolean
74
+	 */
75
+	public static function display_ticket_selector($EVT_ID = 0)
76
+	{
77
+		$event = EEH_Event_View::get_event($EVT_ID);
78
+		return $event instanceof EE_Event ? $event->display_ticket_selector() : false;
79
+	}
80
+
81
+
82
+
83
+	/**
84
+	 *    event_status
85
+	 *
86
+	 * @access    public
87
+	 * @param    int $EVT_ID
88
+	 * @return    string
89
+	 */
90
+	public static function event_status($EVT_ID = 0)
91
+	{
92
+		$event = EEH_Event_View::get_event($EVT_ID);
93
+		return $event instanceof EE_Event ? $event->pretty_active_status(false) : '';
94
+	}
95
+
96
+
97
+
98
+	/**
99
+	 *  event_active_status
100
+	 *
101
+	 *  @access     public
102
+	 * @param    int $EVT_ID
103
+	 *  @return     string
104
+	 */
105
+	public static function event_active_status($EVT_ID = 0, $echo = true)
106
+	{
107
+		$event = EEH_Event_View::get_event($EVT_ID);
108
+		return $event instanceof EE_Event ? $event->pretty_active_status($echo) : 'inactive';
109
+	}
110
+
111
+
112
+
113
+	/**
114
+	 *  event_has_content_or_excerpt
115
+	 *
116
+	 *  @access     public
117
+	 * @param    int $EVT_ID
118
+	 *  @return     string
119
+	 */
120
+	public static function event_has_content_or_excerpt($EVT_ID = 0)
121
+	{
122
+		$event = EEH_Event_View::get_event($EVT_ID);
123
+		$has_content_or_excerpt = false;
124
+		if ($event instanceof EE_Event) {
125
+			$has_content_or_excerpt = $event->description() != '' || $event->short_description(null, null, true) != '' ? true : false;
126
+		}
127
+		if (is_archive() && ! ( espresso_display_full_description_in_event_list() || espresso_display_excerpt_in_event_list() )) {
128
+			$has_content_or_excerpt = false;
129
+		}
130
+		return $has_content_or_excerpt;
131
+	}
132
+
133
+
134
+
135
+	/**
136
+	 *    event_active_status
137
+	 *
138
+	 * @access    public
139
+	 * @param null $num_words
140
+	 * @param null $more
141
+	 * @return    string
142
+	 */
143
+	public static function event_content_or_excerpt($num_words = null, $more = null)
144
+	{
145
+		global $post;
146
+		ob_start();
147
+		if (( is_single() ) || ( is_archive() && espresso_display_full_description_in_event_list() )) {
148
+			// admin has chosen "full description"
149
+			// for the "Event Espresso - Events > Templates > Display Description" option
150
+			the_content();
151
+		} elseif (( is_archive() && espresso_display_excerpt_in_event_list() )) {
152
+			if (has_excerpt($post->ID)) {
153
+				// admin has chosen "excerpt (short desc)"
154
+				// for the "Event Espresso - Events > Templates > Display Description" option
155
+				// AND an excerpt actually exists
156
+				the_excerpt();
157
+			} else {
158
+				// admin has chosen "excerpt (short desc)"
159
+				// for the "Event Espresso - Events > Templates > Display Description" option
160
+				// but NO excerpt actually exists, so we need to create one
161
+				if (! empty($num_words)) {
162
+					if (empty($more)) {
163
+						$more_link_text = __('(more&hellip;)', 'event_espresso');
164
+						$more = ' <a href="' . get_permalink() . '"';
165
+						$more .= ' class="more-link"';
166
+						$more .= \EED_Events_Archive::link_target();
167
+						$more .= '>' . $more_link_text . '</a>';
168
+						$more = apply_filters('the_content_more_link', $more, $more_link_text);
169
+					}
170
+					$content = str_replace('NOMORELINK', '', get_the_content('NOMORELINK'));
171
+
172
+					$content =  wp_trim_words($content, $num_words, ' ') . $more;
173
+				} else {
174
+					$content =  get_the_content();
175
+				}
176
+				global $allowedtags;
177
+				// make sure links are allowed
178
+				$allowedtags['a'] = isset($allowedtags['a'])
179
+					? $allowedtags['a']
180
+					: array();
181
+				// as well as target attribute
182
+				$allowedtags['a']['target'] = isset($allowedtags['a']['target'])
183
+					? $allowedtags['a']['target']
184
+					: false;
185
+				// but get previous value so we can reset it
186
+				$prev_value = $allowedtags['a']['target'];
187
+				$allowedtags['a']['target'] = true;
188
+				$content = wp_kses($content, $allowedtags);
189
+				$content = strip_shortcodes($content);
190
+				echo apply_filters('the_content', $content);
191
+				$allowedtags['a']['target'] = $prev_value;
192
+			}
193
+		} else {
194
+			// admin has chosen "none"
195
+			// for the "Event Espresso - Events > Templates > Display Description" option
196
+			echo apply_filters('the_content', '');
197
+		}
198
+		return ob_get_clean();
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 *  event_tickets_available
205
+	 *
206
+	 *  @access     public
207
+	 * @param    int $EVT_ID
208
+	 *  @return     EE_Ticket[]
209
+	 */
210
+	public static function event_tickets_available($EVT_ID = 0)
211
+	{
212
+		$event = EEH_Event_View::get_event($EVT_ID);
213
+		$tickets_available_for_purchase = array();
214
+		if ($event instanceof EE_Event) {
215
+			$datetimes = EEH_Event_View::get_all_date_obj($EVT_ID, false);
216
+			foreach ($datetimes as $datetime) {
217
+				$tickets_available_for_purchase = array_merge($tickets_available_for_purchase, $datetime->ticket_types_available_for_purchase());
218
+			}
219
+		}
220
+		return $tickets_available_for_purchase;
221
+	}
222
+
223
+
224
+
225
+	/**
226
+	 *    the_event_date
227
+	 *
228
+	 * @access    public
229
+	 * @param    int $EVT_ID
230
+	 * @param     bool   $hide_uncategorized
231
+	 * @return    string
232
+	 */
233
+	public static function event_categories($EVT_ID = 0, $hide_uncategorized = true)
234
+	{
235
+		$category_links = array();
236
+		$event = EEH_Event_View::get_event($EVT_ID);
237
+		if ($event instanceof EE_Event) {
238
+			$event_categories = get_the_terms($event->ID(), 'espresso_event_categories');
239
+			if ($event_categories) {
240
+				// loop thru terms and create links
241
+				foreach ($event_categories as $term) {
242
+					$url = get_term_link($term, 'espresso_venue_categories');
243
+					if (! is_wp_error($url) && (( $hide_uncategorized && strtolower($term->name) != __('uncategorized', 'event_espresso')) || ! $hide_uncategorized )) {
244
+						$category_links[] = '<a href="' . esc_url($url)
245
+											. '" rel="tag"'
246
+											. \EED_Events_Archive::link_target()
247
+											.'>'
248
+											. $term->name
249
+											. '</a>';
250
+					}
251
+				}
252
+			}
253
+		}
254
+		return implode(', ', $category_links);
255
+	}
256
+
257
+
258
+
259
+	/**
260
+	 *    the_event_date - first date by date order
261
+	 *
262
+	 * @access    public
263
+	 * @param string $dt_frmt
264
+	 * @param string $tm_frmt
265
+	 * @param int    $EVT_ID
266
+	 * @return    string
267
+	 */
268
+	public static function the_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
269
+	{
270
+		$datetime = EEH_Event_View::get_primary_date_obj($EVT_ID);
271
+		$format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
272
+		return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_start', $format) :  '';
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 *    the_event_end_date - last date by date order
279
+	 *
280
+	 * @access    public
281
+	 * @param string $dt_frmt
282
+	 * @param string $tm_frmt
283
+	 * @param int    $EVT_ID
284
+	 * @return    string
285
+	 */
286
+	public static function the_event_end_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
287
+	{
288
+		$datetime = EEH_Event_View::get_last_date_obj($EVT_ID);
289
+		$format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
290
+		return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 *    the_earliest_event_date - first date chronologically
297
+	 *
298
+	 * @access    public
299
+	 * @param string $dt_frmt
300
+	 * @param string $tm_frmt
301
+	 * @param int    $EVT_ID
302
+	 * @return    string
303
+	 */
304
+	public static function the_earliest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
305
+	{
306
+		$datetime = EEH_Event_View::get_earliest_date_obj($EVT_ID);
307
+		$format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
308
+		return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_start', $format) : '';
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 *    the_latest_event_date - latest date chronologically
315
+	 *
316
+	 * @access    public
317
+	 * @param string $dt_frmt
318
+	 * @param string $tm_frmt
319
+	 * @param int    $EVT_ID
320
+	 * @return    string
321
+	 */
322
+	public static function the_latest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
323
+	{
324
+		$datetime = EEH_Event_View::get_latest_date_obj($EVT_ID);
325
+		$format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
326
+		return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
327
+	}
328
+
329
+
330
+
331
+	/**
332
+	 *    event_date_as_calendar_page
333
+	 *
334
+	 * @access    public
335
+	 * @param int $EVT_ID
336
+	 * @return    string
337
+	 */
338
+	public static function event_date_as_calendar_page($EVT_ID = 0)
339
+	{
340
+		$datetime = EEH_Event_View::get_primary_date_obj($EVT_ID);
341
+		if ($datetime instanceof EE_Datetime) {
342
+			?>
343 343
         <div class="event-date-calendar-page-dv">
344 344
             <div class="event-date-calendar-page-month-dv"><?php echo $datetime->get_i18n_datetime('DTT_EVT_start', 'M');?></div>
345 345
             <div class="event-date-calendar-page-day-dv"><?php echo $datetime->start_date('d');?></div>
346 346
         </div>
347 347
             <?php
348
-        }
349
-    }
350
-
351
-
352
-
353
-    /**
354
-     *    get_primary_date_obj - orders date by DTT_order
355
-     *
356
-     * @access    public
357
-     * @param int $EVT_ID
358
-     * @return    string
359
-     */
360
-    public static function get_primary_date_obj($EVT_ID = 0)
361
-    {
362
-        $event = EEH_Event_View::get_event($EVT_ID);
363
-        if ($event instanceof EE_Event) {
364
-            $datetimes = $event->get_many_related(
365
-                'Datetime',
366
-                array(
367
-                    'limit' => 1,
368
-                    'order_by' => array( 'DTT_order' => 'ASC' )
369
-                )
370
-            );
371
-            return reset($datetimes);
372
-        } else {
373
-             return false;
374
-        }
375
-    }
376
-
377
-
378
-
379
-    /**
380
-     *    get_last_date_obj - orders date by DTT_order
381
-     *
382
-     * @access    public
383
-     * @param int $EVT_ID
384
-     * @return    string
385
-     */
386
-    public static function get_last_date_obj($EVT_ID = 0)
387
-    {
388
-        $event = EEH_Event_View::get_event($EVT_ID);
389
-        if ($event instanceof EE_Event) {
390
-            $datetimes = $event->get_many_related(
391
-                'Datetime',
392
-                array(
393
-                    'limit' => 1,
394
-                    'order_by' => array( 'DTT_order' => 'DESC' )
395
-                )
396
-            );
397
-            return end($datetimes);
398
-        } else {
399
-            return false;
400
-        }
401
-    }
402
-
403
-
404
-
405
-    /**
406
-     *    get_earliest_date_obj - orders date chronologically
407
-     *
408
-     * @access    public
409
-     * @param int $EVT_ID
410
-     * @return    string
411
-     */
412
-    public static function get_earliest_date_obj($EVT_ID = 0)
413
-    {
414
-        $event = EEH_Event_View::get_event($EVT_ID);
415
-        if ($event instanceof EE_Event) {
416
-            $datetimes = $event->get_many_related(
417
-                'Datetime',
418
-                array(
419
-                    'limit' => 1,
420
-                    'order_by' => array( 'DTT_EVT_start' => 'ASC' )
421
-                )
422
-            );
423
-            return reset($datetimes);
424
-        } else {
425
-             return false;
426
-        }
427
-    }
428
-
429
-
430
-
431
-    /**
432
-     *    get_latest_date_obj - orders date chronologically
433
-     *
434
-     * @access    public
435
-     * @param int $EVT_ID
436
-     * @return    string
437
-     */
438
-    public static function get_latest_date_obj($EVT_ID = 0)
439
-    {
440
-        $event = EEH_Event_View::get_event($EVT_ID);
441
-        if ($event instanceof EE_Event) {
442
-            $datetimes = $event->get_many_related(
443
-                'Datetime',
444
-                array(
445
-                    'limit' => 1,
446
-                    'order_by' => array( 'DTT_EVT_start' => 'DESC' )
447
-                )
448
-            );
449
-            return end($datetimes);
450
-        } else {
451
-            return false;
452
-        }
453
-    }
454
-
455
-    /**
456
-     *    get_next_upcoming_date_obj - return the next upcoming datetime
457
-     *
458
-     * @access    public
459
-     * @param int $EVT_ID
460
-     * @return    EE_Datetime|null
461
-     */
462
-    public static function get_next_upcoming_date_obj($EVT_ID = 0)
463
-    {
464
-        $datetime = EEM_Datetime::instance()->get_one(
465
-            array(
466
-                array(
467
-                    'Event.EVT_ID' => $EVT_ID,
468
-                    'DTT_EVT_start' => array('>=', current_time('mysql', true))
469
-                ),
470
-                'order_by' => array('DTT_EVT_start' => 'asc')
471
-            )
472
-        );
473
-        return $datetime instanceof EE_Datetime ? $datetime : null;
474
-    }
475
-
476
-    /**
477
-     *    get_all_date_obj
478
-     *
479
-     * @access    public
480
-     * @param int $EVT_ID
481
-     * @param null $include_expired
482
-     * @param bool $include_deleted
483
-     * @param null $limit
484
-     * @return EE_Datetime[]
485
-     */
486
-    public static function get_all_date_obj($EVT_ID = 0, $include_expired = null, $include_deleted = false, $limit = null)
487
-    {
488
-        $event = EEH_Event_View::get_event($EVT_ID);
489
-        if ($include_expired === null) {
490
-            if ($event instanceof EE_Event && $event->is_expired()) {
491
-                $include_expired = true;
492
-            } else {
493
-                $include_expired = false;
494
-            }
495
-        }
496
-
497
-        if ($event instanceof EE_Event) {
498
-            return $event->datetimes_ordered($include_expired, $include_deleted, $limit);
499
-        } else {
500
-             return array();
501
-        }
502
-    }
503
-
504
-
505
-
506
-    /**
507
-     *    event_link_url
508
-     *
509
-     * @access    public
510
-     * @param int $EVT_ID
511
-     * @return    string
512
-     */
513
-    public static function event_link_url($EVT_ID = 0)
514
-    {
515
-        $event = EEH_Event_View::get_event($EVT_ID);
516
-        if ($event instanceof EE_Event) {
517
-            $url = $event->external_url() !== null && $event->external_url() !== '' ? $event->external_url() : get_permalink($event->ID());
518
-            return preg_match("~^(?:f|ht)tps?://~i", $url) ? $url : 'http://' . $url;
519
-        }
520
-        return null;
521
-    }
522
-
523
-
524
-
525
-    /**
526
-     *    event_phone
527
-     *
528
-     * @access    public
529
-     * @param int $EVT_ID
530
-     * @return    string
531
-     */
532
-    public static function event_phone($EVT_ID = 0)
533
-    {
534
-        $event = EEH_Event_View::get_event($EVT_ID);
535
-        if ($event instanceof EE_Event) {
536
-            return EEH_Schema::telephone($event->phone());
537
-        }
538
-        return null;
539
-    }
540
-
541
-
542
-
543
-    /**
544
-     *    edit_event_link
545
-     *
546
-     * @access    public
547
-     * @param int    $EVT_ID
548
-     * @param string $link
549
-     * @param string $before
550
-     * @param string $after
551
-     * @return    string
552
-     */
553
-    public static function edit_event_link($EVT_ID = 0, $link = '', $before = '', $after = '')
554
-    {
555
-        $event = EEH_Event_View::get_event($EVT_ID);
556
-        if ($event instanceof EE_Event) {
557
-            // can the user edit this post ?
558
-            if (current_user_can('edit_post', $event->ID())) {
559
-                // set link text
560
-                $link_text = ! empty($link) ? $link : __('edit this event', 'event_espresso');
561
-                // generate nonce
562
-                $nonce = wp_create_nonce('edit_nonce');
563
-                // generate url to event editor for this event
564
-                $url = add_query_arg(array( 'page' => 'espresso_events', 'action' => 'edit', 'post' => $event->ID(), 'edit_nonce' => $nonce ), admin_url());
565
-                // get edit CPT text
566
-                $post_type_obj = get_post_type_object('espresso_events');
567
-                // build final link html
568
-                $link = '<a class="post-edit-link" href="' . $url . '" ';
569
-                $link .= ' title="' . esc_attr($post_type_obj->labels->edit_item) . '"';
570
-                $link .= \EED_Events_Archive::link_target();
571
-                $link .='>' . $link_text . '</a>';
572
-                // put it all together
573
-                return $before . apply_filters('edit_post_link', $link, $event->ID()) . $after;
574
-            }
575
-        }
576
-        return '';
577
-    }
578
-
579
-
580
-
581
-    /**
582
-     * @return string
583
-     */
584
-    public static function event_archive_url()
585
-    {
586
-        return get_post_type_archive_link('espresso_events');
587
-    }
348
+		}
349
+	}
350
+
351
+
352
+
353
+	/**
354
+	 *    get_primary_date_obj - orders date by DTT_order
355
+	 *
356
+	 * @access    public
357
+	 * @param int $EVT_ID
358
+	 * @return    string
359
+	 */
360
+	public static function get_primary_date_obj($EVT_ID = 0)
361
+	{
362
+		$event = EEH_Event_View::get_event($EVT_ID);
363
+		if ($event instanceof EE_Event) {
364
+			$datetimes = $event->get_many_related(
365
+				'Datetime',
366
+				array(
367
+					'limit' => 1,
368
+					'order_by' => array( 'DTT_order' => 'ASC' )
369
+				)
370
+			);
371
+			return reset($datetimes);
372
+		} else {
373
+			 return false;
374
+		}
375
+	}
376
+
377
+
378
+
379
+	/**
380
+	 *    get_last_date_obj - orders date by DTT_order
381
+	 *
382
+	 * @access    public
383
+	 * @param int $EVT_ID
384
+	 * @return    string
385
+	 */
386
+	public static function get_last_date_obj($EVT_ID = 0)
387
+	{
388
+		$event = EEH_Event_View::get_event($EVT_ID);
389
+		if ($event instanceof EE_Event) {
390
+			$datetimes = $event->get_many_related(
391
+				'Datetime',
392
+				array(
393
+					'limit' => 1,
394
+					'order_by' => array( 'DTT_order' => 'DESC' )
395
+				)
396
+			);
397
+			return end($datetimes);
398
+		} else {
399
+			return false;
400
+		}
401
+	}
402
+
403
+
404
+
405
+	/**
406
+	 *    get_earliest_date_obj - orders date chronologically
407
+	 *
408
+	 * @access    public
409
+	 * @param int $EVT_ID
410
+	 * @return    string
411
+	 */
412
+	public static function get_earliest_date_obj($EVT_ID = 0)
413
+	{
414
+		$event = EEH_Event_View::get_event($EVT_ID);
415
+		if ($event instanceof EE_Event) {
416
+			$datetimes = $event->get_many_related(
417
+				'Datetime',
418
+				array(
419
+					'limit' => 1,
420
+					'order_by' => array( 'DTT_EVT_start' => 'ASC' )
421
+				)
422
+			);
423
+			return reset($datetimes);
424
+		} else {
425
+			 return false;
426
+		}
427
+	}
428
+
429
+
430
+
431
+	/**
432
+	 *    get_latest_date_obj - orders date chronologically
433
+	 *
434
+	 * @access    public
435
+	 * @param int $EVT_ID
436
+	 * @return    string
437
+	 */
438
+	public static function get_latest_date_obj($EVT_ID = 0)
439
+	{
440
+		$event = EEH_Event_View::get_event($EVT_ID);
441
+		if ($event instanceof EE_Event) {
442
+			$datetimes = $event->get_many_related(
443
+				'Datetime',
444
+				array(
445
+					'limit' => 1,
446
+					'order_by' => array( 'DTT_EVT_start' => 'DESC' )
447
+				)
448
+			);
449
+			return end($datetimes);
450
+		} else {
451
+			return false;
452
+		}
453
+	}
454
+
455
+	/**
456
+	 *    get_next_upcoming_date_obj - return the next upcoming datetime
457
+	 *
458
+	 * @access    public
459
+	 * @param int $EVT_ID
460
+	 * @return    EE_Datetime|null
461
+	 */
462
+	public static function get_next_upcoming_date_obj($EVT_ID = 0)
463
+	{
464
+		$datetime = EEM_Datetime::instance()->get_one(
465
+			array(
466
+				array(
467
+					'Event.EVT_ID' => $EVT_ID,
468
+					'DTT_EVT_start' => array('>=', current_time('mysql', true))
469
+				),
470
+				'order_by' => array('DTT_EVT_start' => 'asc')
471
+			)
472
+		);
473
+		return $datetime instanceof EE_Datetime ? $datetime : null;
474
+	}
475
+
476
+	/**
477
+	 *    get_all_date_obj
478
+	 *
479
+	 * @access    public
480
+	 * @param int $EVT_ID
481
+	 * @param null $include_expired
482
+	 * @param bool $include_deleted
483
+	 * @param null $limit
484
+	 * @return EE_Datetime[]
485
+	 */
486
+	public static function get_all_date_obj($EVT_ID = 0, $include_expired = null, $include_deleted = false, $limit = null)
487
+	{
488
+		$event = EEH_Event_View::get_event($EVT_ID);
489
+		if ($include_expired === null) {
490
+			if ($event instanceof EE_Event && $event->is_expired()) {
491
+				$include_expired = true;
492
+			} else {
493
+				$include_expired = false;
494
+			}
495
+		}
496
+
497
+		if ($event instanceof EE_Event) {
498
+			return $event->datetimes_ordered($include_expired, $include_deleted, $limit);
499
+		} else {
500
+			 return array();
501
+		}
502
+	}
503
+
504
+
505
+
506
+	/**
507
+	 *    event_link_url
508
+	 *
509
+	 * @access    public
510
+	 * @param int $EVT_ID
511
+	 * @return    string
512
+	 */
513
+	public static function event_link_url($EVT_ID = 0)
514
+	{
515
+		$event = EEH_Event_View::get_event($EVT_ID);
516
+		if ($event instanceof EE_Event) {
517
+			$url = $event->external_url() !== null && $event->external_url() !== '' ? $event->external_url() : get_permalink($event->ID());
518
+			return preg_match("~^(?:f|ht)tps?://~i", $url) ? $url : 'http://' . $url;
519
+		}
520
+		return null;
521
+	}
522
+
523
+
524
+
525
+	/**
526
+	 *    event_phone
527
+	 *
528
+	 * @access    public
529
+	 * @param int $EVT_ID
530
+	 * @return    string
531
+	 */
532
+	public static function event_phone($EVT_ID = 0)
533
+	{
534
+		$event = EEH_Event_View::get_event($EVT_ID);
535
+		if ($event instanceof EE_Event) {
536
+			return EEH_Schema::telephone($event->phone());
537
+		}
538
+		return null;
539
+	}
540
+
541
+
542
+
543
+	/**
544
+	 *    edit_event_link
545
+	 *
546
+	 * @access    public
547
+	 * @param int    $EVT_ID
548
+	 * @param string $link
549
+	 * @param string $before
550
+	 * @param string $after
551
+	 * @return    string
552
+	 */
553
+	public static function edit_event_link($EVT_ID = 0, $link = '', $before = '', $after = '')
554
+	{
555
+		$event = EEH_Event_View::get_event($EVT_ID);
556
+		if ($event instanceof EE_Event) {
557
+			// can the user edit this post ?
558
+			if (current_user_can('edit_post', $event->ID())) {
559
+				// set link text
560
+				$link_text = ! empty($link) ? $link : __('edit this event', 'event_espresso');
561
+				// generate nonce
562
+				$nonce = wp_create_nonce('edit_nonce');
563
+				// generate url to event editor for this event
564
+				$url = add_query_arg(array( 'page' => 'espresso_events', 'action' => 'edit', 'post' => $event->ID(), 'edit_nonce' => $nonce ), admin_url());
565
+				// get edit CPT text
566
+				$post_type_obj = get_post_type_object('espresso_events');
567
+				// build final link html
568
+				$link = '<a class="post-edit-link" href="' . $url . '" ';
569
+				$link .= ' title="' . esc_attr($post_type_obj->labels->edit_item) . '"';
570
+				$link .= \EED_Events_Archive::link_target();
571
+				$link .='>' . $link_text . '</a>';
572
+				// put it all together
573
+				return $before . apply_filters('edit_post_link', $link, $event->ID()) . $after;
574
+			}
575
+		}
576
+		return '';
577
+	}
578
+
579
+
580
+
581
+	/**
582
+	 * @return string
583
+	 */
584
+	public static function event_archive_url()
585
+	{
586
+		return get_post_type_archive_link('espresso_events');
587
+	}
588 588
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
         }
40 40
         // reset property so that the new event is cached.
41 41
         EEH_Event_View::$_event = null;
42
-        if (! $EVT_ID && $post instanceof EE_Event) {
42
+        if ( ! $EVT_ID && $post instanceof EE_Event) {
43 43
             EEH_Event_View::$_event = $post;
44 44
             return EEH_Event_View::$_event;
45 45
         }
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
             return EEH_Event_View::$_event;
58 58
         }
59 59
         // If the event we have isn't an event but we do have an EVT_ID, let's try getting the event using the ID.
60
-        if (! EEH_Event_View::$_event instanceof EE_Event && $EVT_ID) {
60
+        if ( ! EEH_Event_View::$_event instanceof EE_Event && $EVT_ID) {
61 61
             EEH_Event_View::$_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
62 62
         }
63 63
         return EEH_Event_View::$_event;
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
         if ($event instanceof EE_Event) {
125 125
             $has_content_or_excerpt = $event->description() != '' || $event->short_description(null, null, true) != '' ? true : false;
126 126
         }
127
-        if (is_archive() && ! ( espresso_display_full_description_in_event_list() || espresso_display_excerpt_in_event_list() )) {
127
+        if (is_archive() && ! (espresso_display_full_description_in_event_list() || espresso_display_excerpt_in_event_list())) {
128 128
             $has_content_or_excerpt = false;
129 129
         }
130 130
         return $has_content_or_excerpt;
@@ -144,11 +144,11 @@  discard block
 block discarded – undo
144 144
     {
145 145
         global $post;
146 146
         ob_start();
147
-        if (( is_single() ) || ( is_archive() && espresso_display_full_description_in_event_list() )) {
147
+        if ((is_single()) || (is_archive() && espresso_display_full_description_in_event_list())) {
148 148
             // admin has chosen "full description"
149 149
             // for the "Event Espresso - Events > Templates > Display Description" option
150 150
             the_content();
151
-        } elseif (( is_archive() && espresso_display_excerpt_in_event_list() )) {
151
+        } elseif ((is_archive() && espresso_display_excerpt_in_event_list())) {
152 152
             if (has_excerpt($post->ID)) {
153 153
                 // admin has chosen "excerpt (short desc)"
154 154
                 // for the "Event Espresso - Events > Templates > Display Description" option
@@ -158,20 +158,20 @@  discard block
 block discarded – undo
158 158
                 // admin has chosen "excerpt (short desc)"
159 159
                 // for the "Event Espresso - Events > Templates > Display Description" option
160 160
                 // but NO excerpt actually exists, so we need to create one
161
-                if (! empty($num_words)) {
161
+                if ( ! empty($num_words)) {
162 162
                     if (empty($more)) {
163 163
                         $more_link_text = __('(more&hellip;)', 'event_espresso');
164
-                        $more = ' <a href="' . get_permalink() . '"';
164
+                        $more = ' <a href="'.get_permalink().'"';
165 165
                         $more .= ' class="more-link"';
166 166
                         $more .= \EED_Events_Archive::link_target();
167
-                        $more .= '>' . $more_link_text . '</a>';
167
+                        $more .= '>'.$more_link_text.'</a>';
168 168
                         $more = apply_filters('the_content_more_link', $more, $more_link_text);
169 169
                     }
170 170
                     $content = str_replace('NOMORELINK', '', get_the_content('NOMORELINK'));
171 171
 
172
-                    $content =  wp_trim_words($content, $num_words, ' ') . $more;
172
+                    $content = wp_trim_words($content, $num_words, ' ').$more;
173 173
                 } else {
174
-                    $content =  get_the_content();
174
+                    $content = get_the_content();
175 175
                 }
176 176
                 global $allowedtags;
177 177
                 // make sure links are allowed
@@ -240,8 +240,8 @@  discard block
 block discarded – undo
240 240
                 // loop thru terms and create links
241 241
                 foreach ($event_categories as $term) {
242 242
                     $url = get_term_link($term, 'espresso_venue_categories');
243
-                    if (! is_wp_error($url) && (( $hide_uncategorized && strtolower($term->name) != __('uncategorized', 'event_espresso')) || ! $hide_uncategorized )) {
244
-                        $category_links[] = '<a href="' . esc_url($url)
243
+                    if ( ! is_wp_error($url) && (($hide_uncategorized && strtolower($term->name) != __('uncategorized', 'event_espresso')) || ! $hide_uncategorized)) {
244
+                        $category_links[] = '<a href="'.esc_url($url)
245 245
                                             . '" rel="tag"'
246 246
                                             . \EED_Events_Archive::link_target()
247 247
                                             .'>'
@@ -268,8 +268,8 @@  discard block
 block discarded – undo
268 268
     public static function the_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
269 269
     {
270 270
         $datetime = EEH_Event_View::get_primary_date_obj($EVT_ID);
271
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
272
-        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_start', $format) :  '';
271
+        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt.' '.$tm_frmt : $dt_frmt.$tm_frmt;
272
+        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_start', $format) : '';
273 273
     }
274 274
 
275 275
 
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
     public static function the_event_end_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
287 287
     {
288 288
         $datetime = EEH_Event_View::get_last_date_obj($EVT_ID);
289
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
289
+        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt.' '.$tm_frmt : $dt_frmt.$tm_frmt;
290 290
         return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
291 291
     }
292 292
 
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
     public static function the_earliest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
305 305
     {
306 306
         $datetime = EEH_Event_View::get_earliest_date_obj($EVT_ID);
307
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
308
-        return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_start', $format) : '';
307
+        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt.' '.$tm_frmt : $dt_frmt.$tm_frmt;
308
+        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_start', $format) : '';
309 309
     }
310 310
 
311 311
 
@@ -322,8 +322,8 @@  discard block
 block discarded – undo
322 322
     public static function the_latest_event_date($dt_frmt = 'D M jS', $tm_frmt = 'g:i a', $EVT_ID = 0)
323 323
     {
324 324
         $datetime = EEH_Event_View::get_latest_date_obj($EVT_ID);
325
-        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt . ' ' . $tm_frmt : $dt_frmt . $tm_frmt;
326
-        return $datetime instanceof EE_Datetime ?  $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
325
+        $format = ! empty($dt_frmt) && ! empty($tm_frmt) ? $dt_frmt.' '.$tm_frmt : $dt_frmt.$tm_frmt;
326
+        return $datetime instanceof EE_Datetime ? $datetime->get_i18n_datetime('DTT_EVT_end', $format) : '';
327 327
     }
328 328
 
329 329
 
@@ -341,8 +341,8 @@  discard block
 block discarded – undo
341 341
         if ($datetime instanceof EE_Datetime) {
342 342
             ?>
343 343
         <div class="event-date-calendar-page-dv">
344
-            <div class="event-date-calendar-page-month-dv"><?php echo $datetime->get_i18n_datetime('DTT_EVT_start', 'M');?></div>
345
-            <div class="event-date-calendar-page-day-dv"><?php echo $datetime->start_date('d');?></div>
344
+            <div class="event-date-calendar-page-month-dv"><?php echo $datetime->get_i18n_datetime('DTT_EVT_start', 'M'); ?></div>
345
+            <div class="event-date-calendar-page-day-dv"><?php echo $datetime->start_date('d'); ?></div>
346 346
         </div>
347 347
             <?php
348 348
         }
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
                 'Datetime',
366 366
                 array(
367 367
                     'limit' => 1,
368
-                    'order_by' => array( 'DTT_order' => 'ASC' )
368
+                    'order_by' => array('DTT_order' => 'ASC')
369 369
                 )
370 370
             );
371 371
             return reset($datetimes);
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
                 'Datetime',
392 392
                 array(
393 393
                     'limit' => 1,
394
-                    'order_by' => array( 'DTT_order' => 'DESC' )
394
+                    'order_by' => array('DTT_order' => 'DESC')
395 395
                 )
396 396
             );
397 397
             return end($datetimes);
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
                 'Datetime',
418 418
                 array(
419 419
                     'limit' => 1,
420
-                    'order_by' => array( 'DTT_EVT_start' => 'ASC' )
420
+                    'order_by' => array('DTT_EVT_start' => 'ASC')
421 421
                 )
422 422
             );
423 423
             return reset($datetimes);
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
                 'Datetime',
444 444
                 array(
445 445
                     'limit' => 1,
446
-                    'order_by' => array( 'DTT_EVT_start' => 'DESC' )
446
+                    'order_by' => array('DTT_EVT_start' => 'DESC')
447 447
                 )
448 448
             );
449 449
             return end($datetimes);
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
         $event = EEH_Event_View::get_event($EVT_ID);
516 516
         if ($event instanceof EE_Event) {
517 517
             $url = $event->external_url() !== null && $event->external_url() !== '' ? $event->external_url() : get_permalink($event->ID());
518
-            return preg_match("~^(?:f|ht)tps?://~i", $url) ? $url : 'http://' . $url;
518
+            return preg_match("~^(?:f|ht)tps?://~i", $url) ? $url : 'http://'.$url;
519 519
         }
520 520
         return null;
521 521
     }
@@ -561,16 +561,16 @@  discard block
 block discarded – undo
561 561
                 // generate nonce
562 562
                 $nonce = wp_create_nonce('edit_nonce');
563 563
                 // generate url to event editor for this event
564
-                $url = add_query_arg(array( 'page' => 'espresso_events', 'action' => 'edit', 'post' => $event->ID(), 'edit_nonce' => $nonce ), admin_url());
564
+                $url = add_query_arg(array('page' => 'espresso_events', 'action' => 'edit', 'post' => $event->ID(), 'edit_nonce' => $nonce), admin_url());
565 565
                 // get edit CPT text
566 566
                 $post_type_obj = get_post_type_object('espresso_events');
567 567
                 // build final link html
568
-                $link = '<a class="post-edit-link" href="' . $url . '" ';
569
-                $link .= ' title="' . esc_attr($post_type_obj->labels->edit_item) . '"';
568
+                $link = '<a class="post-edit-link" href="'.$url.'" ';
569
+                $link .= ' title="'.esc_attr($post_type_obj->labels->edit_item).'"';
570 570
                 $link .= \EED_Events_Archive::link_target();
571
-                $link .='>' . $link_text . '</a>';
571
+                $link .= '>'.$link_text.'</a>';
572 572
                 // put it all together
573
-                return $before . apply_filters('edit_post_link', $link, $event->ID()) . $after;
573
+                return $before.apply_filters('edit_post_link', $link, $event->ID()).$after;
574 574
             }
575 575
         }
576 576
         return '';
Please login to merge, or discard this patch.
core/helpers/EEH_Schema.helper.php 2 patches
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -12,296 +12,296 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * generates JSON-based linked data for an event
17
-     *
18
-     * @param EE_Event $event
19
-     * @throws EE_Error
20
-     */
21
-    public static function add_json_linked_data_for_event(EE_Event $event)
22
-    {
23
-        // Check we have a valid datetime for the event
24
-        if (! $event->primary_datetime() instanceof EE_Datetime) {
25
-            return;
26
-        }
27
-
28
-        $template_args = array(
29
-            'event_permalink' => '',
30
-            'event_name' => '',
31
-            'event_description' => '',
32
-            'event_start' => '',
33
-            'event_end' => '',
34
-            'event_attendance_mode' => '',
35
-            'event_status' => '',
36
-            'currency' => '',
37
-            'event_tickets' => array(),
38
-            'venue_name' => '',
39
-            'venue_url' => '',
40
-            'venue_locality' => '',
41
-            'venue_region' => '',
42
-            'venue_address' => '',
43
-            'event_image' => '',
44
-        );
45
-        $template_args['event_permalink'] = $event->get_permalink();
46
-        $template_args['event_name'] = $event->name();
47
-        $template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
48
-        // clone datetime so that date formats don't override those for the original datetime
49
-        $primary_datetime = clone $event->primary_datetime();
50
-        $template_args['event_start'] = $primary_datetime->start_date(DateTime::ATOM);
51
-        $template_args['event_end'] = $primary_datetime->end_date(DateTime::ATOM);
52
-        unset($primary_datetime);
53
-        switch ($event->status()) {
54
-            case EEM_Event::cancelled:
55
-                $event_status = 'EventCancelled';
56
-                break;
57
-            case EEM_Event::postponed:
58
-                $event_status = 'EventPostponed';
59
-                break;
60
-            default:
61
-                $event_status = 'EventScheduled';
62
-        }
63
-        $template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
64
-        $template_args['event_status'] = '"https://schema.org/' . $event_status . '"';
65
-        $template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
66
-        foreach ($event->tickets() as $original_ticket) {
67
-            // clone tickets so that date formats don't override those for the original ticket
68
-            $ticket= clone $original_ticket;
69
-            $ID = $ticket->ID();
70
-            $template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
-            $template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
-            $template_args['event_tickets'][ $ID ]['price'] = number_format(
73
-                $ticket->price(),
74
-                EE_Registry::instance()->CFG->currency->dec_plc,
75
-                EE_Registry::instance()->CFG->currency->dec_mrk,
76
-                ''
77
-            );
78
-            switch ($ticket->ticket_status()) {
79
-                case 'TKO':
80
-                    $availability = 'InStock';
81
-                    break;
82
-                case 'TKS':
83
-                    $availability = 'SoldOut';
84
-                    break;
85
-                default:
86
-                    $availability = null;
87
-                    break;
88
-            }
89
-            $template_args['event_tickets'][ $ID ]['availability'] = $availability;
90
-            unset($ticket);
91
-        }
92
-        $VNU_ID = espresso_venue_id();
93
-        if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
94
-            $venue = EEH_Venue_View::get_venue($VNU_ID);
95
-            $template_args['venue_name'] = get_the_title($VNU_ID);
96
-            $template_args['venue_url'] = get_permalink($VNU_ID);
97
-            $template_args['venue_locality'] = $venue->city();
98
-            $template_args['venue_region'] = $venue->state_name();
99
-            $template_args['venue_address'] = $venue->address();
100
-            if ($venue->virtual_url() !== '') {
101
-                $template_args['event_attendance_mode'] = 'OnlineEventAttendanceMode';
102
-            }
103
-            if ($venue->virtual_url() !== '' && $venue->address() !== '') {
104
-                $template_args['event_attendance_mode'] = 'MixedEventAttendanceMode';
105
-            }
106
-        }
107
-        $template_args['event_image'] = $event->feature_image_url();
108
-        $template_args = apply_filters(
109
-            'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
110
-            $template_args,
111
-            $event,
112
-            $VNU_ID
113
-        );
114
-        extract($template_args, EXTR_OVERWRITE);
115
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
116
-    }
117
-
118
-
119
-    /**
120
-     *    location
121
-     *    The location of the event, organization or action.
122
-     *    Should include the Venue name AND schema formatted address info
123
-     *
124
-     * @access public
125
-     * @param string $location
126
-     * @return string
127
-     */
128
-    public static function location($location = null)
129
-    {
130
-        return ! empty($location) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
131
-                                      . $location
132
-                                      . '</div>' : '';
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     *    name
139
-     *    The name of the Event or Venue.
140
-     *
141
-     * @access public
142
-     * @param string $name
143
-     * @return string
144
-     */
145
-    public static function name($name = null)
146
-    {
147
-        return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
148
-    }
149
-
150
-
151
-
152
-    /**
153
-     *    streetAddress
154
-     *    The street address. For example, 1600 Amphitheatre Pkwy.
155
-     *
156
-     * @access public
157
-     * @param EEI_Address $obj_with_address
158
-     * @return string
159
-     */
160
-    public static function streetAddress(EEI_Address $obj_with_address = null)
161
-    {
162
-        return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
163
-            ? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     *    postOfficeBoxNumber
170
-     *    The post office box number for PO box addresses.
171
-     *
172
-     * @access public
173
-     * @param EEI_Address $obj_with_address
174
-     * @return string
175
-     */
176
-    public static function postOfficeBoxNumber(EEI_Address $obj_with_address = null)
177
-    {
178
-        // regex check for some form of PO Box or P.O. Box, etc, etc, etc
179
-        if (preg_match(
180
-            "/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i",
181
-            $obj_with_address->address2()
182
-        )) {
183
-            return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
184
-                ? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
185
-        } else {
186
-            return $obj_with_address->address2();
187
-        }
188
-    }
189
-
190
-
191
-
192
-    /**
193
-     *    addressLocality
194
-     *    The locality (city, town, etc). For example, Mountain View.
195
-     *
196
-     * @access public
197
-     * @param EEI_Address $obj_with_address
198
-     * @return string
199
-     */
200
-    public static function addressLocality(EEI_Address $obj_with_address = null)
201
-    {
202
-        return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
203
-            ? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     *    addressRegion
210
-     *    The region (state, province, etc). For example, CA.
211
-     *
212
-     * @access public
213
-     * @param EEI_Address $obj_with_address
214
-     * @return string
215
-     */
216
-    public static function addressRegion(EEI_Address $obj_with_address = null)
217
-    {
218
-        $state = $obj_with_address->state_name();
219
-        if (! empty($state)) {
220
-            return '<span itemprop="addressRegion">' . $state . '</span>';
221
-        } else {
222
-            return '';
223
-        }
224
-    }
225
-
226
-
227
-
228
-    /**
229
-     *    addressCountry
230
-     *    The country. For example, USA. You can also provide the two-letter ISO 3166-1 alpha-2 country code.
231
-     *
232
-     * @access public
233
-     * @param EEI_Address $obj_with_address
234
-     * @return string
235
-     */
236
-    public static function addressCountry(EEI_Address $obj_with_address = null)
237
-    {
238
-        $country = $obj_with_address->country_name();
239
-        if (! empty($country)) {
240
-            return '<span itemprop="addressCountry">' . $country . '</span>';
241
-        } else {
242
-            return '';
243
-        }
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     *    postalCode
250
-     *    The postal code. For example, 94043.
251
-     *
252
-     * @access public
253
-     * @param EEI_Address $obj_with_address
254
-     * @return string
255
-     */
256
-    public static function postalCode(EEI_Address $obj_with_address = null)
257
-    {
258
-        return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
259
-                                                                                      . $obj_with_address->zip()
260
-                                                                                      . '</span>' : '';
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     *    telephone
267
-     *    The telephone number.
268
-     *
269
-     * @access public
270
-     * @param string $phone_nmbr
271
-     * @return string
272
-     */
273
-    public static function telephone($phone_nmbr = null)
274
-    {
275
-        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
276
-            : '';
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     *    URL
283
-     *    URL of the item as a clickable link
284
-     *
285
-     * @access public
286
-     * @param string $url        - the URL that the link will resolve to
287
-     * @param string $text       - the text that will be used for the visible link
288
-     * @param array  $attributes - array of additional link attributes in  attribute_name => value pairs. ie: array( 'title' => 'click here', 'class' => 'link-class' )
289
-     * @return string (link)
290
-     */
291
-    public static function url($url = null, $text = null, $attributes = array())
292
-    {
293
-        // Check the URL includes a scheme
294
-        $parsed_url = parse_url($url);
295
-        if (empty($parsed_url['scheme'])) {
296
-            $url = 'http://' . ltrim($url, '/');
297
-        }
298
-
299
-        $atts = '';
300
-        foreach ($attributes as $attribute => $value) {
301
-            $atts .= ' ' . $attribute . '="' . $value . '"';
302
-        }
303
-        $text = $text !== null && $text !== '' ? $text : $url;
304
-        return $url !== null && $url !== '' ? '<a itemprop="url" href="' . $url . '"' . $atts . '>' . $text . '</a>'
305
-            : '';
306
-    }
15
+	/**
16
+	 * generates JSON-based linked data for an event
17
+	 *
18
+	 * @param EE_Event $event
19
+	 * @throws EE_Error
20
+	 */
21
+	public static function add_json_linked_data_for_event(EE_Event $event)
22
+	{
23
+		// Check we have a valid datetime for the event
24
+		if (! $event->primary_datetime() instanceof EE_Datetime) {
25
+			return;
26
+		}
27
+
28
+		$template_args = array(
29
+			'event_permalink' => '',
30
+			'event_name' => '',
31
+			'event_description' => '',
32
+			'event_start' => '',
33
+			'event_end' => '',
34
+			'event_attendance_mode' => '',
35
+			'event_status' => '',
36
+			'currency' => '',
37
+			'event_tickets' => array(),
38
+			'venue_name' => '',
39
+			'venue_url' => '',
40
+			'venue_locality' => '',
41
+			'venue_region' => '',
42
+			'venue_address' => '',
43
+			'event_image' => '',
44
+		);
45
+		$template_args['event_permalink'] = $event->get_permalink();
46
+		$template_args['event_name'] = $event->name();
47
+		$template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
48
+		// clone datetime so that date formats don't override those for the original datetime
49
+		$primary_datetime = clone $event->primary_datetime();
50
+		$template_args['event_start'] = $primary_datetime->start_date(DateTime::ATOM);
51
+		$template_args['event_end'] = $primary_datetime->end_date(DateTime::ATOM);
52
+		unset($primary_datetime);
53
+		switch ($event->status()) {
54
+			case EEM_Event::cancelled:
55
+				$event_status = 'EventCancelled';
56
+				break;
57
+			case EEM_Event::postponed:
58
+				$event_status = 'EventPostponed';
59
+				break;
60
+			default:
61
+				$event_status = 'EventScheduled';
62
+		}
63
+		$template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
64
+		$template_args['event_status'] = '"https://schema.org/' . $event_status . '"';
65
+		$template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
66
+		foreach ($event->tickets() as $original_ticket) {
67
+			// clone tickets so that date formats don't override those for the original ticket
68
+			$ticket= clone $original_ticket;
69
+			$ID = $ticket->ID();
70
+			$template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
+			$template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
+			$template_args['event_tickets'][ $ID ]['price'] = number_format(
73
+				$ticket->price(),
74
+				EE_Registry::instance()->CFG->currency->dec_plc,
75
+				EE_Registry::instance()->CFG->currency->dec_mrk,
76
+				''
77
+			);
78
+			switch ($ticket->ticket_status()) {
79
+				case 'TKO':
80
+					$availability = 'InStock';
81
+					break;
82
+				case 'TKS':
83
+					$availability = 'SoldOut';
84
+					break;
85
+				default:
86
+					$availability = null;
87
+					break;
88
+			}
89
+			$template_args['event_tickets'][ $ID ]['availability'] = $availability;
90
+			unset($ticket);
91
+		}
92
+		$VNU_ID = espresso_venue_id();
93
+		if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
94
+			$venue = EEH_Venue_View::get_venue($VNU_ID);
95
+			$template_args['venue_name'] = get_the_title($VNU_ID);
96
+			$template_args['venue_url'] = get_permalink($VNU_ID);
97
+			$template_args['venue_locality'] = $venue->city();
98
+			$template_args['venue_region'] = $venue->state_name();
99
+			$template_args['venue_address'] = $venue->address();
100
+			if ($venue->virtual_url() !== '') {
101
+				$template_args['event_attendance_mode'] = 'OnlineEventAttendanceMode';
102
+			}
103
+			if ($venue->virtual_url() !== '' && $venue->address() !== '') {
104
+				$template_args['event_attendance_mode'] = 'MixedEventAttendanceMode';
105
+			}
106
+		}
107
+		$template_args['event_image'] = $event->feature_image_url();
108
+		$template_args = apply_filters(
109
+			'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
110
+			$template_args,
111
+			$event,
112
+			$VNU_ID
113
+		);
114
+		extract($template_args, EXTR_OVERWRITE);
115
+		include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
116
+	}
117
+
118
+
119
+	/**
120
+	 *    location
121
+	 *    The location of the event, organization or action.
122
+	 *    Should include the Venue name AND schema formatted address info
123
+	 *
124
+	 * @access public
125
+	 * @param string $location
126
+	 * @return string
127
+	 */
128
+	public static function location($location = null)
129
+	{
130
+		return ! empty($location) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
131
+									  . $location
132
+									  . '</div>' : '';
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 *    name
139
+	 *    The name of the Event or Venue.
140
+	 *
141
+	 * @access public
142
+	 * @param string $name
143
+	 * @return string
144
+	 */
145
+	public static function name($name = null)
146
+	{
147
+		return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
148
+	}
149
+
150
+
151
+
152
+	/**
153
+	 *    streetAddress
154
+	 *    The street address. For example, 1600 Amphitheatre Pkwy.
155
+	 *
156
+	 * @access public
157
+	 * @param EEI_Address $obj_with_address
158
+	 * @return string
159
+	 */
160
+	public static function streetAddress(EEI_Address $obj_with_address = null)
161
+	{
162
+		return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
163
+			? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 *    postOfficeBoxNumber
170
+	 *    The post office box number for PO box addresses.
171
+	 *
172
+	 * @access public
173
+	 * @param EEI_Address $obj_with_address
174
+	 * @return string
175
+	 */
176
+	public static function postOfficeBoxNumber(EEI_Address $obj_with_address = null)
177
+	{
178
+		// regex check for some form of PO Box or P.O. Box, etc, etc, etc
179
+		if (preg_match(
180
+			"/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i",
181
+			$obj_with_address->address2()
182
+		)) {
183
+			return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
184
+				? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
185
+		} else {
186
+			return $obj_with_address->address2();
187
+		}
188
+	}
189
+
190
+
191
+
192
+	/**
193
+	 *    addressLocality
194
+	 *    The locality (city, town, etc). For example, Mountain View.
195
+	 *
196
+	 * @access public
197
+	 * @param EEI_Address $obj_with_address
198
+	 * @return string
199
+	 */
200
+	public static function addressLocality(EEI_Address $obj_with_address = null)
201
+	{
202
+		return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
203
+			? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 *    addressRegion
210
+	 *    The region (state, province, etc). For example, CA.
211
+	 *
212
+	 * @access public
213
+	 * @param EEI_Address $obj_with_address
214
+	 * @return string
215
+	 */
216
+	public static function addressRegion(EEI_Address $obj_with_address = null)
217
+	{
218
+		$state = $obj_with_address->state_name();
219
+		if (! empty($state)) {
220
+			return '<span itemprop="addressRegion">' . $state . '</span>';
221
+		} else {
222
+			return '';
223
+		}
224
+	}
225
+
226
+
227
+
228
+	/**
229
+	 *    addressCountry
230
+	 *    The country. For example, USA. You can also provide the two-letter ISO 3166-1 alpha-2 country code.
231
+	 *
232
+	 * @access public
233
+	 * @param EEI_Address $obj_with_address
234
+	 * @return string
235
+	 */
236
+	public static function addressCountry(EEI_Address $obj_with_address = null)
237
+	{
238
+		$country = $obj_with_address->country_name();
239
+		if (! empty($country)) {
240
+			return '<span itemprop="addressCountry">' . $country . '</span>';
241
+		} else {
242
+			return '';
243
+		}
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 *    postalCode
250
+	 *    The postal code. For example, 94043.
251
+	 *
252
+	 * @access public
253
+	 * @param EEI_Address $obj_with_address
254
+	 * @return string
255
+	 */
256
+	public static function postalCode(EEI_Address $obj_with_address = null)
257
+	{
258
+		return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
259
+																					  . $obj_with_address->zip()
260
+																					  . '</span>' : '';
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 *    telephone
267
+	 *    The telephone number.
268
+	 *
269
+	 * @access public
270
+	 * @param string $phone_nmbr
271
+	 * @return string
272
+	 */
273
+	public static function telephone($phone_nmbr = null)
274
+	{
275
+		return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
276
+			: '';
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 *    URL
283
+	 *    URL of the item as a clickable link
284
+	 *
285
+	 * @access public
286
+	 * @param string $url        - the URL that the link will resolve to
287
+	 * @param string $text       - the text that will be used for the visible link
288
+	 * @param array  $attributes - array of additional link attributes in  attribute_name => value pairs. ie: array( 'title' => 'click here', 'class' => 'link-class' )
289
+	 * @return string (link)
290
+	 */
291
+	public static function url($url = null, $text = null, $attributes = array())
292
+	{
293
+		// Check the URL includes a scheme
294
+		$parsed_url = parse_url($url);
295
+		if (empty($parsed_url['scheme'])) {
296
+			$url = 'http://' . ltrim($url, '/');
297
+		}
298
+
299
+		$atts = '';
300
+		foreach ($attributes as $attribute => $value) {
301
+			$atts .= ' ' . $attribute . '="' . $value . '"';
302
+		}
303
+		$text = $text !== null && $text !== '' ? $text : $url;
304
+		return $url !== null && $url !== '' ? '<a itemprop="url" href="' . $url . '"' . $atts . '>' . $text . '</a>'
305
+			: '';
306
+	}
307 307
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
     public static function add_json_linked_data_for_event(EE_Event $event)
22 22
     {
23 23
         // Check we have a valid datetime for the event
24
-        if (! $event->primary_datetime() instanceof EE_Datetime) {
24
+        if ( ! $event->primary_datetime() instanceof EE_Datetime) {
25 25
             return;
26 26
         }
27 27
 
@@ -61,15 +61,15 @@  discard block
 block discarded – undo
61 61
                 $event_status = 'EventScheduled';
62 62
         }
63 63
         $template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
64
-        $template_args['event_status'] = '"https://schema.org/' . $event_status . '"';
64
+        $template_args['event_status'] = '"https://schema.org/'.$event_status.'"';
65 65
         $template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
66 66
         foreach ($event->tickets() as $original_ticket) {
67 67
             // clone tickets so that date formats don't override those for the original ticket
68
-            $ticket= clone $original_ticket;
68
+            $ticket = clone $original_ticket;
69 69
             $ID = $ticket->ID();
70
-            $template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
-            $template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
-            $template_args['event_tickets'][ $ID ]['price'] = number_format(
70
+            $template_args['event_tickets'][$ID]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
+            $template_args['event_tickets'][$ID]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
+            $template_args['event_tickets'][$ID]['price'] = number_format(
73 73
                 $ticket->price(),
74 74
                 EE_Registry::instance()->CFG->currency->dec_plc,
75 75
                 EE_Registry::instance()->CFG->currency->dec_mrk,
@@ -86,11 +86,11 @@  discard block
 block discarded – undo
86 86
                     $availability = null;
87 87
                     break;
88 88
             }
89
-            $template_args['event_tickets'][ $ID ]['availability'] = $availability;
89
+            $template_args['event_tickets'][$ID]['availability'] = $availability;
90 90
             unset($ticket);
91 91
         }
92 92
         $VNU_ID = espresso_venue_id();
93
-        if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
93
+        if ( ! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
94 94
             $venue = EEH_Venue_View::get_venue($VNU_ID);
95 95
             $template_args['venue_name'] = get_the_title($VNU_ID);
96 96
             $template_args['venue_url'] = get_permalink($VNU_ID);
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
             $VNU_ID
113 113
         );
114 114
         extract($template_args, EXTR_OVERWRITE);
115
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
115
+        include EE_TEMPLATES.'json_linked_data_for_event.template.php';
116 116
     }
117 117
 
118 118
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     public static function name($name = null)
146 146
     {
147
-        return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
147
+        return ! empty($name) ? '<span itemprop="name">'.$name.'</span>' : '';
148 148
     }
149 149
 
150 150
 
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
     public static function streetAddress(EEI_Address $obj_with_address = null)
161 161
     {
162 162
         return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
163
-            ? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
163
+            ? '<span itemprop="streetAddress">'.$obj_with_address->address().'</span>' : '';
164 164
     }
165 165
 
166 166
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
             $obj_with_address->address2()
182 182
         )) {
183 183
             return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
184
-                ? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
184
+                ? '<span itemprop="postOfficeBoxNumber">'.$obj_with_address->address2().'</span>' : '';
185 185
         } else {
186 186
             return $obj_with_address->address2();
187 187
         }
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
     public static function addressLocality(EEI_Address $obj_with_address = null)
201 201
     {
202 202
         return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
203
-            ? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
203
+            ? '<span itemprop="addressLocality">'.$obj_with_address->city().'</span>' : '';
204 204
     }
205 205
 
206 206
 
@@ -216,8 +216,8 @@  discard block
 block discarded – undo
216 216
     public static function addressRegion(EEI_Address $obj_with_address = null)
217 217
     {
218 218
         $state = $obj_with_address->state_name();
219
-        if (! empty($state)) {
220
-            return '<span itemprop="addressRegion">' . $state . '</span>';
219
+        if ( ! empty($state)) {
220
+            return '<span itemprop="addressRegion">'.$state.'</span>';
221 221
         } else {
222 222
             return '';
223 223
         }
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
     public static function addressCountry(EEI_Address $obj_with_address = null)
237 237
     {
238 238
         $country = $obj_with_address->country_name();
239
-        if (! empty($country)) {
240
-            return '<span itemprop="addressCountry">' . $country . '</span>';
239
+        if ( ! empty($country)) {
240
+            return '<span itemprop="addressCountry">'.$country.'</span>';
241 241
         } else {
242 242
             return '';
243 243
         }
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
      */
273 273
     public static function telephone($phone_nmbr = null)
274 274
     {
275
-        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
275
+        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">'.$phone_nmbr.'</span>'
276 276
             : '';
277 277
     }
278 278
 
@@ -293,15 +293,15 @@  discard block
 block discarded – undo
293 293
         // Check the URL includes a scheme
294 294
         $parsed_url = parse_url($url);
295 295
         if (empty($parsed_url['scheme'])) {
296
-            $url = 'http://' . ltrim($url, '/');
296
+            $url = 'http://'.ltrim($url, '/');
297 297
         }
298 298
 
299 299
         $atts = '';
300 300
         foreach ($attributes as $attribute => $value) {
301
-            $atts .= ' ' . $attribute . '="' . $value . '"';
301
+            $atts .= ' '.$attribute.'="'.$value.'"';
302 302
         }
303 303
         $text = $text !== null && $text !== '' ? $text : $url;
304
-        return $url !== null && $url !== '' ? '<a itemprop="url" href="' . $url . '"' . $atts . '>' . $text . '</a>'
304
+        return $url !== null && $url !== '' ? '<a itemprop="url" href="'.$url.'"'.$atts.'>'.$text.'</a>'
305 305
             : '';
306 306
     }
307 307
 }
Please login to merge, or discard this patch.
core/EE_Encryption.core.php 1 patch
Indentation   +577 added lines, -577 removed lines patch added patch discarded remove patch
@@ -25,581 +25,581 @@
 block discarded – undo
25 25
 class EE_Encryption implements InterminableInterface
26 26
 {
27 27
 
28
-    /**
29
-     * key used for saving the encryption key to the wp_options table
30
-     */
31
-    const ENCRYPTION_OPTION_KEY = 'ee_encryption_key';
32
-
33
-    /**
34
-     * the OPENSSL cipher method used
35
-     */
36
-    const OPENSSL_CIPHER_METHOD = 'AES-128-CBC';
37
-
38
-    /**
39
-     * WP "options_name" used to store a verified available cipher method
40
-     */
41
-    const OPENSSL_CIPHER_METHOD_OPTION_NAME = 'ee_openssl_cipher_method';
42
-
43
-    /**
44
-     * the OPENSSL digest method used
45
-     */
46
-    const OPENSSL_DIGEST_METHOD = 'sha512';
47
-
48
-    /**
49
-     * separates the encrypted text from the initialization vector
50
-     */
51
-    const OPENSSL_IV_DELIMITER = ':iv:';
52
-
53
-    /**
54
-     * appended to text encrypted using the acme encryption
55
-     */
56
-    const ACME_ENCRYPTION_FLAG = '::ae';
57
-
58
-
59
-    /**
60
-     * instance of the EE_Encryption object
61
-     */
62
-    protected static $_instance;
63
-
64
-    /**
65
-     * @var string $_encryption_key
66
-     */
67
-    protected $_encryption_key;
68
-
69
-    /**
70
-     * @var string $cipher_method
71
-     */
72
-    private $cipher_method = '';
73
-
74
-    /**
75
-     * @var array $cipher_methods
76
-     */
77
-    private $cipher_methods = array();
78
-
79
-    /**
80
-     * @var array $digest_methods
81
-     */
82
-    private $digest_methods = array();
83
-
84
-    /**
85
-     * @var boolean $_use_openssl_encrypt
86
-     */
87
-    protected $_use_openssl_encrypt = false;
88
-
89
-    /**
90
-     * @var boolean $_use_base64_encode
91
-     */
92
-    protected $_use_base64_encode = false;
93
-
94
-
95
-    /**
96
-     * protected constructor to prevent direct creation
97
-     */
98
-    protected function __construct()
99
-    {
100
-        if (! defined('ESPRESSO_ENCRYPT')) {
101
-            define('ESPRESSO_ENCRYPT', true);
102
-        }
103
-        if (extension_loaded('openssl')) {
104
-            $this->_use_openssl_encrypt = true;
105
-        }
106
-        if (function_exists('base64_encode')) {
107
-            $this->_use_base64_encode = true;
108
-        }
109
-    }
110
-
111
-
112
-    /**
113
-     * singleton method used to instantiate class object
114
-     *
115
-     * @return EE_Encryption
116
-     */
117
-    public static function instance()
118
-    {
119
-        // check if class object is instantiated
120
-        if (! EE_Encryption::$_instance instanceof EE_Encryption) {
121
-            EE_Encryption::$_instance = new self();
122
-        }
123
-        return EE_Encryption::$_instance;
124
-    }
125
-
126
-
127
-    /**
128
-     * get encryption key
129
-     *
130
-     * @return string
131
-     */
132
-    public function get_encryption_key()
133
-    {
134
-        // if encryption key has not been set
135
-        if (empty($this->_encryption_key)) {
136
-            // retrieve encryption_key from db
137
-            $this->_encryption_key = get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, '');
138
-            // WHAT?? No encryption_key in the db ??
139
-            if ($this->_encryption_key === '') {
140
-                // let's make one. And md5 it to make it just the right size for a key
141
-                $new_key = md5($this->generate_random_string());
142
-                // now save it to the db for later
143
-                add_option(EE_Encryption::ENCRYPTION_OPTION_KEY, $new_key);
144
-                // here's the key - FINALLY !
145
-                $this->_encryption_key = $new_key;
146
-            }
147
-        }
148
-        return $this->_encryption_key;
149
-    }
150
-
151
-
152
-    /**
153
-     * encrypts data
154
-     *
155
-     * @param string $text_string - the text to be encrypted
156
-     * @return string
157
-     * @throws RuntimeException
158
-     */
159
-    public function encrypt($text_string = '')
160
-    {
161
-        // you give me nothing??? GET OUT !
162
-        if (empty($text_string)) {
163
-            return $text_string;
164
-        }
165
-        if ($this->_use_openssl_encrypt) {
166
-            $encrypted_text = $this->openssl_encrypt($text_string);
167
-        } else {
168
-            $encrypted_text = $this->acme_encrypt($text_string);
169
-        }
170
-        return $encrypted_text;
171
-    }
172
-
173
-
174
-    /**
175
-     * decrypts data
176
-     *
177
-     * @param string $encrypted_text - the text to be decrypted
178
-     * @return string
179
-     * @throws RuntimeException
180
-     */
181
-    public function decrypt($encrypted_text = '')
182
-    {
183
-        // you give me nothing??? GET OUT !
184
-        if (empty($encrypted_text)) {
185
-            return $encrypted_text;
186
-        }
187
-        // if PHP's mcrypt functions are installed then we'll use them
188
-        if ($this->_use_openssl_encrypt) {
189
-            $decrypted_text = $this->openssl_decrypt($encrypted_text);
190
-        } else {
191
-            $decrypted_text = $this->acme_decrypt($encrypted_text);
192
-        }
193
-        return $decrypted_text;
194
-    }
195
-
196
-
197
-    /**
198
-     * encodes string with PHP's base64 encoding
199
-     *
200
-     * @see http://php.net/manual/en/function.base64-encode.php
201
-     * @param string $text_string the text to be encoded
202
-     * @return string
203
-     */
204
-    public function base64_string_encode($text_string = '')
205
-    {
206
-        // you give me nothing??? GET OUT !
207
-        if (empty($text_string) || ! $this->_use_base64_encode) {
208
-            return $text_string;
209
-        }
210
-        // encode
211
-        return base64_encode($text_string);
212
-    }
213
-
214
-
215
-    /**
216
-     * decodes string that has been encoded with PHP's base64 encoding
217
-     *
218
-     * @see http://php.net/manual/en/function.base64-encode.php
219
-     * @param string $encoded_string the text to be decoded
220
-     * @return string
221
-     * @throws RuntimeException
222
-     */
223
-    public function base64_string_decode($encoded_string = '')
224
-    {
225
-        // you give me nothing??? GET OUT !
226
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
227
-            return $encoded_string;
228
-        }
229
-        // decode
230
-        $decoded_string = base64_decode($encoded_string);
231
-        if ($decoded_string === false) {
232
-            throw new RuntimeException(
233
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
234
-            );
235
-        }
236
-        return $decoded_string;
237
-    }
238
-
239
-
240
-    /**
241
-     * encodes  url string with PHP's base64 encoding
242
-     *
243
-     * @see http://php.net/manual/en/function.base64-encode.php
244
-     * @param string $text_string the text to be encoded
245
-     * @return string
246
-     */
247
-    public function base64_url_encode($text_string = '')
248
-    {
249
-        // you give me nothing??? GET OUT !
250
-        if (empty($text_string) || ! $this->_use_base64_encode) {
251
-            return $text_string;
252
-        }
253
-        // encode
254
-        $encoded_string = base64_encode($text_string);
255
-        // remove chars to make encoding more URL friendly
256
-        return strtr($encoded_string, '+/=', '-_,');
257
-    }
258
-
259
-
260
-    /**
261
-     * decodes  url string that has been encoded with PHP's base64 encoding
262
-     *
263
-     * @see http://php.net/manual/en/function.base64-encode.php
264
-     * @param string $encoded_string the text to be decoded
265
-     * @return string
266
-     * @throws RuntimeException
267
-     */
268
-    public function base64_url_decode($encoded_string = '')
269
-    {
270
-        // you give me nothing??? GET OUT !
271
-        if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
272
-            return $encoded_string;
273
-        }
274
-        // replace previously removed characters
275
-        $encoded_string = strtr($encoded_string, '-_,', '+/=');
276
-        // decode
277
-        $decoded_string = base64_decode($encoded_string);
278
-        if ($decoded_string === false) {
279
-            throw new RuntimeException(
280
-                esc_html__('Base 64 decoding failed.', 'event_espresso')
281
-            );
282
-        }
283
-        return $decoded_string;
284
-    }
285
-
286
-
287
-    /**
288
-     * encrypts data using PHP's openssl functions
289
-     *
290
-     * @param string $text_string the text to be encrypted
291
-     * @param string $cipher_method
292
-     * @param string $encryption_key
293
-     * @return string
294
-     * @throws RuntimeException
295
-     */
296
-    protected function openssl_encrypt(
297
-        $text_string = '',
298
-        $cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
299
-        $encryption_key = ''
300
-    ) {
301
-        // you give me nothing??? GET OUT !
302
-        if (empty($text_string)) {
303
-            return $text_string;
304
-        }
305
-        $this->cipher_method = $this->getCipherMethod($cipher_method);
306
-        // get initialization vector size
307
-        $iv_size = openssl_cipher_iv_length($this->cipher_method);
308
-        // generate initialization vector.
309
-        // The second parameter ("crypto_strong") is passed by reference,
310
-        // and is used to determines if the algorithm used was "cryptographically strong"
311
-        // openssl_random_pseudo_bytes() will toggle it to either true or false
312
-        $iv = openssl_random_pseudo_bytes($iv_size, $is_strong);
313
-        if ($iv === false || $is_strong === false) {
314
-            throw new RuntimeException(
315
-                esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
316
-            );
317
-        }
318
-        // encrypt it
319
-        $encrypted_text = openssl_encrypt(
320
-            $text_string,
321
-            $this->cipher_method,
322
-            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
323
-            0,
324
-            $iv
325
-        );
326
-        // append the initialization vector
327
-        $encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
328
-        // trim and maybe encode
329
-        return $this->_use_base64_encode
330
-            ? trim(base64_encode($encrypted_text))
331
-            : trim($encrypted_text);
332
-    }
333
-
334
-
335
-    /**
336
-     * Returns a cipher method that has been verified to work.
337
-     * First checks if the cached cipher has been set already and if so, returns that.
338
-     * Then tests the incoming default and returns that if it's good.
339
-     * If not, then it retrieves the previously tested and saved cipher method.
340
-     * But if that doesn't exist, then calls getAvailableCipherMethod()
341
-     * to see what is available on the server, and returns the results.
342
-     *
343
-     * @param string $cipher_method
344
-     * @return string
345
-     * @throws RuntimeException
346
-     */
347
-    protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
348
-    {
349
-        if ($this->cipher_method !== '') {
350
-            return $this->cipher_method;
351
-        }
352
-        // verify that the default cipher method can produce an initialization vector
353
-        if (openssl_cipher_iv_length($cipher_method) === false) {
354
-            // nope? okay let's get what we found in the past to work
355
-            $cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
356
-            // oops... haven't tested available cipher methods yet
357
-            if ($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
358
-                $cipher_method = $this->getAvailableCipherMethod($cipher_method);
359
-            }
360
-        }
361
-        return $cipher_method;
362
-    }
363
-
364
-
365
-    /**
366
-     * @param string $cipher_method
367
-     * @return string
368
-     * @throws \RuntimeException
369
-     */
370
-    protected function getAvailableCipherMethod($cipher_method)
371
-    {
372
-        // verify that the incoming cipher method can produce an initialization vector
373
-        if (openssl_cipher_iv_length($cipher_method) === false) {
374
-            // nope? then check the next cipher in the list of available cipher methods
375
-            $cipher_method = next($this->cipher_methods);
376
-            // what? there's no list? then generate that list and cache it,
377
-            if (empty($this->cipher_methods)) {
378
-                $this->cipher_methods = openssl_get_cipher_methods();
379
-                // then grab the first item from the list
380
-                $cipher_method = reset($this->cipher_methods);
381
-            }
382
-            if ($cipher_method === false) {
383
-                throw new RuntimeException(
384
-                    esc_html__(
385
-                        'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
386
-                        'event_espresso'
387
-                    )
388
-                );
389
-            }
390
-            // verify that the next cipher method works
391
-            return $this->getAvailableCipherMethod($cipher_method);
392
-        }
393
-        // if we've gotten this far, then we found an available cipher method that works
394
-        // so save that for next time
395
-        update_option(
396
-            EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME,
397
-            $cipher_method
398
-        );
399
-        return $cipher_method;
400
-    }
401
-
402
-
403
-    /**
404
-     * decrypts data that has been encrypted with PHP's openssl functions
405
-     *
406
-     * @param string $encrypted_text the text to be decrypted
407
-     * @param string $cipher_method
408
-     * @param string $encryption_key
409
-     * @return string
410
-     * @throws RuntimeException
411
-     */
412
-    protected function openssl_decrypt(
413
-        $encrypted_text = '',
414
-        $cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
415
-        $encryption_key = ''
416
-    ) {
417
-        // you give me nothing??? GET OUT !
418
-        if (empty($encrypted_text)) {
419
-            return $encrypted_text;
420
-        }
421
-        // decode
422
-        $encrypted_text = $this->valid_base_64($encrypted_text)
423
-            ? $this->base64_url_decode($encrypted_text)
424
-            : $encrypted_text;
425
-        $encrypted_components = explode(
426
-            EE_Encryption::OPENSSL_IV_DELIMITER,
427
-            $encrypted_text,
428
-            2
429
-        );
430
-        // decrypt it
431
-        $decrypted_text = openssl_decrypt(
432
-            $encrypted_components[0],
433
-            $this->getCipherMethod($cipher_method),
434
-            $this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
435
-            0,
436
-            $encrypted_components[1]
437
-        );
438
-        $decrypted_text = trim($decrypted_text);
439
-        return $decrypted_text;
440
-    }
441
-
442
-
443
-    /**
444
-     * Computes the digest hash value using the specified digest method.
445
-     * If that digest method fails to produce a valid hash value,
446
-     * then we'll grab the next digest method and recursively try again until something works.
447
-     *
448
-     * @param string $digest_method
449
-     * @param string $encryption_key
450
-     * @return string
451
-     * @throws RuntimeException
452
-     */
453
-    protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = '')
454
-    {
455
-        $encryption_key = $encryption_key !== ''
456
-            ? $encryption_key
457
-            : $this->get_encryption_key();
458
-        $digest_hash_value = openssl_digest($encryption_key, $digest_method);
459
-        if ($digest_hash_value === false) {
460
-            return $this->getDigestHashValue($this->getDigestMethod());
461
-        }
462
-        return $digest_hash_value;
463
-    }
464
-
465
-
466
-    /**
467
-     * Returns the NEXT element in the $digest_methods array.
468
-     * If the $digest_methods array is empty, then we populate it
469
-     * with the available values returned from openssl_get_md_methods().
470
-     *
471
-     * @return string
472
-     * @throws \RuntimeException
473
-     */
474
-    protected function getDigestMethod()
475
-    {
476
-        $digest_method = prev($this->digest_methods);
477
-        if (empty($this->digest_methods)) {
478
-            $this->digest_methods = openssl_get_md_methods();
479
-            $digest_method = end($this->digest_methods);
480
-        }
481
-        if ($digest_method === false) {
482
-            throw new RuntimeException(
483
-                esc_html__(
484
-                    'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
485
-                    'event_espresso'
486
-                )
487
-            );
488
-        }
489
-        return $digest_method;
490
-    }
491
-
492
-
493
-    /**
494
-     * encrypts data for acme servers that didn't bother to install PHP mcrypt
495
-     *
496
-     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
497
-     * @param string $text_string the text to be decrypted
498
-     * @return string
499
-     */
500
-    protected function acme_encrypt($text_string = '')
501
-    {
502
-        // you give me nothing??? GET OUT !
503
-        if (empty($text_string)) {
504
-            return $text_string;
505
-        }
506
-        $key_bits = str_split(
507
-            str_pad(
508
-                '',
509
-                strlen($text_string),
510
-                $this->get_encryption_key(),
511
-                STR_PAD_RIGHT
512
-            )
513
-        );
514
-        $string_bits = str_split($text_string);
515
-        foreach ($string_bits as $k => $v) {
516
-            $temp = ord($v) + ord($key_bits[ $k ]);
517
-            $string_bits[ $k ] = chr($temp > 255 ? ($temp - 256) : $temp);
518
-        }
519
-        $encrypted_text = implode('', $string_bits);
520
-        $encrypted_text .= EE_Encryption::ACME_ENCRYPTION_FLAG;
521
-        return $this->_use_base64_encode
522
-            ? base64_encode($encrypted_text)
523
-            : $encrypted_text;
524
-    }
525
-
526
-
527
-    /**
528
-     * decrypts data for acme servers that didn't bother to install PHP mcrypt
529
-     *
530
-     * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
531
-     * @param string $encrypted_text the text to be decrypted
532
-     * @return string
533
-     * @throws RuntimeException
534
-     */
535
-    protected function acme_decrypt($encrypted_text = '')
536
-    {
537
-        // you give me nothing??? GET OUT !
538
-        if (empty($encrypted_text)) {
539
-            return $encrypted_text;
540
-        }
541
-        // decode the data ?
542
-        $encrypted_text = $this->valid_base_64($encrypted_text)
543
-            ? $this->base64_url_decode($encrypted_text)
544
-            : $encrypted_text;
545
-        $encrypted_text = substr($encrypted_text, 0, -4);
546
-        $key_bits = str_split(
547
-            str_pad(
548
-                '',
549
-                strlen($encrypted_text),
550
-                $this->get_encryption_key(),
551
-                STR_PAD_RIGHT
552
-            )
553
-        );
554
-        $string_bits = str_split($encrypted_text);
555
-        foreach ($string_bits as $k => $v) {
556
-            $temp = ord($v) - ord($key_bits[ $k ]);
557
-            $string_bits[ $k ] = chr($temp < 0 ? ($temp + 256) : $temp);
558
-        }
559
-        return implode('', $string_bits);
560
-    }
561
-
562
-
563
-    /**
564
-     * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
565
-     * @param $string
566
-     * @return bool
567
-     */
568
-    protected function valid_base_64($string)
569
-    {
570
-        // ensure data is a string
571
-        if (! is_string($string) || ! $this->_use_base64_encode) {
572
-            return false;
573
-        }
574
-        $decoded = base64_decode($string, true);
575
-        // Check if there is no invalid character in string
576
-        if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
577
-            return false;
578
-        }
579
-        // Decode the string in strict mode and send the response
580
-        if (! base64_decode($string, true)) {
581
-            return false;
582
-        }
583
-        // Encode and compare it to original one
584
-        return base64_encode($decoded) === $string;
585
-    }
586
-
587
-
588
-    /**
589
-     * generate random string
590
-     *
591
-     * @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
592
-     * @param int $length number of characters for random string
593
-     * @return string
594
-     */
595
-    public function generate_random_string($length = 40)
596
-    {
597
-        $iterations = ceil($length / 40);
598
-        $random_string = '';
599
-        for ($i = 0; $i < $iterations; $i++) {
600
-            $random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
601
-        }
602
-        $random_string = substr($random_string, 0, $length);
603
-        return $random_string;
604
-    }
28
+	/**
29
+	 * key used for saving the encryption key to the wp_options table
30
+	 */
31
+	const ENCRYPTION_OPTION_KEY = 'ee_encryption_key';
32
+
33
+	/**
34
+	 * the OPENSSL cipher method used
35
+	 */
36
+	const OPENSSL_CIPHER_METHOD = 'AES-128-CBC';
37
+
38
+	/**
39
+	 * WP "options_name" used to store a verified available cipher method
40
+	 */
41
+	const OPENSSL_CIPHER_METHOD_OPTION_NAME = 'ee_openssl_cipher_method';
42
+
43
+	/**
44
+	 * the OPENSSL digest method used
45
+	 */
46
+	const OPENSSL_DIGEST_METHOD = 'sha512';
47
+
48
+	/**
49
+	 * separates the encrypted text from the initialization vector
50
+	 */
51
+	const OPENSSL_IV_DELIMITER = ':iv:';
52
+
53
+	/**
54
+	 * appended to text encrypted using the acme encryption
55
+	 */
56
+	const ACME_ENCRYPTION_FLAG = '::ae';
57
+
58
+
59
+	/**
60
+	 * instance of the EE_Encryption object
61
+	 */
62
+	protected static $_instance;
63
+
64
+	/**
65
+	 * @var string $_encryption_key
66
+	 */
67
+	protected $_encryption_key;
68
+
69
+	/**
70
+	 * @var string $cipher_method
71
+	 */
72
+	private $cipher_method = '';
73
+
74
+	/**
75
+	 * @var array $cipher_methods
76
+	 */
77
+	private $cipher_methods = array();
78
+
79
+	/**
80
+	 * @var array $digest_methods
81
+	 */
82
+	private $digest_methods = array();
83
+
84
+	/**
85
+	 * @var boolean $_use_openssl_encrypt
86
+	 */
87
+	protected $_use_openssl_encrypt = false;
88
+
89
+	/**
90
+	 * @var boolean $_use_base64_encode
91
+	 */
92
+	protected $_use_base64_encode = false;
93
+
94
+
95
+	/**
96
+	 * protected constructor to prevent direct creation
97
+	 */
98
+	protected function __construct()
99
+	{
100
+		if (! defined('ESPRESSO_ENCRYPT')) {
101
+			define('ESPRESSO_ENCRYPT', true);
102
+		}
103
+		if (extension_loaded('openssl')) {
104
+			$this->_use_openssl_encrypt = true;
105
+		}
106
+		if (function_exists('base64_encode')) {
107
+			$this->_use_base64_encode = true;
108
+		}
109
+	}
110
+
111
+
112
+	/**
113
+	 * singleton method used to instantiate class object
114
+	 *
115
+	 * @return EE_Encryption
116
+	 */
117
+	public static function instance()
118
+	{
119
+		// check if class object is instantiated
120
+		if (! EE_Encryption::$_instance instanceof EE_Encryption) {
121
+			EE_Encryption::$_instance = new self();
122
+		}
123
+		return EE_Encryption::$_instance;
124
+	}
125
+
126
+
127
+	/**
128
+	 * get encryption key
129
+	 *
130
+	 * @return string
131
+	 */
132
+	public function get_encryption_key()
133
+	{
134
+		// if encryption key has not been set
135
+		if (empty($this->_encryption_key)) {
136
+			// retrieve encryption_key from db
137
+			$this->_encryption_key = get_option(EE_Encryption::ENCRYPTION_OPTION_KEY, '');
138
+			// WHAT?? No encryption_key in the db ??
139
+			if ($this->_encryption_key === '') {
140
+				// let's make one. And md5 it to make it just the right size for a key
141
+				$new_key = md5($this->generate_random_string());
142
+				// now save it to the db for later
143
+				add_option(EE_Encryption::ENCRYPTION_OPTION_KEY, $new_key);
144
+				// here's the key - FINALLY !
145
+				$this->_encryption_key = $new_key;
146
+			}
147
+		}
148
+		return $this->_encryption_key;
149
+	}
150
+
151
+
152
+	/**
153
+	 * encrypts data
154
+	 *
155
+	 * @param string $text_string - the text to be encrypted
156
+	 * @return string
157
+	 * @throws RuntimeException
158
+	 */
159
+	public function encrypt($text_string = '')
160
+	{
161
+		// you give me nothing??? GET OUT !
162
+		if (empty($text_string)) {
163
+			return $text_string;
164
+		}
165
+		if ($this->_use_openssl_encrypt) {
166
+			$encrypted_text = $this->openssl_encrypt($text_string);
167
+		} else {
168
+			$encrypted_text = $this->acme_encrypt($text_string);
169
+		}
170
+		return $encrypted_text;
171
+	}
172
+
173
+
174
+	/**
175
+	 * decrypts data
176
+	 *
177
+	 * @param string $encrypted_text - the text to be decrypted
178
+	 * @return string
179
+	 * @throws RuntimeException
180
+	 */
181
+	public function decrypt($encrypted_text = '')
182
+	{
183
+		// you give me nothing??? GET OUT !
184
+		if (empty($encrypted_text)) {
185
+			return $encrypted_text;
186
+		}
187
+		// if PHP's mcrypt functions are installed then we'll use them
188
+		if ($this->_use_openssl_encrypt) {
189
+			$decrypted_text = $this->openssl_decrypt($encrypted_text);
190
+		} else {
191
+			$decrypted_text = $this->acme_decrypt($encrypted_text);
192
+		}
193
+		return $decrypted_text;
194
+	}
195
+
196
+
197
+	/**
198
+	 * encodes string with PHP's base64 encoding
199
+	 *
200
+	 * @see http://php.net/manual/en/function.base64-encode.php
201
+	 * @param string $text_string the text to be encoded
202
+	 * @return string
203
+	 */
204
+	public function base64_string_encode($text_string = '')
205
+	{
206
+		// you give me nothing??? GET OUT !
207
+		if (empty($text_string) || ! $this->_use_base64_encode) {
208
+			return $text_string;
209
+		}
210
+		// encode
211
+		return base64_encode($text_string);
212
+	}
213
+
214
+
215
+	/**
216
+	 * decodes string that has been encoded with PHP's base64 encoding
217
+	 *
218
+	 * @see http://php.net/manual/en/function.base64-encode.php
219
+	 * @param string $encoded_string the text to be decoded
220
+	 * @return string
221
+	 * @throws RuntimeException
222
+	 */
223
+	public function base64_string_decode($encoded_string = '')
224
+	{
225
+		// you give me nothing??? GET OUT !
226
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
227
+			return $encoded_string;
228
+		}
229
+		// decode
230
+		$decoded_string = base64_decode($encoded_string);
231
+		if ($decoded_string === false) {
232
+			throw new RuntimeException(
233
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
234
+			);
235
+		}
236
+		return $decoded_string;
237
+	}
238
+
239
+
240
+	/**
241
+	 * encodes  url string with PHP's base64 encoding
242
+	 *
243
+	 * @see http://php.net/manual/en/function.base64-encode.php
244
+	 * @param string $text_string the text to be encoded
245
+	 * @return string
246
+	 */
247
+	public function base64_url_encode($text_string = '')
248
+	{
249
+		// you give me nothing??? GET OUT !
250
+		if (empty($text_string) || ! $this->_use_base64_encode) {
251
+			return $text_string;
252
+		}
253
+		// encode
254
+		$encoded_string = base64_encode($text_string);
255
+		// remove chars to make encoding more URL friendly
256
+		return strtr($encoded_string, '+/=', '-_,');
257
+	}
258
+
259
+
260
+	/**
261
+	 * decodes  url string that has been encoded with PHP's base64 encoding
262
+	 *
263
+	 * @see http://php.net/manual/en/function.base64-encode.php
264
+	 * @param string $encoded_string the text to be decoded
265
+	 * @return string
266
+	 * @throws RuntimeException
267
+	 */
268
+	public function base64_url_decode($encoded_string = '')
269
+	{
270
+		// you give me nothing??? GET OUT !
271
+		if (empty($encoded_string) || ! $this->valid_base_64($encoded_string)) {
272
+			return $encoded_string;
273
+		}
274
+		// replace previously removed characters
275
+		$encoded_string = strtr($encoded_string, '-_,', '+/=');
276
+		// decode
277
+		$decoded_string = base64_decode($encoded_string);
278
+		if ($decoded_string === false) {
279
+			throw new RuntimeException(
280
+				esc_html__('Base 64 decoding failed.', 'event_espresso')
281
+			);
282
+		}
283
+		return $decoded_string;
284
+	}
285
+
286
+
287
+	/**
288
+	 * encrypts data using PHP's openssl functions
289
+	 *
290
+	 * @param string $text_string the text to be encrypted
291
+	 * @param string $cipher_method
292
+	 * @param string $encryption_key
293
+	 * @return string
294
+	 * @throws RuntimeException
295
+	 */
296
+	protected function openssl_encrypt(
297
+		$text_string = '',
298
+		$cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
299
+		$encryption_key = ''
300
+	) {
301
+		// you give me nothing??? GET OUT !
302
+		if (empty($text_string)) {
303
+			return $text_string;
304
+		}
305
+		$this->cipher_method = $this->getCipherMethod($cipher_method);
306
+		// get initialization vector size
307
+		$iv_size = openssl_cipher_iv_length($this->cipher_method);
308
+		// generate initialization vector.
309
+		// The second parameter ("crypto_strong") is passed by reference,
310
+		// and is used to determines if the algorithm used was "cryptographically strong"
311
+		// openssl_random_pseudo_bytes() will toggle it to either true or false
312
+		$iv = openssl_random_pseudo_bytes($iv_size, $is_strong);
313
+		if ($iv === false || $is_strong === false) {
314
+			throw new RuntimeException(
315
+				esc_html__('Failed to generate OpenSSL initialization vector.', 'event_espresso')
316
+			);
317
+		}
318
+		// encrypt it
319
+		$encrypted_text = openssl_encrypt(
320
+			$text_string,
321
+			$this->cipher_method,
322
+			$this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
323
+			0,
324
+			$iv
325
+		);
326
+		// append the initialization vector
327
+		$encrypted_text .= EE_Encryption::OPENSSL_IV_DELIMITER . $iv;
328
+		// trim and maybe encode
329
+		return $this->_use_base64_encode
330
+			? trim(base64_encode($encrypted_text))
331
+			: trim($encrypted_text);
332
+	}
333
+
334
+
335
+	/**
336
+	 * Returns a cipher method that has been verified to work.
337
+	 * First checks if the cached cipher has been set already and if so, returns that.
338
+	 * Then tests the incoming default and returns that if it's good.
339
+	 * If not, then it retrieves the previously tested and saved cipher method.
340
+	 * But if that doesn't exist, then calls getAvailableCipherMethod()
341
+	 * to see what is available on the server, and returns the results.
342
+	 *
343
+	 * @param string $cipher_method
344
+	 * @return string
345
+	 * @throws RuntimeException
346
+	 */
347
+	protected function getCipherMethod($cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD)
348
+	{
349
+		if ($this->cipher_method !== '') {
350
+			return $this->cipher_method;
351
+		}
352
+		// verify that the default cipher method can produce an initialization vector
353
+		if (openssl_cipher_iv_length($cipher_method) === false) {
354
+			// nope? okay let's get what we found in the past to work
355
+			$cipher_method = get_option(EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME, '');
356
+			// oops... haven't tested available cipher methods yet
357
+			if ($cipher_method === '' || openssl_cipher_iv_length($cipher_method) === false) {
358
+				$cipher_method = $this->getAvailableCipherMethod($cipher_method);
359
+			}
360
+		}
361
+		return $cipher_method;
362
+	}
363
+
364
+
365
+	/**
366
+	 * @param string $cipher_method
367
+	 * @return string
368
+	 * @throws \RuntimeException
369
+	 */
370
+	protected function getAvailableCipherMethod($cipher_method)
371
+	{
372
+		// verify that the incoming cipher method can produce an initialization vector
373
+		if (openssl_cipher_iv_length($cipher_method) === false) {
374
+			// nope? then check the next cipher in the list of available cipher methods
375
+			$cipher_method = next($this->cipher_methods);
376
+			// what? there's no list? then generate that list and cache it,
377
+			if (empty($this->cipher_methods)) {
378
+				$this->cipher_methods = openssl_get_cipher_methods();
379
+				// then grab the first item from the list
380
+				$cipher_method = reset($this->cipher_methods);
381
+			}
382
+			if ($cipher_method === false) {
383
+				throw new RuntimeException(
384
+					esc_html__(
385
+						'OpenSSL support appears to be enabled on the server, but no cipher methods are available. Please contact the server administrator.',
386
+						'event_espresso'
387
+					)
388
+				);
389
+			}
390
+			// verify that the next cipher method works
391
+			return $this->getAvailableCipherMethod($cipher_method);
392
+		}
393
+		// if we've gotten this far, then we found an available cipher method that works
394
+		// so save that for next time
395
+		update_option(
396
+			EE_Encryption::OPENSSL_CIPHER_METHOD_OPTION_NAME,
397
+			$cipher_method
398
+		);
399
+		return $cipher_method;
400
+	}
401
+
402
+
403
+	/**
404
+	 * decrypts data that has been encrypted with PHP's openssl functions
405
+	 *
406
+	 * @param string $encrypted_text the text to be decrypted
407
+	 * @param string $cipher_method
408
+	 * @param string $encryption_key
409
+	 * @return string
410
+	 * @throws RuntimeException
411
+	 */
412
+	protected function openssl_decrypt(
413
+		$encrypted_text = '',
414
+		$cipher_method = EE_Encryption::OPENSSL_CIPHER_METHOD,
415
+		$encryption_key = ''
416
+	) {
417
+		// you give me nothing??? GET OUT !
418
+		if (empty($encrypted_text)) {
419
+			return $encrypted_text;
420
+		}
421
+		// decode
422
+		$encrypted_text = $this->valid_base_64($encrypted_text)
423
+			? $this->base64_url_decode($encrypted_text)
424
+			: $encrypted_text;
425
+		$encrypted_components = explode(
426
+			EE_Encryption::OPENSSL_IV_DELIMITER,
427
+			$encrypted_text,
428
+			2
429
+		);
430
+		// decrypt it
431
+		$decrypted_text = openssl_decrypt(
432
+			$encrypted_components[0],
433
+			$this->getCipherMethod($cipher_method),
434
+			$this->getDigestHashValue(EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key),
435
+			0,
436
+			$encrypted_components[1]
437
+		);
438
+		$decrypted_text = trim($decrypted_text);
439
+		return $decrypted_text;
440
+	}
441
+
442
+
443
+	/**
444
+	 * Computes the digest hash value using the specified digest method.
445
+	 * If that digest method fails to produce a valid hash value,
446
+	 * then we'll grab the next digest method and recursively try again until something works.
447
+	 *
448
+	 * @param string $digest_method
449
+	 * @param string $encryption_key
450
+	 * @return string
451
+	 * @throws RuntimeException
452
+	 */
453
+	protected function getDigestHashValue($digest_method = EE_Encryption::OPENSSL_DIGEST_METHOD, $encryption_key = '')
454
+	{
455
+		$encryption_key = $encryption_key !== ''
456
+			? $encryption_key
457
+			: $this->get_encryption_key();
458
+		$digest_hash_value = openssl_digest($encryption_key, $digest_method);
459
+		if ($digest_hash_value === false) {
460
+			return $this->getDigestHashValue($this->getDigestMethod());
461
+		}
462
+		return $digest_hash_value;
463
+	}
464
+
465
+
466
+	/**
467
+	 * Returns the NEXT element in the $digest_methods array.
468
+	 * If the $digest_methods array is empty, then we populate it
469
+	 * with the available values returned from openssl_get_md_methods().
470
+	 *
471
+	 * @return string
472
+	 * @throws \RuntimeException
473
+	 */
474
+	protected function getDigestMethod()
475
+	{
476
+		$digest_method = prev($this->digest_methods);
477
+		if (empty($this->digest_methods)) {
478
+			$this->digest_methods = openssl_get_md_methods();
479
+			$digest_method = end($this->digest_methods);
480
+		}
481
+		if ($digest_method === false) {
482
+			throw new RuntimeException(
483
+				esc_html__(
484
+					'OpenSSL support appears to be enabled on the server, but no digest methods are available. Please contact the server administrator.',
485
+					'event_espresso'
486
+				)
487
+			);
488
+		}
489
+		return $digest_method;
490
+	}
491
+
492
+
493
+	/**
494
+	 * encrypts data for acme servers that didn't bother to install PHP mcrypt
495
+	 *
496
+	 * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
497
+	 * @param string $text_string the text to be decrypted
498
+	 * @return string
499
+	 */
500
+	protected function acme_encrypt($text_string = '')
501
+	{
502
+		// you give me nothing??? GET OUT !
503
+		if (empty($text_string)) {
504
+			return $text_string;
505
+		}
506
+		$key_bits = str_split(
507
+			str_pad(
508
+				'',
509
+				strlen($text_string),
510
+				$this->get_encryption_key(),
511
+				STR_PAD_RIGHT
512
+			)
513
+		);
514
+		$string_bits = str_split($text_string);
515
+		foreach ($string_bits as $k => $v) {
516
+			$temp = ord($v) + ord($key_bits[ $k ]);
517
+			$string_bits[ $k ] = chr($temp > 255 ? ($temp - 256) : $temp);
518
+		}
519
+		$encrypted_text = implode('', $string_bits);
520
+		$encrypted_text .= EE_Encryption::ACME_ENCRYPTION_FLAG;
521
+		return $this->_use_base64_encode
522
+			? base64_encode($encrypted_text)
523
+			: $encrypted_text;
524
+	}
525
+
526
+
527
+	/**
528
+	 * decrypts data for acme servers that didn't bother to install PHP mcrypt
529
+	 *
530
+	 * @see http://stackoverflow.com/questions/800922/how-to-encrypt-string-without-mcrypt-library-in-php
531
+	 * @param string $encrypted_text the text to be decrypted
532
+	 * @return string
533
+	 * @throws RuntimeException
534
+	 */
535
+	protected function acme_decrypt($encrypted_text = '')
536
+	{
537
+		// you give me nothing??? GET OUT !
538
+		if (empty($encrypted_text)) {
539
+			return $encrypted_text;
540
+		}
541
+		// decode the data ?
542
+		$encrypted_text = $this->valid_base_64($encrypted_text)
543
+			? $this->base64_url_decode($encrypted_text)
544
+			: $encrypted_text;
545
+		$encrypted_text = substr($encrypted_text, 0, -4);
546
+		$key_bits = str_split(
547
+			str_pad(
548
+				'',
549
+				strlen($encrypted_text),
550
+				$this->get_encryption_key(),
551
+				STR_PAD_RIGHT
552
+			)
553
+		);
554
+		$string_bits = str_split($encrypted_text);
555
+		foreach ($string_bits as $k => $v) {
556
+			$temp = ord($v) - ord($key_bits[ $k ]);
557
+			$string_bits[ $k ] = chr($temp < 0 ? ($temp + 256) : $temp);
558
+		}
559
+		return implode('', $string_bits);
560
+	}
561
+
562
+
563
+	/**
564
+	 * @see http://stackoverflow.com/questions/2556345/detect-base64-encoding-in-php#30231906
565
+	 * @param $string
566
+	 * @return bool
567
+	 */
568
+	protected function valid_base_64($string)
569
+	{
570
+		// ensure data is a string
571
+		if (! is_string($string) || ! $this->_use_base64_encode) {
572
+			return false;
573
+		}
574
+		$decoded = base64_decode($string, true);
575
+		// Check if there is no invalid character in string
576
+		if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
577
+			return false;
578
+		}
579
+		// Decode the string in strict mode and send the response
580
+		if (! base64_decode($string, true)) {
581
+			return false;
582
+		}
583
+		// Encode and compare it to original one
584
+		return base64_encode($decoded) === $string;
585
+	}
586
+
587
+
588
+	/**
589
+	 * generate random string
590
+	 *
591
+	 * @see http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php
592
+	 * @param int $length number of characters for random string
593
+	 * @return string
594
+	 */
595
+	public function generate_random_string($length = 40)
596
+	{
597
+		$iterations = ceil($length / 40);
598
+		$random_string = '';
599
+		for ($i = 0; $i < $iterations; $i++) {
600
+			$random_string .= sha1(microtime(true) . mt_rand(10000, 90000));
601
+		}
602
+		$random_string = substr($random_string, 0, $length);
603
+		return $random_string;
604
+	}
605 605
 }
Please login to merge, or discard this patch.